dxedline commited on
Commit
73c5b6c
·
verified ·
1 Parent(s): d581c3b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +411 -593
app.py CHANGED
@@ -1,647 +1,465 @@
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, quote_plus
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, concatenate_datasets
18
- from huggingface_hub import login, HfApi
19
- import os
20
-
21
- warnings.filterwarnings('ignore')
22
- requests.packages.urllib3.disable_warnings()
23
-
24
- HF_TOKEN = os.environ.get("HF_TOKEN")
25
- HF_DATASET = "dxedline/historical_research_data"
26
- SCRAPE_WORKERS = 15
27
- IMAGE_WORKERS = 10
28
- MAX_CELL_CHARS = 49000
29
- MAX_WORD_LIMIT = 150000
30
- MIN_IMAGE_SIZE = 400
31
- IMAGE_SIMILARITY_THRESHOLD = 8
32
- MIN_RELEVANCE_SCORE = 25
33
-
34
- if HF_TOKEN:
35
- login(token=HF_TOKEN)
36
-
37
- seen_urls = set()
38
- seen_hashes = set()
39
- seen_image_hashes = {}
40
- url_lock = threading.Lock()
41
- hash_lock = threading.Lock()
42
- image_hash_lock = threading.Lock()
43
-
44
- def clean_text(text):
45
- text = re.sub(r'\s+', ' ', text)
46
- text = re.sub(r'[\x00-\x1f\x7f-\x9f]', '', text)
47
- text = ''.join(char for char in text if char.isprintable() or char.isspace())
48
- text = re.sub(r'[^\w\s\.,;:!?\-\'\"()\[\]{}@#$%&*+=<>/\\|`~]', '', text)
49
- return text.strip()
50
-
51
- def truncate_to_limit(text, max_words=MAX_WORD_LIMIT, max_chars=MAX_CELL_CHARS * 4):
52
- words = text.split()
53
- if len(words) > max_words:
54
- text = ' '.join(words[:max_words])
55
- if len(text) > max_chars:
56
- text = text[:max_chars]
57
- return text
58
-
59
- def get_content_hash(text):
60
- return hashlib.md5(text[:3000].encode()).hexdigest()
61
-
62
- def get_domain(url):
63
- try:
64
- return urlparse(url).netloc.replace('www.', '')
65
- except:
66
- return ""
67
-
68
- def normalize_url(url):
69
- try:
70
- parsed = urlparse(url)
71
- return f"{parsed.netloc}{parsed.path}".lower().rstrip('/')
72
- except:
73
- return url
74
-
75
- def parse_article_date(date_str):
76
- if not date_str:
77
- return None
78
- try:
79
- return date_parser.parse(date_str, fuzzy=True)
80
- except:
81
- return None
82
-
83
- def is_date_valid_for_incident(article_date, incident_date):
84
- if not article_date or not incident_date:
85
- return True
86
- try:
87
- incident_dt = datetime.strptime(str(incident_date), "%Y-%m-%d")
88
- if article_date >= incident_dt:
89
- return True
90
- days_before = (incident_dt - article_date).days
91
- return days_before <= 365
92
- except:
93
- return True
94
 
95
- def calculate_relevance_score(content, query, title, page_title=''):
96
- content_lower = content.lower()
97
- query_lower = query.lower()
98
- title_lower = title.lower()
99
- page_title_lower = page_title.lower() if page_title else ''
100
-
101
- 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'}
102
- query_words = {w for w in query_lower.split() if w not in common_words and len(w) > 2}
103
- title_words = {w for w in title_lower.split() if w not in common_words and len(w) > 2}
104
-
105
- if not query_words and not title_words:
106
- return 100
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
107
 
108
- score = 0
 
 
 
 
109
 
110
- if query_words:
111
- query_matches = sum(1 for word in query_words if word in content_lower)
112
- score += (query_matches / len(query_words)) * 40
113
-
114
- if page_title_lower:
115
- title_query_matches = sum(1 for word in query_words if word in page_title_lower)
116
- score += (title_query_matches / len(query_words)) * 20
 
 
 
 
117
 
118
- if title_words:
119
- title_matches = sum(1 for word in title_words if word in content_lower)
120
- score += (title_matches / len(title_words)) * 25
121
-
122
- if page_title_lower:
123
- page_title_matches = sum(1 for word in title_words if word in page_title_lower)
124
- score += (page_title_matches / len(title_words)) * 15
 
 
 
 
125
 
126
- return min(score, 100)
127
-
128
- def calculate_image_quality_score(width, height, file_size_kb):
129
- resolution_score = min((width * height) / 1000000 * 50, 50)
130
- size_score = min(file_size_kb / 100 * 30, 30)
131
- aspect_ratio = max(width, height) / min(width, height)
132
- aspect_score = 20 if aspect_ratio < 2 else 10
133
- return resolution_score + size_score + aspect_score
134
-
135
- def is_likely_photograph(img_url, img):
136
- try:
137
- width, height = img.size
138
- if width < MIN_IMAGE_SIZE or height < MIN_IMAGE_SIZE:
139
- return False
140
-
141
- if max(width, height) / min(width, height) > 4:
142
- return False
143
-
144
- if img.format not in ['JPEG', 'JPG', 'PNG']:
145
- return False
146
-
147
- url_lower = img_url.lower()
148
- exclude_patterns = [
149
- 'icon', 'logo', 'button', 'banner', 'avatar', 'thumbnail', 'thumb',
150
- 'sprite', 'badge', 'emoji', 'youtube.com', 'ytimg.com',
151
- 'istockphoto.com', 'gettyimages.com', 'shutterstock.com'
152
  ]
