Spaces:
Sleeping
Sleeping
Update main.py
Browse files
main.py
CHANGED
@@ -2,6 +2,12 @@ from fastapi import FastAPI, HTTPException
|
|
2 |
from fastapi.middleware.cors import CORSMiddleware
|
3 |
from pydantic import BaseModel
|
4 |
import pipe_line_obsei
|
|
|
|
|
|
|
|
|
|
|
|
|
5 |
|
6 |
# Định nghĩa model request body
|
7 |
class URLProcessRequest(BaseModel):
|
@@ -9,12 +15,74 @@ class URLProcessRequest(BaseModel):
|
|
9 |
primary_db: str # Tên database chính
|
10 |
primary_collection: str # Tên collection chính
|
11 |
backup_db: str # Tên database dự phòng
|
12 |
-
backup_collection: str
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
13 |
|
14 |
# Khởi tạo FastAPI
|
15 |
app = FastAPI(
|
16 |
-
title="
|
17 |
-
description="
|
18 |
swagger_ui_parameters={"syntaxHighlight.theme": "obsidian"},
|
19 |
version="1.0.0",
|
20 |
contact={
|
@@ -75,3 +143,65 @@ async def process_url_api(request: URLProcessRequest):
|
|
75 |
detail=f"An error occurred while processing the request: {str(e)}"
|
76 |
)
|
77 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
2 |
from fastapi.middleware.cors import CORSMiddleware
|
3 |
from pydantic import BaseModel
|
4 |
import pipe_line_obsei
|
5 |
+
import support_function as sf
|
6 |
+
from typing import Dict, Any
|
7 |
+
import json
|
8 |
+
import asyncio
|
9 |
+
from crawl4ai import AsyncWebCrawler
|
10 |
+
from crawl4ai.extraction_strategy import JsonCssExtractionStrategy
|
11 |
|
12 |
# Định nghĩa model request body
|
13 |
class URLProcessRequest(BaseModel):
|
|
|
15 |
primary_db: str # Tên database chính
|
16 |
primary_collection: str # Tên collection chính
|
17 |
backup_db: str # Tên database dự phòng
|
18 |
+
backup_collection: str
|
19 |
+
|
20 |
+
class SchemaReq(BaseModel):
|
21 |
+
schema: dict[str, Any]
|
22 |
+
url: str
|
23 |
+
|
24 |
+
class SchemaReqMain(BaseModel):
|
25 |
+
schema: dict[str, Any]
|
26 |
+
url: str
|
27 |
+
scroll: bool
|
28 |
+
category: str
|
29 |
+
|
30 |
+
class TimeProcessRequest(BaseModel):
|
31 |
+
target_time : str # Thời gian cần chuẩn hóa
|
32 |
+
|
33 |
+
async def return_json(schema: Dict[str, Any], url: str) -> Dict[str, Any]:
|
34 |
+
extraction_strategy = JsonCssExtractionStrategy(schema, verbose=True)
|
35 |
+
async with AsyncWebCrawler(always_by_pass_cache=True) as crawler:
|
36 |
+
result = await crawler.arun(
|
37 |
+
url=url,
|
38 |
+
exclude_external_links=True,
|
39 |
+
bypass_cache=True,
|
40 |
+
verbose=False,
|
41 |
+
warning=False,
|
42 |
+
extraction_strategy=extraction_strategy
|
43 |
+
)
|
44 |
+
# Parse nội dung đã crawl thành JSON
|
45 |
+
news_teasers = json.loads(result.extracted_content)
|
46 |
+
return news_teasers
|
47 |
+
|
48 |
+
|
49 |
+
async def return_json_main (schema: dict[str, Any], url: str, scroll: bool, category: str):
|
50 |
+
js_code = """
|
51 |
+
(async function() {
|
52 |
+
let lastHeight = 0;
|
53 |
+
while (document.body.scrollHeight !== lastHeight) {
|
54 |
+
lastHeight = document.body.scrollHeight;
|
55 |
+
window.scrollTo(0, document.body.scrollHeight);
|
56 |
+
await new Promise(resolve => setTimeout(resolve, 1000)); // Đợi 1 giây giữa mỗi lần cuộn
|
57 |
+
}
|
58 |
+
})();
|
59 |
+
""" if scroll else ""
|
60 |
+
|
61 |
+
extraction_strategy = JsonCssExtractionStrategy(schema, verbose=True)
|
62 |
+
async with AsyncWebCrawler(always_bypass_cache=True) as crawler:
|
63 |
+
result = await crawler.arun(
|
64 |
+
url=url,
|
65 |
+
extraction_strategy=extraction_strategy,
|
66 |
+
bypass_cache=True,
|
67 |
+
warning=False,
|
68 |
+
js_code=js_code
|
69 |
+
)
|
70 |
+
|
71 |
+
await asyncio.sleep(5)
|
72 |
+
news_teasers = json.loads(result.extracted_content)
|
73 |
+
|
74 |
+
if isinstance(news_teasers, list):
|
75 |
+
for item in news_teasers:
|
76 |
+
item["category"] = category
|
77 |
+
else:
|
78 |
+
print("Unexpected data format:", news_teasers)
|
79 |
+
return []
|
80 |
+
return news_teasers
|
81 |
|
82 |
# Khởi tạo FastAPI
|
83 |
app = FastAPI(
|
84 |
+
title="Obsei",
|
85 |
+
description="API để xử lý dữ liệu từ các nguồn web",
|
86 |
swagger_ui_parameters={"syntaxHighlight.theme": "obsidian"},
|
87 |
version="1.0.0",
|
88 |
contact={
|
|
|
143 |
detail=f"An error occurred while processing the request: {str(e)}"
|
144 |
)
|
145 |
|
146 |
+
# API cho hàm chuẩn hóa thời gian
|
147 |
+
@app.post("/api/v1/obsei/chuan_hoa_time/") # endpoint chuẩn hóa thời gian
|
148 |
+
async def chuan_hoa_time_api(request: TimeProcessRequest):
|
149 |
+
"""
|
150 |
+
API nhận chuỗi thời gian và chuẩn hóa thời gian theo định dạng mong muốn.
|
151 |
+
"""
|
152 |
+
try:
|
153 |
+
time_str = request.target_time # Bạn có thể thay đổi thuộc tính phù hợp
|
154 |
+
formatted_time = sf.chuan_hoa_time(time_str)
|
155 |
+
return {
|
156 |
+
"formatted_time": formatted_time
|
157 |
+
}
|
158 |
+
except Exception as e:
|
159 |
+
raise HTTPException(
|
160 |
+
status_code=500,
|
161 |
+
detail=f"An error occurred while processing the time: {str(e)}"
|
162 |
+
)
|
163 |
+
|
164 |
+
# API cho crawling với schema
|
165 |
+
@app.post("/api/v1/crawl/")
|
166 |
+
async def crawl_url(request: SchemaReq):
|
167 |
+
"""
|
168 |
+
API nhận request body chứa schema và URL, sau đó crawl và trả về dữ liệu.
|
169 |
+
"""
|
170 |
+
try:
|
171 |
+
# Lấy schema và URL từ request body
|
172 |
+
schema = request.schema
|
173 |
+
url = request.url
|
174 |
+
|
175 |
+
# Gọi hàm `return_json` để lấy dữ liệu đã crawl
|
176 |
+
data = await return_json(schema, url) # Gọi async function mà không cần asyncio.run()
|
177 |
+
|
178 |
+
return {"status": "success", "data": data}
|
179 |
+
|
180 |
+
except Exception as e:
|
181 |
+
raise HTTPException(
|
182 |
+
status_code=500,
|
183 |
+
detail=f"An error occurred while processing the request: {str(e)}"
|
184 |
+
)
|
185 |
+
|
186 |
+
@app.post("/api/v1/crawl_main/")
|
187 |
+
async def crawl_url(request: SchemaReqMain):
|
188 |
+
"""
|
189 |
+
API nhận request body chứa schema và URL, sau đó crawl và trả về dữ liệu.
|
190 |
+
"""
|
191 |
+
try:
|
192 |
+
# Lấy schema và URL từ request body
|
193 |
+
schema = request.schema
|
194 |
+
url = request.url
|
195 |
+
scroll = request.scroll
|
196 |
+
category = request.category
|
197 |
+
|
198 |
+
# Gọi hàm `return_json` để lấy dữ liệu đã crawl
|
199 |
+
data = await return_json_main(schema, url,scroll,category ) # Gọi async function mà không cần asyncio.run()
|
200 |
+
|
201 |
+
return {"status": "success", "data": data}
|
202 |
+
|
203 |
+
except Exception as e:
|
204 |
+
raise HTTPException(
|
205 |
+
status_code=500,
|
206 |
+
detail=f"An error occurred while processing the request: {str(e)}"
|
207 |
+
)
|