Spaces:
Sleeping

dxedline commited on
Commit
e682bd2
·
verified ·
1 Parent(s): 1ef0732

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +150 -184
app.py CHANGED
@@ -9,23 +9,22 @@ 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, concatenate_datasets
18
  from huggingface_hub import login, HfApi
19
  import os
20
- import json
21
 
22
  warnings.filterwarnings('ignore')
23
  requests.packages.urllib3.disable_warnings()
24
 
25
  HF_TOKEN = os.environ.get("HF_TOKEN")
26
  HF_DATASET = "dxedline/historical_research_data"
27
- SCRAPE_WORKERS = 50
28
- IMAGE_WORKERS = 35
29
  MAX_CELL_CHARS = 49000
30
  MAX_WORD_LIMIT = 150000
31
  MIN_IMAGE_SIZE = 200
@@ -82,12 +81,10 @@ def parse_article_date(date_str):
82
  return None
83
 
84
  def is_date_valid_for_incident(article_date, incident_date):
85
- if not article_date:
86
- return True
87
- if not incident_date:
88
  return True
89
  try:
90
- incident_dt = datetime.strptime(str(incident_date), "%Y-%m-%d") if isinstance(incident_date, str) else incident_date
91
  if article_date >= incident_dt:
92
  return True
93
  days_before = (incident_dt - article_date).days
@@ -126,15 +123,6 @@ def calculate_relevance_score(content, query, title, page_title=''):
126
  page_title_matches = sum(1 for word in title_words if word in page_title_lower)
127
  score += (page_title_matches / len(title_words)) * 15
128
 
129
- content_words = content_lower.split()
130
- if content_words:
131
- keyword_density = sum(content_lower.count(word) for word in query_words) / len(content_words)
132
- score += min(keyword_density * 1000, 10)
133
-
134
- if page_title_lower and query_words:
135
- exact_match_bonus = sum(5 for word in query_words if word in page_title_lower)
136
- score += min(exact_match_bonus, 10)
137
-
138
  return min(score, 100)
139
 
140
  def calculate_image_quality_score(width, height, file_size_kb):
@@ -159,24 +147,13 @@ def is_likely_photograph(img_url, img):
159
  url_lower = img_url.lower()
160
  exclude_patterns = [
161
  'icon', 'logo', 'button', 'banner', 'avatar', 'thumbnail', 'thumb',
162
- 'sprite', 'badge', 'emoji', 'clipart', 'vector', 'graphic',
163
- 'illustration', 'drawing', 'chart', 'graph', 'diagram',
164
- 'placeholder', 'default', 'profile', 'user', 'author',
165
- 'bg', 'background', 'pattern', 'header', 'footer', 'sidebar',
166
- 'youtube.com', 'ytimg.com', 'youtu.be',
167
- 'istockphoto.com', 'istock.com', 'gettyimages.com', 'shutterstock.com',
168
- 'stock.adobe.com', 'dreamstime.com', 'alamy.com',
169
- 'depositphotos.com', 'pixabay.com', 'pexels.com', 'unsplash.com'
170
  ]
171
 
172
  if any(pattern in url_lower for pattern in exclude_patterns):
173
  return False
174
 
175
- img_rgb = img.convert('RGB')
176
- colors = img_rgb.getcolors(maxcolors=1000000)
177
- if colors and len(colors) < 150:
178
- return False
179
-
180
  return True
181
  except:
182
  return False
@@ -193,46 +170,23 @@ def check_and_store_image_hash(img_hash, img_data):
193
  try:
194
  hash_diff = abs(imagehash.hex_to_hash(existing_hash) - imagehash.hex_to_hash(img_hash))
195
  if hash_diff <= IMAGE_SIMILARITY_THRESHOLD:
196
- existing_quality = existing_data['quality_score']
197
- new_quality = img_data['quality_score']
198
- if new_quality > existing_quality:
199
- del seen_image_hashes[existing_hash]
200
- seen_image_hashes[img_hash] = img_data
201
- return True, True
202
- return True, False
203
  except:
204
  continue
205
  seen_image_hashes[img_hash] = img_data
206
- return False, True
207
 
208
  def process_single_image(img_url, caption, alt_text, source_url, event_id, date_found):
209
  try:
210
- url_lower = img_url.lower()
211
-
212
- exclude_domains = [
213
- 'youtube.com', 'ytimg.com', 'youtu.be',
214
- 'istockphoto.com', 'gettyimages.com', 'shutterstock.com',
215
- 'stock.adobe.com', 'dreamstime.com', 'alamy.com',
216
- 'depositphotos.com', 'pixabay.com', 'pexels.com', 'unsplash.com'
217
- ]
218
-
219
- if any(domain in url_lower for domain in exclude_domains):
220
- return None
221
-
222
  headers = {
223
  'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
224
  'Referer': source_url,
225
- 'Accept': 'image/avif,image/webp,image/apng,image/*,*/*;q=0.8'
226
  }
227
 
228
  img_response = requests.get(img_url, headers=headers, timeout=10, stream=True, verify=False)
229
  if img_response.status_code != 200:
230
  return None
231
 
232
- content_length = img_response.headers.get('content-length')
233
- if content_length and int(content_length) < 10000:
234
- return None
235
-
236
  img_bytes = img_response.content
237
  file_size_kb = len(img_bytes) / 1024
238
 
@@ -264,13 +218,11 @@ def process_single_image(img_url, caption, alt_text, source_url, event_id, date_
264
  'quality_score': float(quality_score)
265
  }
266
 
267
- is_similar, should_keep = check_and_store_image_hash(img_hash, img_data)
268
-
269
- if should_keep:
270
  return img_data
271
 
272
  return None
273
- except Exception as e:
274
  return None
275
 
276
  def extract_images_from_page(soup, base_url, source_url, event_id, date_found):
@@ -279,8 +231,8 @@ def extract_images_from_page(soup, base_url, source_url, event_id, date_found):
279
 
280
  with ThreadPoolExecutor(max_workers=IMAGE_WORKERS) as executor:
281
  futures = []
282
- for img_tag in img_tags[:30]:
283
- img_url = img_tag.get('src') or img_tag.get('data-src') or img_tag.get('data-lazy-src')
284
  if not img_url:
285
  continue
286
 
@@ -308,13 +260,13 @@ def extract_images_from_page(soup, base_url, source_url, event_id, date_found):
308
 
309
  return images_data
310
 
311
- def deep_scrape_content(response, source_url):
312
  try:
313
  soup = BeautifulSoup(response.content, 'lxml')
314
  except:
315
  soup = BeautifulSoup(response.content, 'html.parser')
316
 
317
- for tag in soup(['script', 'style', 'nav', 'footer', 'header', 'aside', 'iframe', 'noscript']):
318
  tag.decompose()
319
 
320
  content_parts = []
@@ -328,9 +280,9 @@ def deep_scrape_content(response, source_url):
328
  main_content = soup.find('body')
329
 
330
  if main_content:
331
- for elem in main_content.find_all(['p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'blockquote', 'li']):
332
  text = elem.get_text(separator=' ', strip=True)
333
- if len(text) > 5:
334
  content_parts.append(text)
335
 
336
  full_content = ' '.join(content_parts)
@@ -339,15 +291,14 @@ def deep_scrape_content(response, source_url):
339
 
340
  return truncated, soup
341
 
342
- def extract_date(soup, response_text):
343
  time_tag = soup.find('time')
344
  if time_tag:
345
  date_val = time_tag.get('datetime') or time_tag.get_text(strip=True)
346
  if date_val:
347
  return date_val
348
 
349
- meta_props = ['article:published_time', 'datePublished', 'publication_date']
350
- for prop in meta_props:
351
  meta = soup.find('meta', attrs={'property': prop}) or soup.find('meta', attrs={'name': prop})
352
  if meta and meta.get('content'):
353
  return meta.get('content')
@@ -362,19 +313,16 @@ def scrape_url(url, event_id, incident_date, query, title):
362
  return None
363
  seen_urls.add(normalized)
364
 
365
- domain = get_domain(url)
366
-
367
  headers = {
368
  'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
369
- 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9',
370
  }
371
 
372
- response = requests.get(url, headers=headers, timeout=15, allow_redirects=True, verify=False)
373
  if response.status_code != 200:
374
  return None
375
 
376
- content, soup = deep_scrape_content(response, url)
377
- if len(content) < 100:
378
  return None
379
 
380
  content_hash = get_content_hash(content)
@@ -383,21 +331,15 @@ def scrape_url(url, event_id, incident_date, query, title):
383
  return None
384
  seen_hashes.add(content_hash)
385
 
386
- page_title = ''
387
- h1_tag = soup.find('h1')
388
- if h1_tag:
389
- page_title = h1_tag.get_text(strip=True)
390
 
391
  relevance_score = calculate_relevance_score(content, query, title, page_title)
392
 
393
  if relevance_score < MIN_RELEVANCE_SCORE:
394
  return None
395
 
396
- date_found = extract_date(soup, response.text)
397
- if date_found:
398
- article_date = parse_article_date(date_found)
399
- if article_date and not is_date_valid_for_incident(article_date, incident_date):
400
- pass
401
 
402
  images_data = extract_images_from_page(soup, response.url, url, event_id, date_found)
403
 
@@ -408,25 +350,47 @@ def scrape_url(url, event_id, incident_date, query, title):
408
  'date': date_found or '',
409
  'relevance_score': float(relevance_score),
410
  'images': images_data,
411
- 'domain': domain
412
  }
413
- except Exception as e:
414
  return None
415
 
416
- def search_web_simple(query, max_results=30):
417
  links = []
418
  try:
419
- search_url = f"https://html.duckduckgo.com/html/?q={requests.utils.quote(query)}"
420
- headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'}
 
 
 
421
  response = requests.get(search_url, headers=headers, timeout=10)
422
  soup = BeautifulSoup(response.content, 'html.parser')
423
 
424
- for link in soup.find_all('a', class_='result__a'):
425
  href = link.get('href')
426
- if href and href.startswith('http'):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
427
  links.append(href)
428
- if len(links) >= max_results:
429
- break
430
  except:
431
  pass
432
  return links
@@ -434,31 +398,37 @@ def search_web_simple(query, max_results=30):
434
  def search_and_scrape_event(event_id, query, title, incident_date):
435
  all_links = []
436
 
437
- priority_domains = [
438
- 'wikipedia.org', 'britannica.com', 'history.com',
439
- 'bbc.com', 'reuters.com', 'nytimes.com', 'theguardian.com'
440
- ]
441
-
442
- for domain in priority_domains:
443
- domain_links = search_web_simple(f"{query} site:{domain}", max_results=5)
444
- all_links.extend(domain_links)
445
- time.sleep(1)
446
-
447
- general_links = search_web_simple(query, max_results=40)
448
- all_links.extend(general_links)
449
 
450
- title_links = search_web_simple(title, max_results=30)
 
451
  all_links.extend(title_links)
 
 
 
 
 
 
 
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({
@@ -469,8 +439,8 @@ def search_and_scrape_event(event_id, query, title, incident_date):
469
  'relevance_score': result['relevance_score'],
470
  'domain': result['domain']
471
  })
472
-
473
  all_images.extend(result['images'])
 
474
 
475
  return scraped_articles, all_images
476
 
@@ -478,59 +448,49 @@ def save_to_hf_dataset(articles, images, event_info):
478
  try:
479
  api = HfApi()
480
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
481
  try:
482
- dataset = load_dataset(HF_DATASET, token=HF_TOKEN)
 
 
483
  except:
484
- dataset = DatasetDict({
485
- 'articles': Dataset.from_dict({
486
- 'event_id': [],
487
- 'url': [],
488
- 'content': [],
489
- 'date': [],
490
- 'relevance_score': [],
491
- 'domain': [],
492
- 'event_title': [],
493
- 'event_query': [],
494
- 'incident_date': []
495
- }),
496
- 'images': Dataset.from_dict({
497
- 'event_id': [],
498
- 'image_url': [],
499
- 'caption': [],
500
- 'alt_text': [],
501
- 'date': [],
502
- 'source_url': [],
503
- 'width': [],
504
- 'height': [],
505
- 'file_size_kb': [],
506
- 'quality_score': [],
507
- 'event_title': []
508
- })
509
- })
510
 
511
- if articles:
512
- articles_df = pd.DataFrame(articles)
513
- articles_df['event_title'] = event_info['title']
514
- articles_df['event_query'] = event_info['query']
515
- articles_df['incident_date'] = event_info['incident_date']
516
-
517
- new_articles = Dataset.from_pandas(articles_df)
518
- if 'articles' in dataset:
519
- dataset['articles'] = concatenate_datasets([dataset['articles'], new_articles])
520
- else:
521
- dataset['articles'] = new_articles
522
-
523
- if images:
524
- images_df = pd.DataFrame(images)
525
- images_df['event_title'] = event_info['title']
526
-
527
- new_images = Dataset.from_pandas(images_df)
528
- if 'images' in dataset:
529
- dataset['images'] = concatenate_datasets([dataset['images'], new_images])
530
- else:
531
- dataset['images'] = new_images
532
 
533
- dataset.push_to_hub(HF_DATASET, token=HF_TOKEN)
534
  return True
535
  except Exception as e:
536
  print(f"Save error: {e}")
@@ -538,16 +498,16 @@ def save_to_hf_dataset(articles, images, event_info):
538
 
539
  def get_next_event_id():
540
  try:
541
- dataset = load_dataset(HF_DATASET, token=HF_TOKEN)
542
- processed_ids = set()
543
- if 'articles' in dataset and len(dataset['articles']) > 0:
544
- processed_ids = set(dataset['articles']['event_id'])
545
- next_id = 1
546
- while next_id in processed_ids:
547
- next_id += 1
548
- return next_id
549
  except:
550
- return 1
 
551
 
552
  def process_event(event_id_input):
553
  try:
@@ -558,7 +518,8 @@ def process_event(event_id_input):
558
  else:
559
  next_id = get_next_event_id()
560
  if next_id > len(df):
561
- return "All events processed!"
 
562
  event = df[df['id'] == next_id].iloc[0]
563
 
564
  event_id = int(event['id'])
@@ -566,38 +527,44 @@ def process_event(event_id_input):
566
  title = str(event['title'])
567
  incident_date = str(event['incident_date'])
568
 
569
- status = f"Processing Event {event_id}: {title}\n\nSearching web...\n"
570
  yield status
571
 
572
- articles, images = search_and_scrape_event(event_id, query, title, incident_date)
573
-
574
- status += f"\nFound {len(articles)} articles and {len(images)} images\n\n"
575
 
576
- if articles:
577
- status += "Articles:\n"
578
- for art in articles[:5]:
579
- status += f" • {art['domain']} ({art['relevance_score']:.0f}%)\n"
 
580
 
581
- if images:
582
- status += f"\nImages: {len(images)} photographs\n"
583
 
 
584
  yield status
585
 
 
 
 
 
 
586
  event_info = {
587
  'title': title,
588
  'query': query,
589
  'incident_date': incident_date
590
  }
591
 
592
- status += "\nSaving to dataset...\n"
593
  yield status
594
 
595
  success = save_to_hf_dataset(articles, images, event_info)
596
 
597
  if success:
598
- status += f"\n✓ Successfully saved to {HF_DATASET}\n"
599
  else:
600
- status += f"\n✗ Failed to save to dataset\n"
601
 
602
  yield status
603
 
@@ -612,21 +579,20 @@ def auto_process():
612
  print(result)
613
  time.sleep(600)
614
  except Exception as e:
615
- print(f"Auto process error: {e}")
616
  time.sleep(120)
617
 
618
  with gr.Blocks(title="Historical Event Scraper") as demo:
619
  gr.Markdown("# Historical Event Scraper")
620
- gr.Markdown("Automatically scrapes and processes historical events")
621
 
622
  with gr.Row():
623
  event_id = gr.Number(label="Event ID (leave empty for auto)", precision=0, value=None)
624
  process_btn = gr.Button("Process Event", variant="primary")
625
 
626
- output = gr.Textbox(label="Status", lines=15, max_lines=20)
627
 
628
- gr.Markdown(f"### Dataset: [{HF_DATASET}](https://huggingface.co/datasets/{HF_DATASET})")
629
- gr.Markdown("Auto-processing runs every 10 minutes")
630
 
631
  process_btn.click(process_event, inputs=[event_id], outputs=[output])
632
 
 
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 = 40
27
+ IMAGE_WORKERS = 15
28
  MAX_CELL_CHARS = 49000
29
  MAX_WORD_LIMIT = 150000
30
  MIN_IMAGE_SIZE = 200
 
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
 
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):
 
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
 
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
 
 
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):
 
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
 
 
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 = []
 
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)
 
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')
 
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)
 
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
 
 
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_google(query, num_results=50):
359
  links = []