153
 
154
- if any(pattern in url_lower for pattern in exclude_patterns):
155
- return False
 
 
 
 
 
 
156
 
157
- return True
158
- except:
159
- return False
160
-
161
- def get_image_hash(img):
162
- try:
163
- return str(imagehash.average_hash(img, hash_size=16))
164
- except:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
165
  return None
166
-
167
- def check_and_store_image_hash(img_hash, img_data):
168
- with image_hash_lock:
169
- for existing_hash, existing_data in list(seen_image_hashes.items()):
170
- try:
171
- hash_diff = abs(imagehash.hex_to_hash(existing_hash) - imagehash.hex_to_hash(img_hash))
172
- if hash_diff <= IMAGE_SIMILARITY_THRESHOLD:
173
- return False
174
- except:
175
- continue
176
- seen_image_hashes[img_hash] = img_data
177
- return True
178
-
179
- def process_single_image(img_url, caption, alt_text, source_url, event_id, date_found):
180
- try:
181
- headers = {
182
- 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
183
- 'Referer': source_url,
184
- }
185
 
186
- img_response = requests.get(img_url, headers=headers, timeout=10, stream=True, verify=False)
187
- if img_response.status_code != 200:
188
  return None
189
 
190
- img_bytes = img_response.content
191
- file_size_kb = len(img_bytes) / 1024
192
 
193
- if file_size_kb < 10:
 
194
  return None
195
 
196
- img = Image.open(BytesIO(img_bytes))
197
-
198
- if not is_likely_photograph(img_url, img):
199
  return None
200
 
201
- img_hash = get_image_hash(img)
202
- if not img_hash:
203
- return None
204
 
205
- width, height = img.size
206
- quality_score = calculate_image_quality_score(width, height, file_size_kb)
207
-
208
- img_data = {
209
- 'event_id': int(event_id),
210
- 'image_url': img_url,
211
- 'caption': clean_text(caption) if caption else '',
212
- 'alt_text': clean_text(alt_text) if alt_text else '',
213
- 'date': date_found or '',
214
- 'source_url': source_url,
215
- 'width': int(width),
216
- 'height': int(height),
217
- 'file_size_kb': float(round(file_size_kb, 2)),
218
- 'quality_score': float(quality_score)
219
- }
220
 
221
- if check_and_store_image_hash(img_hash, img_data):
222
- return img_data
 
223
 
224
- return None
225
- except:
226
- return None
227
 
228
- def extract_images_from_page(soup, base_url, source_url, event_id, date_found):
229
- img_tags = soup.find_all('img')
230
- images_data = []
 
 
 
231
 
232
- with ThreadPoolExecutor(max_workers=IMAGE_WORKERS) as executor:
233
- futures = []
234
- for img_tag in img_tags[:20]:
235
- img_url = img_tag.get('src') or img_tag.get('data-src')
236
- if not img_url:
237
- continue
238
-
239
- img_url = urljoin(base_url, img_url)
240
-
241
- if img_url.startswith('data:') or img_url.endswith(('.svg', '.gif')):
242
- continue
243
-
244
- alt_text = img_tag.get('alt', '')
245
- caption = ''
246
-
247
- parent = img_tag.find_parent('figure')
248
- if parent:
249
- figcaption = parent.find('figcaption')
250
- if figcaption:
251
- caption = figcaption.get_text(strip=True)
252
-
253
- future = executor.submit(process_single_image, img_url, caption, alt_text, source_url, event_id, date_found)
254
- futures.append(future)
255
 
