multilingual-scraper / src /extractor.py
arki3212's picture
Upload folder using huggingface_hub
c40402f verified
Raw History Blame Contribute Delete
5.32 kB
import trafilatura
from bs4 import BeautifulSoup
from langdetect import detect, DetectorFactory
from typing import Dict, Optional
from datetime import datetime
import json
import re
DetectorFactory.seed = 0
class ArticleExtractor:
def _extract_date_from_url(self, url: str) -> Optional[str]:
patterns = [r"/(\d{4})/(\d{2})/(\d{2})/", r"/(\d{4})-(\d{2})-(\d{2})/", r"(\d{8})"]
for pattern in patterns:
match = re.search(pattern, url)
if match:
g = match.groups()
if len(g) == 3: return f"{g[0]}-{g[1]}-{g[2]}"
if len(g) == 1: return f"{g[0][:4]}-{g[0][4:6]}-{g[0][6:8]}"
return None
def _get_fallback_metadata(self, html_content: str) -> Dict[str, Optional[str]]:
meta = {"title": None, "date": None, "image": None}
try:
soup = BeautifulSoup(html_content, "html.parser")
if soup.h1: meta["title"] = soup.h1.get_text().strip()
elif soup.title: meta["title"] = soup.title.get_text().strip()
# Date extraction
date_tags = [("meta", {"property": "article:published_time"}), ("meta", {"name": "pubdate"}), ("meta", {"property": "og:pubdate"})]
for tag, attrs in date_tags:
found = soup.find(tag, attrs)
if found:
candidate = found.get("content")
if candidate and not candidate.startswith("PT") and len(candidate) > 6:
meta["date"] = candidate
break
# Image extraction
img_tags = [("meta", {"property": "og:image"}), ("meta", {"name": "twitter:image"}), ("meta", {"property": "og:image:url"})]
for tag, attrs in img_tags:
found = soup.find(tag, attrs)
if found:
meta["image"] = found.get("content")
break
# Fallback: Scrape the first real image in the article body (Task 3)
if not meta["image"]:
for img in soup.find_all("img"):
src = img.get("src")
if src and src.startswith("http"):
# Filter out tracking pixels, icons, loaders, and ad banners
src_lower = src.lower()
if any(x in src_lower for x in ["icon", "logo", "avatar", "tracking", "pixel", "loader", "ad_", "/ads/", "sprite"]):
continue
# Filter out small decoration icons
width = img.get("width")
height = img.get("height")
try:
if width and int(width) < 60: continue
if height and int(height) < 60: continue
except ValueError:
pass
meta["image"] = src
break
if not meta["date"]:
time_tags = soup.find_all("time", {"datetime": True})
for t in time_tags:
dt = t.get("datetime")
if dt and re.match(r"\d{4}-\d{2}-\d{2}", dt):
meta["date"] = dt
break
except: pass
return meta
def extract(self, html_content: str, url: str) -> Optional[Dict]:
downloaded = trafilatura.extract(html_content, include_comments=False, include_tables=True, output_format="json")
data = {}
if downloaded:
try: data = json.loads(downloaded)
except: pass
text = data.get("text")
if not text or len(text) < 100: return None
pub_date = data.get("date") or self._extract_date_from_url(url)
title = data.get("title")
if not pub_date or not title:
fallback = self._get_fallback_metadata(html_content)
title = title or fallback["title"]
pub_date = pub_date or fallback["date"]
image = fallback.get("image")
else:
fallback = self._get_fallback_metadata(html_content)
image = fallback.get("image")
if pub_date:
try:
from dateutil import parser
from datetime import timezone
dt = parser.parse(pub_date)
if dt.tzinfo is None: dt = dt.replace(tzinfo=timezone.utc)
age = (datetime.now(dt.tzinfo) - dt).total_seconds()
if age > 604800 or age < -3600: return None
except: return None
else: return None
try: lang = detect(text)
except: lang = "unknown"
return {
"url": url,
"title": title,
"content": text,
"published_at": pub_date,
"language": lang,
"image_url": image,
"scraped_at": datetime.utcnow().isoformat() + "Z"
}
async def process_url(self, scraper, url: str, source_name: str, client) -> Optional[Dict]:
html = await scraper.fetch_url(url, client)
if not html: return None
article = self.extract(html, url)
if article: article["source"] = source_name
return article