360
  try:
361
+ encoded_query = quote_plus(query)
362
+ search_url = f"https://www.google.com/search?q={encoded_query}&num={num_results}"
363
+ headers = {
364
+ 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
365
+ }
366
  response = requests.get(search_url, headers=headers, timeout=10)
367
  soup = BeautifulSoup(response.content, 'html.parser')
368
 
369
+ for link in soup.find_all('a'):
370
  href = link.get('href')
371
+ if href and '/url?q=' in href:
372
+ url = href.split('/url?q=')[1].split('&')[0]
373
+ if url.startswith('http') and 'google.com' not in url:
374
+ links.append(url)
375
+ except:
376
+ pass
377
+ return links
378
+
379
+ def search_bing(query, count=50):
380
+ links = []
381
+ try:
382
+ encoded_query = quote_plus(query)
383
+ search_url = f"https://www.bing.com/search?q={encoded_query}&count={count}"
384
+ headers = {
385
+ 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
386
+ }
387
+ response = requests.get(search_url, headers=headers, timeout=10)
388
+ soup = BeautifulSoup(response.content, 'html.parser')
389
+
390
+ for link in soup.find_all('a'):
391
+ href = link.get('href')
392
+ if href and href.startswith('http') and 'bing.com' not in href and 'microsoft.com' not in href:
393
  links.append(href)
 
 