256
- for future in as_completed(futures):
257
- result = future.result()
258
- if result:
259
- images_data.append(result)
260
-
261
- return images_data
262
-
263
- def deep_scrape_content(response):
264
- try:
265
- soup = BeautifulSoup(response.content, 'lxml')
266
- except:
267
- soup = BeautifulSoup(response.content, 'html.parser')
268
-
269
- for tag in soup(['script', 'style', 'nav', 'footer', 'header', 'aside', 'iframe']):
270
- tag.decompose()
271
-
272
- content_parts = []
273
- title = soup.find('h1')
274
- if title:
275
- content_parts.append(title.get_text(strip=True))
276
-
277
- main_content = soup.find('article') or soup.find('main') or soup.find('div', id='content')
278
-
279
- if not main_content:
280
- main_content = soup.find('body')
281
-
282
- if main_content:
283
- for elem in main_content.find_all(['p', 'h2', 'h3', 'h4', 'h5', 'blockquote', 'li']):
284
- text = elem.get_text(separator=' ', strip=True)
285
- if len(text) > 10:
286
- content_parts.append(text)
287
-
288
- full_content = ' '.join(content_parts)
289
- cleaned = clean_text(full_content)
290
- truncated = truncate_to_limit(cleaned)
291
-
292
- return truncated, soup
293
-
294
- def extract_date(soup):
295
- time_tag = soup.find('time')
296
- if time_tag:
297
- date_val = time_tag.get('datetime') or time_tag.get_text(strip=True)
298
- if date_val:
299
- return date_val
300
-
301
- for prop in ['article:published_time', 'datePublished']:
302
- meta = soup.find('meta', attrs={'property': prop}) or soup.find('meta', attrs={'name': prop})
303
- if meta and meta.get('content'):
304
- return meta.get('content')
305
-
306
- return ''
307
-
308
- def scrape_url(url, event_id, incident_date, query, title):
309
- try:
310
- normalized = normalize_url(url)
311
- with url_lock:
312
- if normalized in seen_urls:
313
- return None
314
- seen_urls.add(normalized)
315
-
316
- headers = {
317
- 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
318
- }
319
-
320
- response = requests.get(url, headers=headers, timeout=15, verify=False)
321
- if response.status_code != 200:
322
- return None
323
-
324
- content, soup = deep_scrape_content(response)
325
- if len(content) < 200:
326
- return None
327
-
328
- content_hash = get_content_hash(content)
329
- with hash_lock:
330
- if content_hash in seen_hashes:
331
- return None
332
- seen_hashes.add(content_hash)
333
-
334
- page_title = soup.find('h1')
335
- page_title = page_title.get_text(strip=True) if page_title else ''
336
-
337
- relevance_score = calculate_relevance_score(content, query, title, page_title)
338
 
339
- if relevance_score < MIN_RELEVANCE_SCORE:
340
- return None
341
-
342
- date_found = extract_date(soup)
 
 
 
343
 
344
- images_data = extract_images_from_page(soup, response.url, url, event_id, date_found)
345
-
346
- return {
347
- 'event_id': int(event_id),
348
- 'url': url,
349
- 'content': content,
350
- 'date': date_found or '',
351
- 'relevance_score': float(relevance_score),
352
- 'images': images_data,
353
- 'domain': get_domain(url)
354
- }
355
- except:
356
- return None
357
-
358
- def search_duckduckgo_html(query, max_results=100):
359
- links = []
360
- try:
361
- headers = {
362
- 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
363
- 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
364
- 'Accept-Language': 'en-US,en;q=0.9',
365
- 'Accept-Encoding': 'gzip, deflate',
366
- 'DNT': '1',
367
- 'Connection': 'keep-alive',
368
- 'Upgrade-Insecure-Requests': '1'
369
- }
370
 
371
- encoded_query = quote_plus(query)
372
- search_url = f"https://html.duckduckgo.com/html/?q={encoded_query}"
373
-
374
- response = requests.get(search_url, headers=headers, timeout=15)
375
- soup = BeautifulSoup(response.content, 'html.parser')
376
-
377
- for result in soup.find_all('a', class_='result__a'):
378
- href = result.get('href')
379
- if href:
380
- if href.startswith('//duckduckgo.com/l/?'):
381
- actual_url = href.split('uddg=')[1].split('&')[0] if 'uddg=' in href else None
382
- if actual_url:
383
- from urllib.parse import unquote
384
- decoded_url = unquote(actual_url)
385
- if decoded_url.startswith('http') and 'youtube.com' not in decoded_url.lower():
386
- links.append(decoded_url)
387
- if len(links) >= max_results:
388
- break
389
-
390
- time.sleep(2)
391
- except Exception as e:
392
- print(f"HTML search error: {e}")
393
 
394
- return links
395
-
396
- def search_duckduckgo_api(query, timelimit=None, max_results=100):
397
- links = []
398
- try:
399
- from duckduckgo_search import DDGS
400
 
401
- ddgs = DDGS(timeout=20)
 
 
 
 
402
 
403
- if timelimit:
404
- results = ddgs.text(query, timelimit=timelimit, max_results=max_results)
405
- else:
406
- results = ddgs.text(query, max_results=max_results)
407
 
408
- for result in results:
409
- link = result.get('href') or result.get('link')
410
- if link and 'youtube.com' not in link.lower():
411
- links.append(link)
412
 
