Spaces:
Sleeping
Sleeping
Download app.py from dxedline/scrape-backlog: direct link, hf CLI and curl.
- Browser
- Download file 11.7 kB
-
https://huggingface.co/spaces/dxedline/scrape-backlog/resolve/main/app.py
- Command line
-
hf download hf://spaces/dxedline/scrape-backlog/app.py
-
curl -L -o app.py https://huggingface.co/spaces/dxedline/scrape-backlog/resolve/main/app.py
11.7 kB
| import gradio as gr | |
| from duckduckgo_search import DDGS | |
| import asyncio | |
| import aiohttp | |
| from bs4 import BeautifulSoup | |
| from urllib.parse import urlparse, urljoin | |
| import hashlib | |
| from datetime import datetime, timedelta | |
| import json | |
| from collections import defaultdict | |
| import time | |
| from concurrent.futures import ThreadPoolExecutor | |
| import requests | |
| from PIL import Image | |
| from io import BytesIO | |
| import imagehash | |
| class RateLimiter: | |
| def __init__(self, calls_per_minute=30): | |
| self.calls_per_minute = calls_per_minute | |
| self.calls = [] | |
| async def acquire(self): | |
| now = time.time() | |
| self.calls = [t for t in self.calls if now - t < 60] | |
| if len(self.calls) >= self.calls_per_minute: | |
| sleep_time = 60 - (now - self.calls[0]) + 1 | |
| await asyncio.sleep(sleep_time) | |
| self.calls = [] | |
| self.calls.append(time.time()) | |
| class SearchWorker: | |
| def __init__(self, rate_limiter): | |
| self.rate_limiter = rate_limiter | |
| self.ddgs = DDGS() | |
| async def search(self, query, time_filter=None): | |
| await self.rate_limiter.acquire() | |
| try: | |
| results = [] | |
| search_params = {'max_results': 20} | |
| if time_filter: | |
| search_params['timelimit'] = time_filter | |
| for result in self.ddgs.text(query, **search_params): | |
| results.append({ | |
| 'url': result.get('href', ''), | |
| 'title': result.get('title', ''), | |
| 'snippet': result.get('body', '') | |
| }) | |
| return results | |
| except Exception as e: | |
| print(f"Search error: {str(e)}") | |
| return [] | |
| class ContentScraper: | |
| def __init__(self): | |
| self.session = None | |
| self.image_hashes = set() | |
| async def init_session(self): | |
| if not self.session: | |
| self.session = aiohttp.ClientSession( | |
| timeout=aiohttp.ClientTimeout(total=30), | |
| headers={'User-Agent': 'Mozilla/5.0'} | |
| ) | |
| async def close_session(self): | |
| if self.session: | |
| await self.session.close() | |
| def extract_text(self, soup): | |
| for tag in soup(['script', 'style', 'nav', 'footer', 'header', 'aside', 'form']): | |
| tag.decompose() | |
| paragraphs = soup.find_all(['p', 'article', 'section']) | |
| text_content = [] | |
| for p in paragraphs: | |
| text = p.get_text(strip=True) | |
| if len(text) > 50: | |
| text_content.append(text) | |
| return ' '.join(text_content) | |
| def extract_images(self, soup, base_url): | |
| images = [] | |
| for img in soup.find_all('img'): | |
| src = img.get('src') or img.get('data-src') | |
| if not src: | |
| continue | |
| img_url = urljoin(base_url, src) | |
| if img_url.endswith(('.svg', '.gif')): | |
| continue | |
| images.append(img_url) | |
| return images | |
| def is_duplicate_image(self, img_data): | |
| try: | |
| img = Image.open(BytesIO(img_data)) | |
| img_hash = str(imagehash.average_hash(img)) | |
| if img_hash in self.image_hashes: | |
| return True | |
| self.image_hashes.add(img_hash) | |
| return False | |
| except: | |
| return True | |
| async def scrape_url(self, url): | |
| try: | |
| await self.init_session() | |
| async with self.session.get(url) as response: | |
| if response.status != 200: | |
| return None | |
| html = await response.text() | |
| soup = BeautifulSoup(html, 'html.parser') | |
| title = soup.find('title') | |
| title_text = title.get_text(strip=True) if title else '' | |
| text_content = self.extract_text(soup) | |
| image_urls = self.extract_images(soup, url) | |
| return { | |
| 'url': url, | |
| 'title': title_text, | |
| 'content': text_content, | |
| 'images': image_urls | |
| } | |
| except Exception as e: | |
| print(f"Scrape error for {url}: {str(e)}") | |
| return None | |
| async def download_image(self, img_url): | |
| try: | |
| await self.init_session() | |
| async with self.session.get(img_url) as response: | |
| if response.status != 200: | |
| return None | |
| img_data = await response.read() | |
| if self.is_duplicate_image(img_data): | |
| return None | |
| return { | |
| 'url': img_url, | |
| 'data': img_data | |
| } | |
| except: | |
| return None | |
| class EventResearcher: | |
| def __init__(self): | |
| self.rate_limiter = RateLimiter(calls_per_minute=30) | |
| self.search_worker = SearchWorker(self.rate_limiter) | |
| self.visited_urls = set() | |
| self.url_hashes = set() | |
| def get_url_hash(self, url): | |
| return hashlib.md5(url.encode()).hexdigest() | |
| def is_duplicate_url(self, url): | |
| url_hash = self.get_url_hash(url) | |
| if url_hash in self.url_hashes: | |
| return True | |
| self.url_hashes.add(url_hash) | |
| return False | |
| async def search_all_timeframes(self, query, title): | |
| timeframes = [ | |
| ('w', 'Past Week'), | |
| ('m', 'Past Month'), | |
| ('y', 'Past Year'), | |
| (None, 'All Time') | |
| ] | |
| all_results = [] | |
| queries = [query, title] | |
| for q in queries: | |
| for timeframe, label in timeframes: | |
| results = await self.search_worker.search(q, timeframe) | |
| for result in results: | |
| url = result['url'] | |
| if self.is_duplicate_url(url): | |
| continue | |
| result['timeframe'] = label | |
| result['query'] = q | |
| all_results.append(result) | |
| yield f"Searched: {label} for '{q}' - Found {len(results)} results", all_results | |
| def calculate_relevance(self, result, event_query, event_title): | |
| score = 0 | |
| text = f"{result['title']} {result['snippet']}".lower() | |
| query_terms = event_query.lower().split() | |
| title_terms = event_title.lower().split() | |
| for term in query_terms: | |
| if term in text: | |
| score += 2 | |
| for term in title_terms: | |
| if term in text: | |
| score += 3 | |
| return score | |
| async def research_event(self, event_id, event_title, event_query): | |
| all_search_results = [] | |
| async for status, results in self.search_all_timeframes(event_query, event_title): | |
| yield status, [] | |
| all_search_results = results | |
| for result in all_search_results: | |
| relevance = self.calculate_relevance(result, event_query, event_title) | |
| result['relevance'] = relevance | |
| all_search_results.sort(key=lambda x: x['relevance'], reverse=True) | |
| top_results = all_search_results[:30] | |
| yield f"Selected top {len(top_results)} relevant URLs", top_results | |
| scraper = ContentScraper() | |
| scraped_data = [] | |
| async def scrape_batch(urls): | |
| tasks = [scraper.scrape_url(url) for url in urls] | |
| return await asyncio.gather(*tasks) | |
| batch_size = 20 | |
| for i in range(0, len(top_results), batch_size): | |
| batch = top_results[i:i+batch_size] | |
| urls = [r['url'] for r in batch] | |
| results = await scrape_batch(urls) | |
| for result in results: | |
| if result and len(result['content']) > 200: | |
| scraped_data.append(result) | |
| yield f"Scraped {len(scraped_data)} articles so far", scraped_data | |
| all_images = [] | |
| for article in scraped_data: | |
| all_images.extend(article.get('images', [])) | |
| downloaded_images = [] | |
| async def download_batch(img_urls): | |
| tasks = [scraper.download_image(url) for url in img_urls] | |
| return await asyncio.gather(*tasks) | |
| batch_size = 40 | |
| for i in range(0, len(all_images), batch_size): | |
| batch = all_images[i:i+batch_size] | |
| results = await download_batch(batch) | |
| for result in results: | |
| if result: | |
| downloaded_images.append(result) | |
| yield f"Downloaded {len(downloaded_images)} unique images", scraped_data | |
| await scraper.close_session() | |
| dataset = { | |
| 'event_id': event_id, | |
| 'event_title': event_title, | |
| 'event_query': event_query, | |
| 'timestamp': datetime.now().isoformat(), | |
| 'articles': scraped_data, | |
| 'images': [{'url': img['url']} for img in downloaded_images], | |
| 'total_articles': len(scraped_data), | |
| 'total_images': len(downloaded_images) | |
| } | |
| filename = f"event_{event_id}_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json" | |
| with open(filename, 'w', encoding='utf-8') as f: | |
| json.dump(dataset, f, indent=2, ensure_ascii=False) | |
| for img in downloaded_images: | |
| img_filename = f"event_{event_id}_img_{hashlib.md5(img['url'].encode()).hexdigest()[:8]}.jpg" | |
| with open(img_filename, 'wb') as f: | |
| f.write(img['data']) | |
| yield f"Completed! Saved {len(scraped_data)} articles and {len(downloaded_images)} images", scraped_data | |
| async def process_event(event_id, event_title, event_query, progress=gr.Progress()): | |
| researcher = EventResearcher() | |
| final_data = [] | |
| async for status, data in researcher.research_event(event_id, event_title, event_query): | |
| progress(0.5, desc=status) | |
| if data: | |
| final_data = data | |
| summary = f"Research complete for Event {event_id}: {event_title}\n" | |
| summary += f"Total articles collected: {len(final_data)}\n" | |
| summary += f"Data saved successfully" | |
| return summary | |
| def launch_research(event_id, event_title, event_query): | |
| return asyncio.run(process_event(event_id, event_title, event_query)) | |
| with gr.Blocks(title="Historical Event Researcher") as app: | |
| gr.Markdown("# Historical Event Deep Research System") | |
| gr.Markdown("Optimized parallel scraping with rate limit management") | |
| with gr.Row(): | |
| event_id = gr.Number(label="Event ID", value=1, precision=0) | |
| event_title = gr.Textbox(label="Event Title", placeholder="Battle of Plassey") | |
| event_query = gr.Textbox(label="Search Query", placeholder="Battle of Plassey Robert Clive treachery") | |
| research_btn = gr.Button("Start Research", variant="primary") | |
| output = gr.Textbox(label="Status", lines=10) | |
| research_btn.click( | |
| fn=launch_research, | |
| inputs=[event_id, event_title, event_query], | |
| outputs=output | |
| ) | |
| app.launch(server_name="0.0.0.0", server_port=7860) |