394
  except:
395
  pass
396
  return links
 
398
  def search_and_scrape_event(event_id, query, title, incident_date):
399
  all_links = []
400
 
401
+ yield f"Searching Google for: {query}...\n"
402
+ google_links = search_google(query, num_results=30)
403
+ all_links.extend(google_links)
404
+ yield f"Found {len(google_links)} Google results\n"
405
+ time.sleep(2)
 
 
 
 
 
 
 
406
 
407
+ yield f"Searching Google for: {title}...\n"
408
+ title_links = search_google(title, num_results=30)
409
  all_links.extend(title_links)
410
+ yield f"Found {len(title_links)} more results\n"
411
+ time.sleep(2)
412
+
413
+ yield f"Searching Bing...\n"
414
+ bing_links = search_bing(query, count=30)
415
+ all_links.extend(bing_links)
416
+ yield f"Found {len(bing_links)} Bing results\n"
417
 
418
  all_links = list(dict.fromkeys(all_links))
419
+ yield f"\nTotal unique links: {len(all_links)}\n\n"
420
 
421
  scraped_articles = []
422
  all_images = []
423
 
424
+ yield "Scraping articles...\n"
425
+
426
  with ThreadPoolExecutor(max_workers=SCRAPE_WORKERS) as executor:
427
  futures = {executor.submit(scrape_url, link, event_id, incident_date, query, title): link for link in all_links}
428
 
429
+ completed = 0
430
  for future in as_completed(futures):
431
+ completed += 1
432
  result = future.result()
433
  if result:
434
  scraped_articles.append({
 
439
  'relevance_score': result['relevance_score'],
440
  'domain': result['domain']
441
  })
 
442
  all_images.extend(result['images'])
443
+ yield f"Progress: {completed}/{len(all_links)} | Found: {len(scraped_articles)} articles, {len(all_images)} images\n"
444
 
445
  return scraped_articles, all_images
446
 
 
448
  try:
449
  api = HfApi()
450
 
451
+ articles_dict = {
452
+ 'event_id': [a['event_id'] for a in articles],
453
+ 'url': [a['url'] for a in articles],
454
+ 'content': [a['content'] for a in articles],
455
+ 'date': [a['date'] for a in articles],
456
+ 'relevance_score': [a['relevance_score'] for a in articles],
457
+ 'domain': [a['domain'] for a in articles],
458
+ 'event_title': [event_info['title']] * len(articles),
459
+ 'event_query': [event_info['query']] * len(articles),
460
+ 'incident_date': [event_info['incident_date']] * len(articles)
461
+ }
462
+
463
+ images_dict = {
464
+ 'event_id': [i['event_id'] for i in images],
465
+ 'image_url': [i['image_url'] for i in images],
466
+ 'caption': [i['caption'] for i in images],
467
+ 'alt_text': [i['alt_text'] for i in images],
468
+ 'date': [i['date'] for i in images],
469
+ 'source_url': [i['source_url'] for i in images],
470
+ 'width': [i['width'] for i in images],
471
+ 'height': [i['height'] for i in images],
472
+ 'file_size_kb': [i['file_size_kb'] for i in images],
473
+ 'quality_score': [i['quality_score'] for i in images],
474
+ 'event_title': [event_info['title']] * len(images)
475
+ }
476
+
477
  try:
478
+ existing_articles = load_dataset(HF_DATASET, split='articles', token=HF_TOKEN)
479
+ new_articles = Dataset.from_dict(articles_dict)
480
+ combined_articles = concatenate_datasets([existing_articles, new_articles])
481
  except:
482
+ combined_articles = Dataset.from_dict(articles_dict)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
483
 
484
+ try:
485
+ existing_images = load_dataset(HF_DATASET, split='images', token=HF_TOKEN)
486
+ new_images = Dataset.from_dict(images_dict)
487
+ combined_images = concatenate_datasets([existing_images, new_images])
488
+ except:
489
+ combined_images = Dataset.from_dict(images_dict)
490
+
491
+ combined_articles.push_to_hub(HF_DATASET, split='articles', token=HF_TOKEN)
492
+ combined_images.push_to_hub(HF_DATASET, split='images', token=HF_TOKEN)
 
 
 
 
 
 
 
 
 
 
 
 
493
 
 
494
  return True
495
  except Exception as e:
496
  print(f"Save error: {e}")
 
498
 
499
  def get_next_event_id():
500
  try:
501
+ dataset = load_dataset(HF_DATASET, split='articles', token=HF_TOKEN)
502
+ if len(dataset) > 0:
503
+ processed_ids = set(dataset['event_id'])
504
+ next_id = 1
505
+ while next_id in processed_ids:
506
+ next_id += 1
507
+ return next_id
 
508
  except:
509
+ pass
510
+ return 1
511
 
512
  def process_event(event_id_input):
513
  try:
 
518
  else:
519
  next_id = get_next_event_id()
520
  if next_id > len(df):
521
+ yield "All events processed!"
522
+ return
523
  event = df[df['id'] == next_id].iloc[0]
524
 
525
  event_id = int(event['id'])
 
527
  title = str(event['title'])
528
  incident_date = str(event['incident_date'])
529
 
530
+ status = f"Processing Event {event_id}: {title}\n\n"
531
  yield status
532
 
533
+ articles = []
534
+ images = []
 
535
 
536
+ for update in search_and_scrape_event(event_id, query, title, incident_date):
537
+ status += update
538
+ yield status
539
+ if isinstance(update, tuple):
540
+ articles, images = update
541
 
542
+ if not isinstance(articles, list):
543
+ articles, images = articles
544
 
545
+ status += f"\n\nFinal count: {len(articles)} articles, {len(images)} images\n"
546
  yield status
547
 
548
+ if not articles and not images:
549
+ status += "\n✗ No data to save\n"
550
+ yield status
551
+ return
552
+
553
  event_info = {
554
  'title': title,
555
  'query': query,
556
  'incident_date': incident_date
557
  }
558
 
559
+ status += "Saving to dataset...\n"
560
  yield status
561
 
562
  success = save_to_hf_dataset(articles, images, event_info)
563
 
564
  if success:
565
+ status += f"✓ Successfully saved to {HF_DATASET}\n"
566
  else:
567
+ status += f"✗ Failed to save to dataset\n"
568
 
569
  yield status
570
 
 
579
  print(result)
580
  time.sleep(600)
581
  except Exception as e:
582
+ print(f"Auto error: {e}")
583
  time.sleep(120)
584
 
585
  with gr.Blocks(title="Historical Event Scraper") as demo:
586
  gr.Markdown("# Historical Event Scraper")
587
+ gr.Markdown("Scrapes historical events from multiple search engines")
588
 
589
  with gr.Row():
590
  event_id = gr.Number(label="Event ID (leave empty for auto)", precision=0, value=None)
591
  process_btn = gr.Button("Process Event", variant="primary")
592
 
593
+ output = gr.Textbox(label="Status", lines=20, max_lines=25, autoscroll=True)
594
 
595
+ gr.Markdown(f"Dataset: [{HF_DATASET}](https://huggingface.co/datasets/{HF_DATASET})")
 
596
 
597
  process_btn.click(process_event, inputs=[event_id], outputs=[output])
598