413
- time.sleep(2)
414
- except Exception as e:
415
- print(f"API search error: {e}")
416
-
417
- return links
418
-
419
- def search_combined(query, timelimit=None, max_results=100):
420
- all_links = []
421
-
422
- api_links = search_duckduckgo_api(query, timelimit, max_results)
423
- all_links.extend(api_links)
424
-
425
- if len(api_links) < 10:
426
- html_links = search_duckduckgo_html(query, max_results)
427
- all_links.extend(html_links)
428
-
429
- return list(dict.fromkeys(all_links))
430
-
431
- def search_and_scrape_event(event_id, query, title, incident_date):
432
- all_links = []
433
-
434
- yield f"Searching all time for query: {query}...\n"
435
- query_all = search_combined(query, timelimit=None, max_results=100)
436
- all_links.extend(query_all)
437
- yield f"Found {len(query_all)} results\n"
438
-
439
- yield f"Searching all time for title: {title}...\n"
440
- title_all = search_combined(title, timelimit=None, max_results=100)
441
- all_links.extend(title_all)
442
- yield f"Found {len(title_all)} results\n"
443
-
444
- yield f"Searching past year: {query}...\n"
445
- year_links = search_combined(query, timelimit='y', max_results=80)
446
- all_links.extend(year_links)
447
- yield f"Found {len(year_links)} results from past year\n"
448
-
449
- yield f"Searching past year: {title}...\n"
450
- year_title = search_combined(title, timelimit='y', max_results=80)
451
- all_links.extend(year_title)
452
- yield f"Found {len(year_title)} results\n"
453
-
454
- yield f"Searching past month: {query}...\n"
455
- month_links = search_combined(query, timelimit='m', max_results=60)
456
- all_links.extend(month_links)
457
- yield f"Found {len(month_links)} results from past month\n"
458
-
459
- yield f"Searching past week: {query}...\n"
460
- week_links = search_combined(query, timelimit='w', max_results=40)
461
- all_links.extend(week_links)
462
- yield f"Found {len(week_links)} results from past week\n"
463
-
464
- all_links = list(dict.fromkeys(all_links))
465
- yield f"\nTotal unique links collected: {len(all_links)}\n\n"
466
-
467
- scraped_articles = []
468
- all_images = []
469
-
470
- yield "Scraping articles...\n"
471
-
472
- with ThreadPoolExecutor(max_workers=SCRAPE_WORKERS) as executor:
473
- futures = {executor.submit(scrape_url, link, event_id, incident_date, query, title): link for link in all_links}
474
-
475
- completed = 0
476
- for future in as_completed(futures):
477
- completed += 1
478
- result = future.result()
479
- if result:
480
- scraped_articles.append({
481
- 'event_id': result['event_id'],
482
- 'url': result['url'],
483
- 'content': result['content'],
484
- 'date': result['date'],
485
- 'relevance_score': result['relevance_score'],
486
- 'domain': result['domain']
487
- })
488
- all_images.extend(result['images'])
489
- yield f"Progress: {completed}/{len(all_links)} | Found: {len(scraped_articles)} articles, {len(all_images)} images\n"
490
 
491
- return scraped_articles, all_images
492
-
493
- def save_to_hf_dataset(articles, images, event_info):
494
- try:
495
- api = HfApi()
496
-
497
- articles_dict = {
498
- 'event_id': [a['event_id'] for a in articles],
499
- 'url': [a['url'] for a in articles],
500
- 'content': [a['content'] for a in articles],
501
- 'date': [a['date'] for a in articles],
502
- 'relevance_score': [a['relevance_score'] for a in articles],
503
- 'domain': [a['domain'] for a in articles],
504
- 'event_title': [event_info['title']] * len(articles),
505
- 'event_query': [event_info['query']] * len(articles),
506
- 'incident_date': [event_info['incident_date']] * len(articles)
507
- }
508
 
509
- images_dict = {
510
- 'event_id': [i['event_id'] for i in images],
511
- 'image_url': [i['image_url'] for i in images],
512
- 'caption': [i['caption'] for i in images],
513
- 'alt_text': [i['alt_text'] for i in images],
514
- 'date': [i['date'] for i in images],
515
- 'source_url': [i['source_url'] for i in images],
516
- 'width': [i['width'] for i in images],
517
- 'height': [i['height'] for i in images],
518
- 'file_size_kb': [i['file_size_kb'] for i in images],
519
- 'quality_score': [i['quality_score'] for i in images],
520
- 'event_title': [event_info['title']] * len(images)
521
- }
522
 
523
- try:
524
- existing_articles = load_dataset(HF_DATASET, split='articles', token=HF_TOKEN)
525
- new_articles = Dataset.from_dict(articles_dict)
526
- combined_articles = concatenate_datasets([existing_articles, new_articles])
527
- except:
528
- combined_articles = Dataset.from_dict(articles_dict)
529
 
530
- try:
531
- existing_images = load_dataset(HF_DATASET, split='images', token=HF_TOKEN)
532
- new_images = Dataset.from_dict(images_dict)
533
- combined_images = concatenate_datasets([existing_images, new_images])
534
- except:
535
- combined_images = Dataset.from_dict(images_dict)
536
 
537
- combined_articles.push_to_hub(HF_DATASET, split='articles', token=HF_TOKEN)
538
- combined_images.push_to_hub(HF_DATASET, split='images', token=HF_TOKEN)
539
 
