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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import pandas as pd
|
| 3 |
+
import requests
|
| 4 |
+
from bs4 import BeautifulSoup
|
| 5 |
+
from datetime import datetime, timedelta
|
| 6 |
+
import re
|
| 7 |
+
from concurrent.futures import ThreadPoolExecutor, as_completed
|
| 8 |
+
import threading
|
| 9 |
+
import warnings
|
| 10 |
+
import hashlib
|
| 11 |
+
import time
|
| 12 |
+
from urllib.parse import urlparse, urljoin
|
| 13 |
+
from PIL import Image
|
| 14 |
+
import imagehash
|
| 15 |
+
from io import BytesIO
|
| 16 |
+
import dateutil.parser as date_parser
|
| 17 |
+
from datasets import load_dataset, Dataset, DatasetDict
|
| 18 |
+
from huggingface_hub import login
|
| 19 |
+
import os
|
| 20 |
+
|
| 21 |
+
warnings.filterwarnings('ignore')
|
| 22 |
+
|
| 23 |
+
HF_TOKEN = os.environ.get("HF_TOKEN")
|
| 24 |
+
HF_DATASET = "dxedline/historical_research_data"
|
| 25 |
+
SCRAPE_WORKERS = 30
|
| 26 |
+
IMAGE_WORKERS = 20
|
| 27 |
+
MAX_CELL_CHARS = 49000
|
| 28 |
+
MAX_WORD_LIMIT = 150000
|
| 29 |
+
MIN_IMAGE_SIZE = 400
|
| 30 |
+
IMAGE_SIMILARITY_THRESHOLD = 8
|
| 31 |
+
MIN_RELEVANCE_SCORE = 30
|
| 32 |
+
|
| 33 |
+
if HF_TOKEN:
|
| 34 |
+
login(token=HF_TOKEN)
|
| 35 |
+
|
| 36 |
+
seen_urls = set()
|
| 37 |
+
seen_hashes = set()
|
| 38 |
+
seen_image_hashes = {}
|
| 39 |
+
url_lock = threading.Lock()
|
| 40 |
+
hash_lock = threading.Lock()
|
| 41 |
+
image_hash_lock = threading.Lock()
|
| 42 |
+
|
| 43 |
+
def clean_text(text):
|
| 44 |
+
text = re.sub(r'\s+', ' ', text)
|
| 45 |
+
text = re.sub(r'[\x00-\x1f\x7f-\x9f]', '', text)
|
| 46 |
+
text = ''.join(char for char in text if char.isprintable() or char.isspace())
|
| 47 |
+
text = re.sub(r'[^\w\s\.,;:!?\-\'\"()\[\]{}@#$%&*+=<>/\\|`~]', '', text)
|
| 48 |
+
return text.strip()
|
| 49 |
+
|
| 50 |
+
def truncate_to_limit(text, max_words=MAX_WORD_LIMIT, max_chars=MAX_CELL_CHARS * 4):
|
| 51 |
+
words = text.split()
|
| 52 |
+
if len(words) > max_words:
|
| 53 |
+
text = ' '.join(words[:max_words])
|
| 54 |
+
if len(text) > max_chars:
|
| 55 |
+
text = text[:max_chars]
|
| 56 |
+
return text
|
| 57 |
+
|
| 58 |
+
def get_content_hash(text):
|
| 59 |
+
return hashlib.md5(text[:3000].encode()).hexdigest()
|
| 60 |
+
|
| 61 |
+
def get_domain(url):
|
| 62 |
+
try:
|
| 63 |
+
return urlparse(url).netloc.replace('www.', '')
|
| 64 |
+
except:
|
| 65 |
+
return ""
|
| 66 |
+
|
| 67 |
+
def normalize_url(url):
|
| 68 |
+
try:
|
| 69 |
+
parsed = urlparse(url)
|
| 70 |
+
return f"{parsed.netloc}{parsed.path}".lower().rstrip('/')
|
| 71 |
+
except:
|
| 72 |
+
return url
|
| 73 |
+
|
| 74 |
+
def parse_article_date(date_str):
|
| 75 |
+
if not date_str:
|
| 76 |
+
return None
|
| 77 |
+
try:
|
| 78 |
+
return date_parser.parse(date_str, fuzzy=True)
|
| 79 |
+
except:
|
| 80 |
+
return None
|
| 81 |
+
|
| 82 |
+
def is_date_valid_for_incident(article_date, incident_date):
|
| 83 |
+
if not article_date:
|
| 84 |
+
return True
|
| 85 |
+
if not incident_date:
|
| 86 |
+
return True
|
| 87 |
+
try:
|
| 88 |
+
incident_dt = datetime.strptime(incident_date, "%Y-%m-%d") if isinstance(incident_date, str) else incident_date
|
| 89 |
+
if article_date >= incident_dt:
|
| 90 |
+
return True
|
| 91 |
+
days_before = (incident_dt - article_date).days
|
| 92 |
+
return days_before <= 7
|
| 93 |
+
except:
|
| 94 |
+
return True
|
| 95 |
+
|
| 96 |
+
def calculate_relevance_score(content, query, title, page_title=''):
|
| 97 |
+
content_lower = content.lower()
|
| 98 |
+
query_lower = query.lower()
|
| 99 |
+
title_lower = title.lower()
|
| 100 |
+
page_title_lower = page_title.lower() if page_title else ''
|
| 101 |
+
|
| 102 |
+
common_words = {'the', 'a', 'an', 'and', 'or', 'but', 'in', 'on', 'at', 'to', 'for', 'of', 'with', 'by', 'from', 'as', 'is', 'was', 'are', 'were', 'been', 'be', 'have', 'has', 'had', 'do', 'does', 'did'}
|
| 103 |
+
query_words = {w for w in query_lower.split() if w not in common_words and len(w) > 2}
|
| 104 |
+
title_words = {w for w in title_lower.split() if w not in common_words and len(w) > 2}
|
| 105 |
+
|
| 106 |
+
if not query_words and not title_words:
|
| 107 |
+
return 100
|
| 108 |
+
|
| 109 |
+
score = 0
|
| 110 |
+
|
| 111 |
+
if query_words:
|
| 112 |
+
query_matches = sum(1 for word in query_words if word in content_lower)
|
| 113 |
+
score += (query_matches / len(query_words)) * 40
|
| 114 |
+
|
| 115 |
+
if page_title_lower:
|
| 116 |
+
title_query_matches = sum(1 for word in query_words if word in page_title_lower)
|
| 117 |
+
score += (title_query_matches / len(query_words)) * 20
|
| 118 |
+
|
| 119 |
+
if title_words:
|
| 120 |
+
title_matches = sum(1 for word in title_words if word in content_lower)
|
| 121 |
+
score += (title_matches / len(title_words)) * 25
|
| 122 |
+
|
| 123 |
+
if page_title_lower:
|
| 124 |
+
page_title_matches = sum(1 for word in title_words if word in page_title_lower)
|
| 125 |
+
score += (page_title_matches / len(title_words)) * 15
|
| 126 |
+
|
| 127 |
+
content_words = content_lower.split()
|
| 128 |
+
if content_words:
|
| 129 |
+
keyword_density = sum(content_lower.count(word) for word in query_words) / len(content_words)
|
| 130 |
+
score += min(keyword_density * 1000, 10)
|
| 131 |
+
|
| 132 |
+
if page_title_lower and query_words:
|
| 133 |
+
exact_match_bonus = sum(5 for word in query_words if word in page_title_lower)
|
| 134 |
+
score += min(exact_match_bonus, 10)
|
| 135 |
+
|
| 136 |
+
return min(score, 100)
|
| 137 |
+
|
| 138 |
+
def calculate_image_quality_score(width, height, file_size_kb):
|
| 139 |
+
resolution_score = min((width * height) / 1000000 * 50, 50)
|
| 140 |
+
size_score = min(file_size_kb / 100 * 30, 30)
|
| 141 |
+
aspect_ratio = max(width, height) / min(width, height)
|
| 142 |
+
aspect_score = 20 if aspect_ratio < 2 else 10
|
| 143 |
+
return resolution_score + size_score + aspect_score
|
| 144 |
+
|
| 145 |
+
def is_likely_photograph(img_url, img, img_tag=None):
|
| 146 |
+
try:
|
| 147 |
+
width, height = img.size
|
| 148 |
+
if width < MIN_IMAGE_SIZE or height < MIN_IMAGE_SIZE:
|
| 149 |
+
return False
|
| 150 |
+
|
| 151 |
+
if max(width, height) / min(width, height) > 4:
|
| 152 |
+
return False
|
| 153 |
+
|
| 154 |
+
if img.format not in ['JPEG', 'JPG', 'PNG']:
|
| 155 |
+
return False
|
| 156 |
+
|
| 157 |
+
url_lower = img_url.lower()
|
| 158 |
+
exclude_patterns = [
|
| 159 |
+
'icon', 'logo', 'button', 'banner', 'avatar', 'thumbnail', 'thumb',
|
| 160 |
+
'sprite', 'badge', 'emoji', 'clipart', 'vector', 'graphic',
|
| 161 |
+
'illustration', 'drawing', 'chart', 'graph', 'diagram',
|
| 162 |
+
'placeholder', 'default', 'profile', 'user', 'author',
|
| 163 |
+
'bg', 'background', 'pattern', 'header', 'footer', 'sidebar',
|
| 164 |
+
'ai-generated', 'midjourney', 'dalle', 'stable-diffusion',
|
| 165 |
+
'youtube.com', 'ytimg.com', 'youtu.be', 'yt3.ggpht.com',
|
| 166 |
+
'gravatar', 'favicon', 'edit', 'composite', 'collage',
|
| 167 |
+
'istockphoto.com', 'istock.com', 'gettyimages.com', 'shutterstock.com',
|
| 168 |
+
'adobestock.com', 'stock.adobe.com', 'dreamstime.com', 'alamy.com',
|
| 169 |
+
'123rf.com', 'depositphotos.com', 'pond5.com', 'pixabay.com',
|
| 170 |
+
'pexels.com', 'unsplash.com', 'freepik.com', 'canva.com'
|
| 171 |
+
]
|
| 172 |
+
|
| 173 |
+
if any(pattern in url_lower for pattern in exclude_patterns):
|
| 174 |
+
return False
|
| 175 |
+
|
| 176 |
+
img_rgb = img.convert('RGB')
|
| 177 |
+
colors = img_rgb.getcolors(maxcolors=1000000)
|
| 178 |
+
if colors and len(colors) < 150:
|
| 179 |
+
return False
|
| 180 |
+
|
| 181 |
+
pixels = list(img_rgb.getdata())
|
| 182 |
+
if len(pixels) > 100:
|
| 183 |
+
sample = pixels[::len(pixels)//100][:100]
|
| 184 |
+
if len(set(sample)) < 20:
|
| 185 |
+
return False
|
| 186 |
+
|
| 187 |
+
return True
|
| 188 |
+
except:
|
| 189 |
+
return False
|
| 190 |
+
|
| 191 |
+
def get_image_hash(img):
|
| 192 |
+
try:
|
| 193 |
+
return str(imagehash.average_hash(img, hash_size=16))
|
| 194 |
+
except:
|
| 195 |
+
return None
|
| 196 |
+
|
| 197 |
+
def check_and_store_image_hash(img_hash, img_data):
|
| 198 |
+
with image_hash_lock:
|
| 199 |
+
for existing_hash, existing_data in seen_image_hashes.items():
|
| 200 |
+
try:
|
| 201 |
+
hash_diff = abs(imagehash.hex_to_hash(existing_hash) - imagehash.hex_to_hash(img_hash))
|
| 202 |
+
if hash_diff <= IMAGE_SIMILARITY_THRESHOLD:
|
| 203 |
+
existing_quality = existing_data['quality_score']
|
| 204 |
+
new_quality = img_data['quality_score']
|
| 205 |
+
if new_quality > existing_quality:
|
| 206 |
+
del seen_image_hashes[existing_hash]
|
| 207 |
+
seen_image_hashes[img_hash] = img_data
|
| 208 |
+
return True, True
|
| 209 |
+
return True, False
|
| 210 |
+
except:
|
| 211 |
+
continue
|
| 212 |
+
seen_image_hashes[img_hash] = img_data
|
| 213 |
+
return False, True
|
| 214 |
+
|
| 215 |
+
def process_single_image(img_url, caption, alt_text, source_url, event_id, date_found):
|
| 216 |
+
try:
|
| 217 |
+
url_lower = img_url.lower()
|
| 218 |
+
|
| 219 |
+
exclude_domains = [
|
| 220 |
+
'youtube.com', 'ytimg.com', 'youtu.be', 'yt3.ggpht.com',
|
| 221 |
+
'istockphoto.com', 'istock.com', 'gettyimages.com', 'shutterstock.com',
|
| 222 |
+
'adobestock.com', 'stock.adobe.com', 'dreamstime.com', 'alamy.com',
|
| 223 |
+
'123rf.com', 'depositphotos.com', 'pond5.com', 'pixabay.com',
|
| 224 |
+
'pexels.com', 'unsplash.com', 'freepik.com', 'canva.com'
|
| 225 |
+
]
|
| 226 |
+
|
| 227 |
+
if any(domain in url_lower for domain in exclude_domains):
|
| 228 |
+
return None
|
| 229 |
+
|
| 230 |
+
headers = {
|
| 231 |
+
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
|
| 232 |
+
'Referer': source_url,
|
| 233 |
+
'Accept': 'image/avif,image/webp,image/apng,image/*,*/*;q=0.8'
|
| 234 |
+
}
|
| 235 |
+
|
| 236 |
+
img_response = requests.get(img_url, headers=headers, timeout=10, stream=True)
|
| 237 |
+
if img_response.status_code != 200:
|
| 238 |
+
return None
|
| 239 |
+
|
| 240 |
+
content_length = img_response.headers.get('content-length')
|
| 241 |
+
if content_length and int(content_length) < 10000:
|
| 242 |
+
return None
|
| 243 |
+
|
| 244 |
+
img_bytes = img_response.content
|
| 245 |
+
file_size_kb = len(img_bytes) / 1024
|
| 246 |
+
|
| 247 |
+
if file_size_kb < 10:
|
| 248 |
+
return None
|
| 249 |
+
|
| 250 |
+
img = Image.open(BytesIO(img_bytes))
|
| 251 |
+
|
| 252 |
+
if not is_likely_photograph(img_url, img):
|
| 253 |
+
return None
|
| 254 |
+
|
| 255 |
+
img_hash = get_image_hash(img)
|
| 256 |
+
if not img_hash:
|
| 257 |
+
return None
|
| 258 |
+
|
| 259 |
+
width, height = img.size
|
| 260 |
+
quality_score = calculate_image_quality_score(width, height, file_size_kb)
|
| 261 |
+
|
| 262 |
+
img_data = {
|
| 263 |
+
'event_id': event_id,
|
| 264 |
+
'image_url': img_url,
|
| 265 |
+
'caption': clean_text(caption) if caption else '',
|
| 266 |
+
'alt_text': clean_text(alt_text) if alt_text else '',
|
| 267 |
+
'date': date_found,
|
| 268 |
+
'source_url': source_url,
|
| 269 |
+
'width': width,
|
| 270 |
+
'height': height,
|
| 271 |
+
'file_size_kb': round(file_size_kb, 2),
|
| 272 |
+
'quality_score': quality_score
|
| 273 |
+
}
|
| 274 |
+
|
| 275 |
+
is_similar, should_keep = check_and_store_image_hash(img_hash, img_data)
|
| 276 |
+
|
| 277 |
+
if should_keep:
|
| 278 |
+
return img_data
|
| 279 |
+
|
| 280 |
+
return None
|
| 281 |
+
except:
|
| 282 |
+
return None
|
| 283 |
+
|
| 284 |
+
def extract_images_from_page(soup, base_url, source_url, event_id, date_found):
|
| 285 |
+
img_tags = soup.find_all('img')
|
| 286 |
+
images_data = []
|
| 287 |
+
|
| 288 |
+
with ThreadPoolExecutor(max_workers=IMAGE_WORKERS) as executor:
|
| 289 |
+
futures = []
|
| 290 |
+
for img_tag in img_tags:
|
| 291 |
+
img_url = img_tag.get('src') or img_tag.get('data-src') or img_tag.get('data-lazy-src')
|
| 292 |
+
if not img_url:
|
| 293 |
+
continue
|
| 294 |
+
|
| 295 |
+
img_url = urljoin(base_url, img_url)
|
| 296 |
+
|
| 297 |
+
if img_url.startswith('data:') or img_url.endswith(('.svg', '.gif')):
|
| 298 |
+
continue
|
| 299 |
+
|
| 300 |
+
alt_text = img_tag.get('alt', '')
|
| 301 |
+
caption = ''
|
| 302 |
+
|
| 303 |
+
parent = img_tag.find_parent('figure')
|
| 304 |
+
if parent:
|
| 305 |
+
figcaption = parent.find('figcaption')
|
| 306 |
+
if figcaption:
|
| 307 |
+
caption = figcaption.get_text(strip=True)
|
| 308 |
+
|
| 309 |
+
future = executor.submit(process_single_image, img_url, caption, alt_text, source_url, event_id, date_found)
|
| 310 |
+
futures.append(future)
|
| 311 |
+
|
| 312 |
+
for future in as_completed(futures):
|
| 313 |
+
result = future.result()
|
| 314 |
+
if result:
|
| 315 |
+
images_data.append(result)
|
| 316 |
+
|
| 317 |
+
return images_data
|
| 318 |
+
|
| 319 |
+
def deep_scrape_content(response, source_url):
|
| 320 |
+
try:
|
| 321 |
+
soup = BeautifulSoup(response.content, 'lxml')
|
| 322 |
+
except:
|
| 323 |
+
soup = BeautifulSoup(response.content, 'html.parser')
|
| 324 |
+
|
| 325 |
+
for tag in soup(['script', 'style', 'nav', 'footer', 'header', 'aside', 'iframe', 'noscript']):
|
| 326 |
+
tag.decompose()
|
| 327 |
+
|
| 328 |
+
content_parts = []
|
| 329 |
+
title = soup.find('h1')
|
| 330 |
+
if title:
|
| 331 |
+
content_parts.append(title.get_text(strip=True))
|
| 332 |
+
|
| 333 |
+
main_content = soup.find('article') or soup.find('main') or soup.find('div', id='content')
|
| 334 |
+
|
| 335 |
+
if not main_content:
|
| 336 |
+
main_content = soup.find('body')
|
| 337 |
+
|
| 338 |
+
if main_content:
|
| 339 |
+
for elem in main_content.find_all(['p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'blockquote', 'li']):
|
| 340 |
+
text = elem.get_text(separator=' ', strip=True)
|
| 341 |
+
if len(text) > 5:
|
| 342 |
+
content_parts.append(text)
|
| 343 |
+
|
| 344 |
+
full_content = ' '.join(content_parts)
|
| 345 |
+
cleaned = clean_text(full_content)
|
| 346 |
+
truncated = truncate_to_limit(cleaned)
|
| 347 |
+
|
| 348 |
+
return truncated, soup
|
| 349 |
+
|
| 350 |
+
def extract_date(soup, response_text):
|
| 351 |
+
time_tag = soup.find('time')
|
| 352 |
+
if time_tag:
|
| 353 |
+
date_val = time_tag.get('datetime') or time_tag.get_text(strip=True)
|
| 354 |
+
if date_val:
|
| 355 |
+
return date_val
|
| 356 |
+
|
| 357 |
+
meta_props = ['article:published_time', 'datePublished', 'publication_date']
|
| 358 |
+
for prop in meta_props:
|
| 359 |
+
meta = soup.find('meta', attrs={'property': prop}) or soup.find('meta', attrs={'name': prop})
|
| 360 |
+
if meta and meta.get('content'):
|
| 361 |
+
return meta.get('content')
|
| 362 |
+
|
| 363 |
+
return ''
|
| 364 |
+
|
| 365 |
+
def scrape_url(url, event_id, incident_date, query, title):
|
| 366 |
+
try:
|
| 367 |
+
normalized = normalize_url(url)
|
| 368 |
+
with url_lock:
|
| 369 |
+
if normalized in seen_urls:
|
| 370 |
+
return None
|
| 371 |
+
seen_urls.add(normalized)
|
| 372 |
+
|
| 373 |
+
domain = get_domain(url)
|
| 374 |
+
|
| 375 |
+
headers = {
|
| 376 |
+
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
|
| 377 |
+
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9',
|
| 378 |
+
}
|
| 379 |
+
|
| 380 |
+
response = requests.get(url, headers=headers, timeout=20, allow_redirects=True, verify=False)
|
| 381 |
+
if response.status_code != 200:
|
| 382 |
+
return None
|
| 383 |
+
|
| 384 |
+
content, soup = deep_scrape_content(response, url)
|
| 385 |
+
if len(content) < 100:
|
| 386 |
+
return None
|
| 387 |
+
|
| 388 |
+
content_hash = get_content_hash(content)
|
| 389 |
+
with hash_lock:
|
| 390 |
+
if content_hash in seen_hashes:
|
| 391 |
+
return None
|
| 392 |
+
seen_hashes.add(content_hash)
|
| 393 |
+
|
| 394 |
+
page_title = ''
|
| 395 |
+
h1_tag = soup.find('h1')
|
| 396 |
+
if h1_tag:
|
| 397 |
+
page_title = h1_tag.get_text(strip=True)
|
| 398 |
+
|
| 399 |
+
relevance_score = calculate_relevance_score(content, query, title, page_title)
|
| 400 |
+
|
| 401 |
+
if relevance_score < MIN_RELEVANCE_SCORE:
|
| 402 |
+
return None
|
| 403 |
+
|
| 404 |
+
date_found = extract_date(soup, response.text)
|
| 405 |
+
if date_found:
|
| 406 |
+
article_date = parse_article_date(date_found)
|
| 407 |
+
if article_date and not is_date_valid_for_incident(article_date, incident_date):
|
| 408 |
+
return None
|
| 409 |
+
|
| 410 |
+
images_data = extract_images_from_page(soup, response.url, url, event_id, date_found)
|
| 411 |
+
|
| 412 |
+
return {
|
| 413 |
+
'event_id': event_id,
|
| 414 |
+
'url': url,
|
| 415 |
+
'content': content,
|
| 416 |
+
'date': date_found,
|
| 417 |
+
'relevance_score': relevance_score,
|
| 418 |
+
'images': images_data
|
| 419 |
+
}
|
| 420 |
+
except:
|
| 421 |
+
return None
|
| 422 |
+
|
| 423 |
+
def search_and_scrape_event(event_id, query, title, incident_date):
|
| 424 |
+
all_links = []
|
| 425 |
+
|
| 426 |
+
try:
|
| 427 |
+
from duckduckgo_search import DDGS
|
| 428 |
+
ddgs = DDGS()
|
| 429 |
+
|
| 430 |
+
sources = ['wikipedia.org', 'britannica.com', 'history.com']
|
| 431 |
+
for source in sources:
|
| 432 |
+
try:
|
| 433 |
+
results = ddgs.text(f"{query} site:{source}", max_results=10)
|
| 434 |
+
for result in results:
|
| 435 |
+
link = result.get('href') or result.get('link')
|
| 436 |
+
if link:
|
| 437 |
+
all_links.append(link)
|
| 438 |
+
time.sleep(1)
|
| 439 |
+
except:
|
| 440 |
+
pass
|
| 441 |
+
|
| 442 |
+
try:
|
| 443 |
+
results = ddgs.text(query, max_results=50)
|
| 444 |
+
for result in results:
|
| 445 |
+
link = result.get('href') or result.get('link')
|
| 446 |
+
if link:
|
| 447 |
+
all_links.append(link)
|
| 448 |
+
except:
|
| 449 |
+
pass
|
| 450 |
+
except:
|
| 451 |
+
pass
|
| 452 |
+
|
| 453 |
+
all_links = list(dict.fromkeys(all_links))
|
| 454 |
+
|
| 455 |
+
scraped_articles = []
|
| 456 |
+
all_images = []
|
| 457 |
+
|
| 458 |
+
with ThreadPoolExecutor(max_workers=SCRAPE_WORKERS) as executor:
|
| 459 |
+
futures = {executor.submit(scrape_url, link, event_id, incident_date, query, title): link for link in all_links}
|
| 460 |
+
|
| 461 |
+
for future in as_completed(futures):
|
| 462 |
+
result = future.result()
|
| 463 |
+
if result:
|
| 464 |
+
scraped_articles.append({
|
| 465 |
+
'event_id': result['event_id'],
|
| 466 |
+
'url': result['url'],
|
| 467 |
+
'content': result['content'],
|
| 468 |
+
'date': result['date'],
|
| 469 |
+
'relevance_score': result['relevance_score']
|
| 470 |
+
})
|
| 471 |
+
|
| 472 |
+
all_images.extend(result['images'])
|
| 473 |
+
|
| 474 |
+
return scraped_articles, all_images
|
| 475 |
+
|
| 476 |
+
def save_to_hf_dataset(articles, images, event_info):
|
| 477 |
+
try:
|
| 478 |
+
dataset = load_dataset(HF_DATASET)
|
| 479 |
+
|
| 480 |
+
if articles:
|
| 481 |
+
articles_df = pd.DataFrame(articles)
|
| 482 |
+
articles_df['event_title'] = event_info['title']
|
| 483 |
+
articles_df['event_query'] = event_info['query']
|
| 484 |
+
articles_df['incident_date'] = event_info['incident_date']
|
| 485 |
+
|
| 486 |
+
new_articles = Dataset.from_pandas(articles_df)
|
| 487 |
+
if 'articles' in dataset:
|
| 488 |
+
dataset['articles'] = concatenate_datasets([dataset['articles'], new_articles])
|
| 489 |
+
else:
|
| 490 |
+
dataset['articles'] = new_articles
|
| 491 |
+
|
| 492 |
+
if images:
|
| 493 |
+
images_df = pd.DataFrame(images)
|
| 494 |
+
images_df['event_title'] = event_info['title']
|
| 495 |
+
|
| 496 |
+
new_images = Dataset.from_pandas(images_df)
|
| 497 |
+
if 'images' in dataset:
|
| 498 |
+
dataset['images'] = concatenate_datasets([dataset['images'], new_images])
|
| 499 |
+
else:
|
| 500 |
+
dataset['images'] = new_images
|
| 501 |
+
|
| 502 |
+
dataset.push_to_hub(HF_DATASET)
|
| 503 |
+
return True
|
| 504 |
+
except Exception as e:
|
| 505 |
+
return False
|
| 506 |
+
|
| 507 |
+
def process_event(event_id_input):
|
| 508 |
+
try:
|
| 509 |
+
df = pd.read_csv('events.csv')
|
| 510 |
+
|
| 511 |
+
if event_id_input:
|
| 512 |
+
event = df[df['id'] == int(event_id_input)].iloc[0]
|
| 513 |
+
else:
|
| 514 |
+
try:
|
| 515 |
+
dataset = load_dataset(HF_DATASET)
|
| 516 |
+
processed_ids = set()
|
| 517 |
+
if 'articles' in dataset:
|
| 518 |
+
processed_ids.update(dataset['articles']['event_id'])
|
| 519 |
+
next_id = 1
|
| 520 |
+
while next_id in processed_ids:
|
| 521 |
+
next_id += 1
|
| 522 |
+
event = df[df['id'] == next_id].iloc[0]
|
| 523 |
+
except:
|
| 524 |
+
event = df.iloc[0]
|
| 525 |
+
|
| 526 |
+
event_id = event['id']
|
| 527 |
+
query = event['query']
|
| 528 |
+
title = event['title']
|
| 529 |
+
incident_date = event['incident_date']
|
| 530 |
+
|
| 531 |
+
status = f"Processing Event {event_id}: {title}\n\n"
|
| 532 |
+
|
| 533 |
+
articles, images = search_and_scrape_event(event_id, query, title, incident_date)
|
| 534 |
+
|
| 535 |
+
status += f"Found {len(articles)} articles and {len(images)} images\n\n"
|
| 536 |
+
|
| 537 |
+
event_info = {
|
| 538 |
+
'title': title,
|
| 539 |
+
'query': query,
|
| 540 |
+
'incident_date': incident_date
|
| 541 |
+
}
|
| 542 |
+
|
| 543 |
+
success = save_to_hf_dataset(articles, images, event_info)
|
| 544 |
+
|
| 545 |
+
if success:
|
| 546 |
+
status += f"✓ Successfully saved to dataset\n"
|
| 547 |
+
else:
|
| 548 |
+
status += f"✗ Failed to save to dataset\n"
|
| 549 |
+
|
| 550 |
+
return status
|
| 551 |
+
|
| 552 |
+
except Exception as e:
|
| 553 |
+
return f"Error: {str(e)}"
|
| 554 |
+
|
| 555 |
+
def auto_process():
|
| 556 |
+
while True:
|
| 557 |
+
try:
|
| 558 |
+
result = process_event(None)
|
| 559 |
+
print(result)
|
| 560 |
+
time.sleep(300)
|
| 561 |
+
except:
|
| 562 |
+
time.sleep(60)
|
| 563 |
+
|
| 564 |
+
with gr.Blocks() as demo:
|
| 565 |
+
gr.Markdown("# Historical Event Scraper")
|
| 566 |
+
gr.Markdown("Automatically scrapes and processes historical events from events.csv")
|
| 567 |
+
|
| 568 |
+
with gr.Row():
|
| 569 |
+
event_id = gr.Number(label="Event ID (leave empty for auto)", precision=0)
|
| 570 |
+
process_btn = gr.Button("Process Event")
|
| 571 |
+
|
| 572 |
+
output = gr.Textbox(label="Status", lines=10)
|
| 573 |
+
|
| 574 |
+
process_btn.click(process_event, inputs=[event_id], outputs=[output])
|
| 575 |
+
|
| 576 |
+
gr.Markdown("### Auto-processing runs every 5 minutes")
|
| 577 |
+
|
| 578 |
+
if __name__ == "__main__":
|
| 579 |
+
threading.Thread(target=auto_process, daemon=True).start()
|
| 580 |
+
demo.launch()
|