Spaces:
Sleeping
Sleeping
| import json | |
| from typing import Any, Dict | |
| import asyncio | |
| from datetime import datetime, timedelta | |
| import re | |
| from crawl4ai import AsyncWebCrawler | |
| from crawl4ai.extraction_strategy import JsonCssExtractionStrategy | |
| schema_short= { | |
| "name": "VnExpress", | |
| "baseSelector": "div.sidebar-1", | |
| "fields": [ | |
| { | |
| "name": "description", | |
| "selector": "article p.Normal", | |
| "type": "list", | |
| "fields": [ | |
| {"name": "description", "type": "text"}, | |
| ] | |
| }, | |
| { | |
| "name": "genres", | |
| "selector": "div.header-content ul.breadcrumb li a", | |
| "type": "list", | |
| "fields": [ | |
| {"name": "genres", "type": "text"}, | |
| ] | |
| } | |
| ] | |
| } | |
| url = "https://vnexpress.net/co-nen-bo-30-trieu-dong-de-hoc-them-mot-bang-o-tuoi-40-4825599.html" | |
| async def return_json(schema: Dict[str, Any], url: str) -> Dict[str, Any]: | |
| extraction_strategy = JsonCssExtractionStrategy(schema, verbose=True) | |
| async with AsyncWebCrawler(always_by_pass_cache=True) as crawler: | |
| result = await crawler.arun( | |
| url=url, | |
| exclude_external_links=True, | |
| bypass_cache=True, | |
| verbose=False, | |
| warning=False, | |
| extraction_strategy=extraction_strategy | |
| ) | |
| news_teasers = json.loads(result.extracted_content) | |
| return news_teasers | |
| from datetime import datetime | |
| import re | |
| def chuan_hoa_time(time_str): | |
| days_map = { | |
| "thứ bảy": "Saturday", | |
| "chủ nhật": "Sunday", | |
| "thứ hai": "Monday", | |
| "thứ ba": "Tuesday", | |
| "thứ tư": "Wednesday", | |
| "thứ năm": "Thursday", | |
| "thứ sáu": "Friday", | |
| } | |
| month_map = { | |
| "tháng 1": "January", "tháng 2": "February", "tháng 3": "March", | |
| "tháng 4": "April", "tháng 5": "May", "tháng 6": "June", | |
| "tháng 7": "July", "tháng 8": "August", "tháng 9": "September", | |
| "tháng 10": "October", "tháng 11": "November", "tháng 12": "December" | |
| } | |
| # Làm sạch chuỗi thời gian | |
| if isinstance(time_str, datetime): | |
| # Nếu là đối tượng datetime, chuyển sang chuỗi | |
| time_str = time_str.strftime('%Y-%m-%d %H:%M:%S') | |
| elif not isinstance(time_str, str): | |
| # Nếu không phải là chuỗi hoặc datetime, trả về chuỗi rỗng | |
| return "" | |
| time_str = time_str.lower().strip() | |
| now = datetime.now() | |
| if "phút trước" in time_str: | |
| minutes = int(re.search(r"(\d+)", time_str).group(1)) | |
| time_result = now - timedelta(minutes=minutes) | |
| return time_result.strftime("%d/%m/%Y %H:%M") | |
| elif "giờ trước" in time_str: | |
| hours = int(re.search(r"(\d+)", time_str).group(1)) | |
| time_result = now - timedelta(hours=hours) | |
| return time_result.strftime("%d/%m/%Y %H:%M") | |
| elif "hôm qua" in time_str: | |
| time_result = now - timedelta(days=1) | |
| return time_result.strftime("%d/%m/%Y %H:%M") | |
| elif "ngày trước" in time_str: | |
| days = int(re.search(r"(\d+)", time_str).group(1)) | |
| time_result = now - timedelta(days=days) | |
| return time_result.strftime("%d/%m/%Y %H:%M") | |
| # Sửa các lỗi chính tả thông thường | |
| time_str = re.sub(r"\s?\(gmt[+\-]\d{1,2}\)", "", time_str).strip() # Loại bỏ múi giờ | |
| time_str = time_str.replace("|", "") # Loại bỏ ký tự phân cách '|' | |
| # time_str = time_str.replace(",", "") # Loại bỏ dấu phẩy nếu có | |
| time_str = re.sub(r"\s+", " ", time_str).strip() # Loại bỏ khoảng trắng thừa | |
| # Nếu chuỗi có dạng "20241202 15:44", cần chèn dấu "/" vào | |
| if re.match(r"^\d{8} \d{2}:\d{2}$", time_str): | |
| time_str = f"{time_str[:4]}/{time_str[4:6]}/{time_str[6:8]} {time_str[9:]}" | |
| # Thêm dấu phẩy nếu thiếu sau ngày | |
| if re.match(r"^[a-z]+ \d{2}/\d{2}/\d{4} \d{2}:\d{2}$", time_str): | |
| time_str = time_str.replace(" ", ", ", 1) # Thêm dấu phẩy sau ngày | |
| # Thay thế tháng tiếng Việt thành tiếng Anh | |
| for vietnamese_month, english_month in month_map.items(): | |
| time_str = time_str.replace(vietnamese_month, english_month) | |
| # Thay thế ngày trong tuần | |
| for vietnamese_day, english_day in days_map.items(): | |
| time_str = time_str.replace(vietnamese_day, english_day) | |
| # Định dạng chuỗi thời gian chuẩn | |
| formats = [ | |
| "%A, %d/%m/%Y %H:%M", # Monday, 2/12/2024 11:33 | |
| "%Y-%m-%d %H:%M:%S", # 2024-11-29 16:01:23 | |
| "%Y-%m-%dT%H:%M:%S", # 2024-11-30T10:20:00 | |
| "%A, %d/%m/%Y - %H:%M", # Monday, 2/12/2024 - 11:33 | |
| "%A, %d/%m/%Y, %H:%M", # Monday, 2/12/2024, 11:33 | |
| "%Y-%m-%d %H:%M", # 2024-12-01 08:00 | |
| "%H:%M, %d/%m/%Y", # 10:45, 01/12/2024 | |
| "%d %B %Y %H:%M", # 2 December 2024 11:33 | |
| "%d/%m/%Y %H:%M", # 02/12/2024 15:22 | |
| "%d %b %Y %H:%M", # 2 Dec 2024 11:33 | |
| "%d/%m/%Y %H:%M:%S", # 02/12/2024 15:22:00 | |
| "%A, %d/%m/%Y %H:%M %z", # Monday, 02/12/2024 10:08 +0700 | |
| "%b %d, %Y %H:%M", # Dec 2, 2024 15:22 | |
| "%d tháng %m, %Y | %H:%M", # 2 tháng 12, 2024 | 15:10 | |
| "%A, %d/%m/%Y - %H:%M", # thứ hai, 02/12/2024 - 15:40 | |
| "%Y,%m,%d %H:%M", # 2024,12,02 15:44 | |
| "%A, %d/%m/%Y , %H:%M" # Monday, 02/12/2024 , 16:01 | |
| ] | |
| for fmt in formats: | |
| try: | |
| dt =datetime.strptime(time_str, fmt) | |
| return dt | |
| except ValueError: | |
| continue | |
| raise ValueError(f"Không thể chuẩn hóa chuỗi thời gian: {time_str}") |