540
- return True
541
- except Exception as e:
542
- print(f"Save error: {e}")
543
- return False
544
-
545
- def get_next_event_id():
546
- try:
547
- dataset = load_dataset(HF_DATASET, split='articles', token=HF_TOKEN)
548
- if len(dataset) > 0:
549
- processed_ids = set(dataset['event_id'])
550
- next_id = 1
551
- while next_id in processed_ids:
552
- next_id += 1
553
- return next_id
554
- except:
555
- pass
556
- return 1
557
-
558
- def process_event(event_id_input):
559
- try:
560
- df = pd.read_csv('events.csv')
561
-
562
- if event_id_input and event_id_input > 0:
563
- event = df[df['id'] == int(event_id_input)].iloc[0]
564
- else:
565
- next_id = get_next_event_id()
566
- if next_id > len(df):
567
- yield "All events processed!"
568
- return
569
- event = df[df['id'] == next_id].iloc[0]
570
-
571
- event_id = int(event['id'])
572
- query = str(event['query'])
573
- title = str(event['title'])
574
- incident_date = str(event['incident_date'])
575
-
576
- status = f"Processing Event {event_id}: {title}\n\n"
577
- yield status
578
-
579
- articles = []
580
- images = []
581
-
582
- for update in search_and_scrape_event(event_id, query, title, incident_date):
583
- status += update
584
- yield status
585
- if isinstance(update, tuple):
586
- articles, images = update
587
-
588
- if not isinstance(articles, list):
589
- articles, images = articles
590
-
591
- status += f"\n\nFinal count: {len(articles)} articles, {len(images)} images\n"
592
- yield status
593
-
594
- if not articles and not images:
595
- status += "\n✗ No data to save\n"
596
- yield status
597
- return
598
 
599
- event_info = {
600
- 'title': title,
 
 
 
 
 
601
  'query': query,
602
- 'incident_date': incident_date
 
 
 
 
603
  }
604
 
605
- status += "Saving to dataset...\n"
606
- yield status
607
-
608
- success = save_to_hf_dataset(articles, images, event_info)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
609
 
610
- if success:
611
- status += f"✓ Successfully saved to {HF_DATASET}\n"
612
- else:
613
- status += f"✗ Failed to save to dataset\n"
614
 
615
- yield status
 
 
 
 
 
616
 
617
- except Exception as e:
618
- yield f"Error: {str(e)}"
619
-
620
- def auto_process():
621
- while True:
622
- try:
623
- result_gen = process_event(None)
624
- for result in result_gen:
625
- print(result)
626
- time.sleep(600)
627
- except Exception as e:
628
- print(f"Auto error: {e}")
629
- time.sleep(120)
630
-
631
- with gr.Blocks(title="Historical Event Scraper") as demo:
632
- gr.Markdown("# Historical Event Scraper")
633
- gr.Markdown("Scrapes historical events from multiple search engines")
634
-
635
- with gr.Row():
636
- event_id = gr.Number(label="Event ID (leave empty for auto)", precision=0, value=None)
637
- process_btn = gr.Button("Process Event", variant="primary")
638
 
639
- output = gr.Textbox(label="Status", lines=20, max_lines=25, autoscroll=True)
 
 
 
 
640
 
641
- gr.Markdown(f"Dataset: [{HF_DATASET}](https://huggingface.co/datasets/{HF_DATASET})")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
642
 
643
- process_btn.click(process_event, inputs=[event_id], outputs=[output])
 
644
 
645
  if __name__ == "__main__":
646
- threading.Thread(target=auto_process, daemon=True).start()
647
- demo.queue().launch(server_name="0.0.0.0", server_port=7860)
 
1
+ import asyncio
2
+ import aiohttp
3
+ from duckduckgo_search import DDGS
4
  from bs4 import BeautifulSoup
5
+ from urllib.parse import urljoin, urlparse
 
 
 
 
6
  import hashlib
7
+ from datetime import datetime
8
+ import json
9
+ from pathlib import Path
10
  import time
11
+ import re
12
  from PIL import Image
 
13
  from io import BytesIO
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
 
15
+ class RateLimitedSearcher:
16
+ def __init__(self):
17
+ self.last_search = 0
18
+ self.min_interval = 2.5
19
+ self.lock = asyncio.Lock()
20
+
21
+ async def search(self, query, max_results=20, timelimit=None):
22
+ async with self.lock:
23
+ elapsed = time.time() - self.last_search
24
+ if elapsed < self.min_interval:
25
+ await asyncio.sleep(self.min_interval - elapsed)
26
+
27
+ try:
28
+ ddgs = DDGS()
29
+ results = list(ddgs.text(query, max_results=max_results, timelimit=timelimit))
30
+ self.last_search = time.time()
31
+ return results
32
+ except Exception as e:
33
+ print(f"Search error: {e}")
34
+ self.last_search = time.time()
35
+ await asyncio.sleep(5.0)
36
+ return []
37
+
38
+ class ContentScraper:
39
+ def __init__(self, max_workers=40):
40
+ self.max_workers = max_workers
41
+ self.seen_urls = set()
42
+ self.seen_images = set()
43
+ self.session = None
44
+
45
+ async def get_session(self):
46
+ if self.session is None:
47
+ timeout = aiohttp.ClientTimeout(total=30)
48
+ self.session = aiohttp.ClientSession(
49
+ timeout=timeout,
50
+ headers={
51
+ 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
52
+ }
53
+ )
54
+ return self.session
55
+
56
+ async def close(self):
57
+ if self.session:
58
+ await self.session.close()
59
+
60
+ def url_hash(self, url):
61
+ normalized = re.sub(r'[?#].*$', '', url)
62
+ return hashlib.md5(normalized.encode()).hexdigest()
63
+
64
+ def image_hash(self, content):
65
+ try:
66
+ img = Image.open(BytesIO(content))
67
+ img = img.resize((8, 8), Image.Resampling.LANCZOS).convert('L')
68
+ pixels = list(img.getdata())
69
+ avg = sum(pixels) / len(pixels)
70
+ bits = ''.join('1' if p > avg else '0' for p in pixels)
71
+ return bits
72
+ except:
73
+ return hashlib.md5(content).hexdigest()
74
 
