File size: 11,726 Bytes
674beaa
 
73c5b6c
 
31b18fd
674beaa
31b18fd
674beaa
73c5b6c
674beaa
31b18fd
674beaa
 
31b18fd
 
674beaa
31b18fd
674beaa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
73c5b6c
674beaa
 
 
 
 
 
 
 
 
 
 
 
 
 
73c5b6c
 
674beaa
73c5b6c
674beaa
73c5b6c
674beaa
 
73c5b6c
674beaa
 
73c5b6c
674beaa
 
73c5b6c
 
 
674beaa
 
 
 
 
 
31b18fd
674beaa
 
 
 
 
 
73c5b6c
674beaa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cf74df1
674beaa
 
 
 
 
 
 
 
 
 
 
cf74df1
 
674beaa
73c5b6c
674beaa
73c5b6c
674beaa
 
 
 
 
 
cf74df1
674beaa
 
 
 
 
 
 
 
 
 
 
 
73c5b6c
674beaa
73c5b6c
 
 
 
674beaa
 
 
 
 
73c5b6c
674beaa
 
 
 
73c5b6c
674beaa
 
 
 
 
31b18fd
 
674beaa
 
 
 
 
 
cf74df1
674beaa
 
cf74df1
674beaa
 
 
 
 
 
 
 
 
 
 
 
 
73c5b6c
31b18fd
674beaa
 
d581c3b
674beaa
 
 
73c5b6c
 
674beaa
 
 
 
 
 
 
 
 
1b3e1cc
d581c3b
674beaa
 
 
d581c3b
674beaa
 
d581c3b
674beaa
 
 
 
 
 
 
 
 
 
 
1b3e1cc
d581c3b
1b3e1cc
674beaa
1b3e1cc
d581c3b
1b3e1cc
674beaa
 
e682bd2
1b3e1cc
 
e682bd2
674beaa
31b18fd
674beaa
 
e682bd2
674beaa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31b18fd
674beaa
 
 
e682bd2
674beaa
73c5b6c
674beaa
 
 
73c5b6c
674beaa
 
 
 
 
 
 
 
 
 
cf74df1
674beaa
cf74df1
674beaa
 
 
 
73c5b6c
674beaa
 
 
 
31b18fd
 
674beaa
 
 
31b18fd
674beaa
 
 
 
cf74df1
674beaa
73c5b6c
674beaa
 
cf74df1
674beaa
 
 
 
 
cf74df1
674beaa
 
 
cf74df1
674beaa
cf74df1
674beaa
 
 
 
 
 
cf74df1
 
674beaa
73c5b6c
674beaa
 
cf74df1
674beaa
 
31b18fd
674beaa
 
 
 
 
31b18fd
674beaa
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
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)