75
+ def is_similar_image(self, hash1, hash2):
76
+ if len(hash1) == len(hash2) == 64:
77
+ diff = sum(c1 != c2 for c1, c2 in zip(hash1, hash2))
78
+ return diff < 5
79
+ return hash1 == hash2
80
 
81
+ def is_valid_image(self, content):
82
+ try:
83
+ img = Image.open(BytesIO(content))
84
+ width, height = img.size
85
+ if width < 200 or height < 200:
86
+ return False
87
+ if width * height < 40000:
88
+ return False
89
+ return True
90
+ except:
91
+ return False
92
 
93
+ async def fetch_page(self, url):
94
+ try:
95
+ session = await self.get_session()
96
+ async with session.get(url, allow_redirects=True) as response:
97
+ if response.status == 200:
98
+ content_type = response.headers.get('Content-Type', '')
99
+ if 'text/html' in content_type:
100
+ return await response.text()
101
+ except Exception as e:
102
+ print(f"Fetch error {url}: {e}")
103
+ return None
104
 
105
+ def clean_text(self, text):
106
+ text = re.sub(r'\s+', ' ', text)
107
+ text = re.sub(r'[\r\n]+', '\n', text)
108
+ return text.strip()
109
+
110
+ def extract_meaningful_content(self, soup):
111
+ content_selectors = [
112
+ 'article',
113
+ 'main',
114
+ '[role="main"]',
115
+ '.post-content',
116
+ '.article-content',
117
+ '.entry-content',
118
+ '.content',
119
+ '#content',
120
+ '.post-body',
121
+ '.article-body'
 
 
 
 
 
 
 
 
 
122
  ]
123
 
124
+ for selector in content_selectors:
125
+ if selector.startswith('.') or selector.startswith('#'):
126
+ content = soup.select_one(selector)
127
+ else:
128
+ content = soup.find(selector)
129
+
130
+ if content:
131
+ return content
132
 
133
+ return soup.find('body') or soup
134
+
135
+ async def extract_content(self, url, html, keywords):
136
+ try:
137
+ soup = BeautifulSoup(html, 'html.parser')
138
+
139
+ for tag in soup(['script', 'style', 'nav', 'footer', 'header', 'aside', 'iframe', 'noscript']):
140
+ tag.decompose()
141
+
142
+ for tag in soup.find_all(class_=re.compile(r'(menu|sidebar|comment|ad|banner|share|social|related|recommend)', re.I)):
143
+ tag.decompose()
144
+
145
+ for tag in soup.find_all(id=re.compile(r'(menu|sidebar|comment|ad|banner|share|social)', re.I)):
146
+ tag.decompose()
147
+
148
+ title = soup.find('title')
149
+ title_text = self.clean_text(title.get_text()) if title else ''
150
+
151
+ h1 = soup.find('h1')
152
+ h1_text = self.clean_text(h1.get_text()) if h1 else ''
153
+
154
+ final_title = h1_text or title_text
155
+
156
+ meta_desc = soup.find('meta', {'name': 'description'}) or soup.find('meta', {'property': 'og:description'})
157
+ description = self.clean_text(meta_desc['content']) if meta_desc and meta_desc.get('content') else ''
158
+
159
+ content_area = self.extract_meaningful_content(soup)
160
+
161
+ paragraphs = []
162
+ for p in content_area.find_all(['p', 'div', 'section']):
163
+ text = self.clean_text(p.get_text())
164
+ if len(text) > 50:
165
+ paragraphs.append(text)
166
+
167
+ main_text = '\n\n'.join(paragraphs)
168
+
169
+ if len(main_text) < 200:
170
+ return None
171
+
172
+ keyword_lower = [k.lower() for k in keywords]
173
+ text_lower = main_text.lower()
174
+ title_lower = final_title.lower()
175
+
176
+ keyword_count = sum(text_lower.count(kw) + title_lower.count(kw) * 3 for kw in keyword_lower)
177
+
178
+ if keyword_count == 0:
179
+ return None
180
+
181
+ images = []
182
+ for img in content_area.find_all('img'):
183
+ src = img.get('src') or img.get('data-src') or img.get('data-original')
184
+ if src:
185
+ img_url = urljoin(url, src)
186
+ if img_url.startswith('http') and not any(x in img_url.lower() for x in ['logo', 'icon', 'avatar', 'emoji', 'badge']):
187
+ images.append(img_url)
188
+
189
+ return {
190
+ 'url': url,
191
+ 'title': final_title,
192
+ 'description': description,
193
+ 'text': main_text,
194
+ 'images': images[:15],
195
+ 'keyword_count': keyword_count
196
+ }
197
+ except Exception as e:
198
+ print(f"Extract error {url}: {e}")
199
+ return None
200
+
201
+ async def download_image(self, img_url):
202
+ try:
203
+ session = await self.get_session()
204
+ async with session.get(img_url) as response:
205
+ if response.status == 200:
206
+ content = await response.read()
207
+
208
+ if not self.is_valid_image(content):
209
+ return None
210
+
211
+ img_hash = self.image_hash(content)
212
+
213
+ for seen_hash in self.seen_images:
214
+ if self.is_similar_image(img_hash, seen_hash):
215
+ return None
216
+
217
+ self.seen_images.add(img_hash)
218
+
219
+ ext = img_url.split('.')[-1].split('?')[0][:4]
220
+ if ext not in ['jpg', 'jpeg', 'png', 'webp', 'gif']:
221
+ ext = 'jpg'
222
+
223
+ return {
224
+ 'url': img_url,
225
+ 'hash': img_hash,
226
+ 'content': content,
227
+ 'ext': ext
228
+ }
229
+ except Exception as e:
230
+ print(f"Image download error {img_url}: {e}")
231
  return None
232
+
233
+ async def scrape_url(self, url, keywords):
234
+ url_id = self.url_hash(url)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
235
 
236
+ if url_id in self.seen_urls:
 
237
  return None
238
 
239
+ self.seen_urls.add(url_id)
 
240
 
241
+ html = await self.fetch_page(url)
242
+ if not html:
243
  return None
244
 
245
+ content = await self.extract_content(url, html, keywords)
246
+ if not content:
 
247
  return None
248
 
249
+ image_tasks = [self.download_image(img_url) for img_url in content['images']]
250
+ images = await asyncio.gather(*image_tasks)
251
+ content['image_data'] = [img for img in images if img]
252
 
253
+ return content
254
+
255
+ async def scrape_batch(self, urls, keywords):
256
+ semaphore = asyncio.Semaphore(self.max_workers)
 
 
 
 
 
 
 
 
 
 
 
257
 
258
+ async def scrape_with_limit(url):
259
+ async with semaphore:
260
+ return await self.scrape_url(url, keywords)
261
 
262
+ tasks = [scrape_with_limit(url) for url in urls]
263
+ results = await asyncio.gather(*tasks)
264
+ return [r for r in results if r]
265
 
266
+ class EventProcessor:
267
+ def __init__(self, output_dir='output'):
268
+ self.searcher = RateLimitedSearcher()
269
+ self.scraper = ContentScraper(max_workers=40)
270
+ self.output_dir = Path(output_dir)
271
+ self.output_dir.mkdir(exist_ok=True)
272
 
273
+ async def search_event(self, query, title_query):
274
+ all_links = {}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
275
 
276
+ print(f"Searching for: {query}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
277
 
278
+ time_filters = [
279
+ (None, 'all_time'),
280
+ ('y', 'past_year'),
281
+ ('m', 'past_month'),
282
+ ('w', 'past_week'),
283
+ ('d', 'past_day')
284
+ ]
285
 
286
+ queries = [query, title_query] if title_query else [query]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
287
 
288
+ for search_query in queries:
289
+ for timelimit, label in time_filters:
290
+ results = await self.searcher.search(search_query, max_results=20, timelimit=timelimit)
291
+
292
+ for result in results:
293
+ link = result.get('href') or result.get('link')
294
+ if link and link not in all_links:
295
+ all_links[link] = {
296
+ 'title': result.get('title', ''),
297
+ 'snippet': result.get('body', ''),
298
+ 'time_filter': label
299
+ }
300
+
301
+ print(f" {label}: {len(results)} results | Total unique: {len(all_links)}")
302
+
303
+ return all_links
 
 
 
 
 
 
304
 
305
+ def calculate_relevance(self, content, keywords):
306
+ text_lower = content['text'].lower()
307
+ title_lower = content['title'].lower()
 
 
 
308
 
309
+ keyword_matches = 0
310
+ for kw in keywords:
311
+ kw_lower = kw.lower()
312
+ keyword_matches += text_lower.count(kw_lower)
313
+ keyword_matches += title_lower.count(kw_lower) * 5
314
 
315
+ text_length = len(content['text'])
316
+ length_score = min(text_length / 100, 100)
 
 
317
 
318
+ image_score = len(content['image_data']) * 5
 
 
 
319
 
320
+ relevance_score = keyword_matches * 10 + length_score + image_score
321
+
322
+ return relevance_score
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
323
 
324
+ async def process_event(self, event_name, query, title_query, keywords):
325
+ print(f"\n{'='*80}")
326
+ print(f"Processing: {event_name}")
327
+ print(f"Query: {query}")
328
+ print(f"Keywords: {', '.join(keywords)}")
329
+ print(f"{'='*80}\n")
 
 
 
 
 
 
 
 
 
 
 
330
 
331
+ link_data = await self.search_event(query, title_query)
 
 
 
 
 
 
 
 
 
 
 
 
332
 
333
+ if not link_data:
334
+ print("No links found")
335
+ return None
 
 
 
336
 
337
+ links = list(link_data.keys())
338
+ print(f"\nScraping {len(links)} unique URLs...")
 
 
 
 
339
 
340
+ articles = await self.scraper.scrape_batch(links, keywords)
 
341
 
342
+ if not articles:
343
+ print("No relevant content extracted")
344
+ return None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
345
 
346
+ for article in articles:
347
+ article['relevance'] = self.calculate_relevance(article, keywords)
348
+
349
+ articles.sort(key=lambda x: x['relevance'], reverse=True)
350
+
351
+ event_data = {
352
+ 'event_name': event_name,
353
  'query': query,
354
+ 'keywords': keywords,
355
+ 'timestamp': datetime.now().isoformat(),
356
+ 'articles_count': len(articles),
357
+ 'total_images': sum(len(a['image_data']) for a in articles),
358
+ 'articles': []
359
  }
360
 
361
+ event_dir = self.output_dir / event_name.replace(' ', '_').replace('/', '_')
362
+ event_dir.mkdir(exist_ok=True)
363
+
364
+ for idx, article in enumerate(articles):
365
+ article_data = {
366
+ 'rank': idx + 1,
367
+ 'title': article['title'],
368
+ 'url': article['url'],
369
+ 'relevance_score': round(article['relevance'], 2),
370
+ 'keyword_matches': article['keyword_count'],
371
+ 'text_length': len(article['text']),
372
+ 'description': article['description'],
373
+ 'images': []
374
+ }
375
+
376
+ for img_idx, img in enumerate(article['image_data']):
377
+ img_filename = f"{idx+1:03d}_img_{img_idx+1}.{img['ext']}"
378
+ img_path = event_dir / img_filename
379
+
380
+ with open(img_path, 'wb') as f:
381
+ f.write(img['content'])
382
+
383
+ article_data['images'].append({
384
+ 'filename': img_filename,
385
+ 'url': img['url']
386
+ })
387
+
388
+ txt_filename = f"{idx+1:03d}_article.txt"
389
+ txt_path = event_dir / txt_filename
390
+ with open(txt_path, 'w', encoding='utf-8') as f:
391
+ f.write(f"Rank: #{idx+1}\n")
392
+ f.write(f"Title: {article['title']}\n")
393
+ f.write(f"URL: {article['url']}\n")
394
+ f.write(f"Relevance Score: {article['relevance']:.2f}\n")
395
+ f.write(f"Keyword Matches: {article['keyword_count']}\n")
396
+ f.write(f"Images: {len(article['image_data'])}\n")
397
+ f.write(f"\nDescription:\n{article['description']}\n")
398
+ f.write(f"\n{'='*80}\n\n")
399
+ f.write(article['text'])
400
+
401
+ article_data['text_file'] = txt_filename
402
+ event_data['articles'].append(article_data)
403
 
404
+ metadata_path = event_dir / 'metadata.json'
405
+ with open(metadata_path, 'w', encoding='utf-8') as f:
406
+ json.dump(event_data, f, indent=2, ensure_ascii=False)
 
407
 
408
+ print(f"\n{'='*80}")
409
+ print(f"✓ Successfully processed '{event_name}'")
410
+ print(f" Articles saved: {len(articles)}")
411
+ print(f" Images saved: {sum(len(a['image_data']) for a in articles)}")
412
+ print(f" Output directory: {event_dir}")
413
+ print(f"{'='*80}\n")
414
 
415
+ return event_data
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
416
 
417
+ async def close(self):
418
+ await self.scraper.close()
419
+
420
+ async def main():
421
+ processor = EventProcessor()
422
 
423
+ try:
424
+ events = []
425
+
426
+ print("="*80)
427
+ print("DuckDuckGo Event Scraper")
428
+ print("="*80)
429
+ print("\nEnter events to process (leave event name empty to finish):\n")
430
+
431
+ while True:
432
+ event_name = input("Event name: ").strip()
433
+ if not event_name:
434
+ break
435
+
436
+ query = input("Search query: ").strip()
437
+ if not query:
438
+ print("Query cannot be empty!")
439
+ continue
440
+
441
+ title_query = input("Title query (optional): ").strip()
442
+
443
+ keywords_input = input("Keywords (comma-separated): ").strip()
444
+ if not keywords_input:
445
+ print("Keywords cannot be empty!")
446
+ continue
447
+
448
+ keywords = [k.strip() for k in keywords_input.split(',') if k.strip()]
449
+
450
+ events.append((event_name, query, title_query or query, keywords))
451
+ print()
452
+
453
+ if not events:
454
+ print("No events to process!")
455
+ return
456
+
457
+ for event_name, query, title_query, keywords in events:
458
+ await processor.process_event(event_name, query, title_query, keywords)
459
+ await asyncio.sleep(1)
460
 
461
+ finally:
462
+ await processor.close()
463
 
464
  if __name__ == "__main__":
465
+ asyncio.run(main())