File size: 17,591 Bytes
c0f0b79
 
 
 
 
 
 
 
 
1998e27
 
2846655
 
c0f0b79
 
 
 
 
 
 
df97ae1
c0f0b79
2846655
 
df97ae1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1998e27
2846655
 
 
df97ae1
2846655
df97ae1
2846655
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
df97ae1
1998e27
2846655
df97ae1
2846655
 
df97ae1
 
2846655
1998e27
c0f0b79
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
df97ae1
c0f0b79
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18a8062
c0f0b79
df97ae1
c0f0b79
 
18a8062
2846655
 
 
18a8062
c0f0b79
18a8062
 
 
 
 
 
c0f0b79
18a8062
 
 
 
c0f0b79
18a8062
 
c0f0b79
18a8062
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c0f0b79
1998e27
18a8062
1998e27
 
c0f0b79
1998e27
18a8062
1998e27
18a8062
 
 
 
 
1998e27
 
18a8062
 
 
 
1998e27
 
18a8062
1998e27
 
18a8062
 
 
 
 
1998e27
 
 
df97ae1
 
c0f0b79
 
 
 
18a8062
 
 
c0f0b79
 
 
18a8062
c0f0b79
18a8062
 
 
 
c0f0b79
18a8062
 
 
c0f0b79
18a8062
c0f0b79
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
df97ae1
 
c0f0b79
 
df97ae1
18a8062
 
 
df97ae1
c0f0b79
df97ae1
2846655
 
df97ae1
c0f0b79
2846655
df97ae1
 
 
 
 
 
 
 
 
 
c0f0b79
2846655
 
 
 
 
 
 
 
 
 
 
 
c0f0b79
2846655
 
 
 
 
 
 
 
c0f0b79
2846655
c0f0b79
df97ae1
 
2846655
df97ae1
c0f0b79
2846655
df97ae1
c0f0b79
2846655
 
 
 
 
df97ae1
2846655
 
 
 
df97ae1
2846655
 
df97ae1
 
2846655
 
 
 
 
 
 
 
 
 
 
 
 
 
 
df97ae1
 
2846655
 
df97ae1
2846655
 
 
c0f0b79
df97ae1
2846655
c0f0b79
df97ae1
 
c0f0b79
df97ae1
 
 
2846655
df97ae1
c0f0b79
2846655
 
 
 
 
df97ae1
2846655
df97ae1
2846655
df97ae1
c0f0b79
df97ae1
 
2846655
df97ae1
 
2846655
df97ae1
2846655
 
df97ae1
2846655
 
df97ae1
 
2846655
df97ae1
 
 
 
 
 
c0f0b79
2846655
df97ae1
 
 
 
 
 
c0f0b79
df97ae1
2846655
167467b
2846655
df97ae1
2846655
 
df97ae1
 
2846655
df97ae1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2846655
df97ae1
 
2846655
df97ae1
 
1c4afe8
df97ae1
 
167467b
 
 
 
 
 
df97ae1
2846655
df97ae1
 
167467b
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
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
import os
import csv
import json
import time
import requests
from bs4 import BeautifulSoup
from datasets import Dataset, load_dataset
from huggingface_hub import HfApi, login
import re
import torch
from transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig
import gradio as gr
import threading

HF_TOKEN = os.environ.get("HF_TOKEN")
if HF_TOKEN:
    login(token=HF_TOKEN)

DATASET_NAME = "historical_research_data"
HF_USERNAME = os.environ.get("HF_USERNAME", "your_username")
CSV_FILE = "events.csv"

model = None
tokenizer = None
processing_status = {"running": False, "logs": [], "current_event": "", "progress": "", "total_records": 0}

def initialize_model():
    global model, tokenizer
    if model is not None:
        return
    
    print("πŸ”„ Auto-loading model on startup...")
    model_id = "Qwen/Qwen2.5-7B-Instruct"
    
    quantization_config = BitsAndBytesConfig(
        load_in_4bit=True,
        bnb_4bit_compute_dtype=torch.float16,
        bnb_4bit_use_double_quant=True,
        bnb_4bit_quant_type="nf4"
    )
    
    tokenizer = AutoTokenizer.from_pretrained(model_id, token=HF_TOKEN, trust_remote_code=True)
    model = AutoModelForCausalLM.from_pretrained(
        model_id,
        quantization_config=quantization_config,
        device_map="auto",
        token=HF_TOKEN,
        low_cpu_mem_usage=True,
        torch_dtype=torch.float16,
        trust_remote_code=True
    )
    
    print(f"βœ… Model auto-loaded successfully! Context window: 128K tokens")
    log_message("βœ… Model loaded and ready!")

threading.Thread(target=initialize_model, daemon=True).start()

def load_model():
    global model, tokenizer
    if model is not None:
        return "βœ… Model already loaded"
    
    log_message("πŸ”„ Loading Qwen 2.5 7B model...")
    model_id = "Qwen/Qwen2.5-7B-Instruct"
    
    quantization_config = BitsAndBytesConfig(
        load_in_4bit=True,
        bnb_4bit_compute_dtype=torch.float16,
        bnb_4bit_use_double_quant=True,
        bnb_4bit_quant_type="nf4"
    )
    
    tokenizer = AutoTokenizer.from_pretrained(model_id, token=HF_TOKEN, trust_remote_code=True)
    model = AutoModelForCausalLM.from_pretrained(
        model_id,
        quantization_config=quantization_config,
        device_map="auto",
        token=HF_TOKEN,
        low_cpu_mem_usage=True,
        torch_dtype=torch.float16,
        trust_remote_code=True
    )
    
    log_message(f"βœ… Model loaded! Context window: 128K tokens")
    return "βœ… Model loaded successfully! Ready to process."

def log_message(msg):
    timestamp = time.strftime('%H:%M:%S')
    log_entry = f"[{timestamp}] {msg}"
    processing_status["logs"].append(log_entry)
    if len(processing_status["logs"]) > 100:
        processing_status["logs"] = processing_status["logs"][-100:]
    print(log_entry)

def search_duckduckgo(query, max_results=10):
    search_url = "https://html.duckduckgo.com/html/"
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
    }
    params = {'q': query}
    
    try:
        response = requests.post(search_url, data=params, headers=headers, timeout=10)
        soup = BeautifulSoup(response.text, 'html.parser')
        results = []
        for result in soup.find_all('a', class_='result__a', limit=max_results):
            url = result.get('href')
            if url:
                results.append(url)
        return results
    except Exception as e:
        log_message(f"⚠️ Search error: {e}")
        return []

def scrape_website(url):
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
    }
    
    try:
        response = requests.get(url, headers=headers, timeout=15)
        soup = BeautifulSoup(response.text, 'html.parser')
        
        for tag in soup(['script', 'style', 'nav', 'footer', 'header', 'aside', 'iframe', 'noscript']):
            tag.decompose()
        
        paragraphs = soup.find_all(['p', 'article', 'div'], limit=100)
        text_content = []
        
        for p in paragraphs:
            text = p.get_text(strip=True)
            if len(text) > 50:
                text_content.append(text)
        
        full_text = ' '.join(text_content)
        full_text = re.sub(r'\s+', ' ', full_text).strip()
        return full_text[:20000] if full_text else ""
    except Exception as e:
        log_message(f"⚠️ Scraping error: {str(e)[:100]}")
        return ""

def summarize_with_qwen(text, event_title, query):
    if model is None or tokenizer is None:
        return "Error: Model not loaded"
    
    prompt = f"""You are an expert historian and researcher. Analyze the following text about "{event_title}" related to query "{query}".

CRITICAL INSTRUCTIONS:
1. Extract EVERY SINGLE fact, date, name, place, number, and detail
2. Do NOT skip or summarize - include ALL information
3. Organize comprehensively with maximum detail
4. Include exact quotes where significant
5. Note any contradictions or multiple perspectives

Required Structure:
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
MAIN FACTS AND CORE INFORMATION:
[List every key fact with full details]

HISTORICAL CONTEXT AND BACKGROUND:
[All contextual information, causes, conditions, prior events]

KEY FIGURES AND PEOPLE:
[Every person mentioned with their roles, actions, and significance]

COMPLETE TIMELINE AND DATES:
[All dates, periods, sequences in chronological order]

LOCATIONS AND GEOGRAPHY:
[Every place mentioned with geographic and strategic significance]

ECONOMIC AND SOCIAL FACTORS:
[Financial details, trade, social structures, class dynamics]

POLITICAL ANALYSIS AND PERSPECTIVE:
[Ideological leanings: left-wing/progressive, right-wing/conservative, nationalist, colonial, anti-colonial, neutral, etc.]

MILITARY AND STRATEGIC DETAILS:
[If applicable: battles, tactics, forces, outcomes]

SOURCES AND CITATIONS:
[Any sources, authors, or references mentioned in the text]

CONTRADICTIONS AND MULTIPLE VIEWPOINTS:
[Note any conflicting information or different interpretations]

ADDITIONAL DETAILS AND NUANCES:
[Everything else not covered above - leave nothing out]
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

TEXT TO ANALYZE:
{text[:15000]}

BEGIN COMPREHENSIVE ANALYSIS:"""

    messages = [
        {"role": "system", "content": "You are a meticulous historian who extracts and preserves every detail from historical texts without omission."},
        {"role": "user", "content": prompt}
    ]
    
    try:
        text_input = tokenizer.apply_chat_template(
            messages,
            tokenize=False,
            add_generation_prompt=True
        )
        
        model_inputs = tokenizer([text_input], return_tensors="pt").to(model.device)
        
        with torch.no_grad():
            generated_ids = model.generate(
                **model_inputs,
                max_new_tokens=3072,
                temperature=0.2,
                top_p=0.9,
                do_sample=True,
                repetition_penalty=1.1
            )
        
        generated_ids = [
            output_ids[len(input_ids):] for input_ids, output_ids in zip(model_inputs.input_ids, generated_ids)
        ]
        
        response = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]
        return response.strip()
        
    except Exception as e:
        log_message(f"❌ Generation error: {str(e)[:200]}")
        return f"Summary generation failed. Raw text captured ({len(text)} chars)."

def extract_political_bias(summary):
    summary_lower = summary.lower()
    
    left_indicators = ['progressive', 'socialist', 'liberal', 'reform', 'equality', 'workers rights', 'anti-colonial', 'revolutionary', 'peasant uprising']
    right_indicators = ['conservative', 'traditional', 'nationalist', 'colonial', 'imperial', 'order', 'establishment', 'royalist']
    neutral_indicators = ['balanced', 'objective', 'multiple perspectives', 'various viewpoints']
    
    left_count = sum(1 for word in left_indicators if word in summary_lower)
    right_count = sum(1 for word in right_indicators if word in summary_lower)
    neutral_count = sum(1 for word in neutral_indicators if word in summary_lower)
    
    if neutral_count >= 2:
        return "neutral/balanced"
    elif left_count > right_count + 2:
        return "left-wing/progressive/anti-colonial"
    elif right_count > left_count + 2:
        return "right-wing/conservative/colonial"
    elif left_count > 0 and right_count > 0:
        return "mixed-perspectives"
    else:
        return "neutral/unclear"

def save_to_dataset(data_records):
    try:
        dataset_id = f"{HF_USERNAME}/{DATASET_NAME}"
        
        try:
            existing_dataset = load_dataset(dataset_id, split='train')
            existing_data = existing_dataset.to_dict()
            
            for key in existing_data:
                existing_data[key].extend(data_records[key])
            
            combined_dataset = Dataset.from_dict(existing_data)
        except:
            combined_dataset = Dataset.from_dict(data_records)
        
        combined_dataset.push_to_hub(
            dataset_id,
            private=False,
            token=HF_TOKEN
        )
        log_message(f"βœ… Saved {len(data_records['event_id'])} records to dataset")
        processing_status["total_records"] = len(data_records['event_id'])
        
    except Exception as e:
        log_message(f"⚠️ Dataset save error: {str(e)[:200]}")
        backup_file = f'backup_data_{int(time.time())}.json'
        with open(backup_file, 'w', encoding='utf-8') as f:
            json.dump(data_records, f, indent=2, ensure_ascii=False)
        log_message(f"βœ… Backup saved to {backup_file}")

def process_events_background():
    processing_status["running"] = True
    processing_status["logs"] = []
    processing_status["total_records"] = 0
    
    try:
        if not os.path.exists(CSV_FILE):
            log_message(f"❌ CSV file '{CSV_FILE}' not found!")
            processing_status["running"] = False
            return
        
        with open(CSV_FILE, 'r', encoding='utf-8') as f:
            reader = csv.DictReader(f)
            events = list(reader)
        
        log_message(f"πŸ“‚ Loaded {len(events)} events from CSV")
        
        data_records = {
            'event_id': [],
            'title': [],
            'query': [],
            'url': [],
            'scraped_content': [],
            'summary': [],
            'political_bias': [],
            'timestamp': [],
            'content_length': [],
            'summary_length': []
        }
        
        for event in events:
            if not processing_status["running"]:
                log_message("⚠️ Processing stopped by user")
                break
                
            event_id = event['event_id']
            title = event['title']
            query = event['query']
            
            processing_status["current_event"] = f"Event {event_id}: {title}"
            
            log_message(f"\n{'='*60}")
            log_message(f"πŸ“š Event {event_id}: {title}")
            log_message(f"πŸ” Query: {query}")
            log_message(f"{'='*60}")
            
            urls = search_duckduckgo(query, max_results=15)
            log_message(f"🌐 Found {len(urls)} URLs")
            
            for idx, url in enumerate(urls):
                if not processing_status["running"]:
                    break
                    
                processing_status["progress"] = f"URL {idx+1}/{len(urls)}"
                log_message(f"\n[{idx+1}/{len(urls)}] {url[:80]}...")
                
                content = scrape_website(url)
                
                if len(content) < 200:
                    log_message("⚠️ Content too short, skipping")
                    continue
                
                log_message(f"βœ“ Scraped {len(content)} chars")
                log_message("πŸ€– Generating analysis...")
                
                summary = summarize_with_qwen(content, title, query)
                political_bias = extract_political_bias(summary)
                
                data_records['event_id'].append(event_id)
                data_records['title'].append(title)
                data_records['query'].append(query)
                data_records['url'].append(url)
                data_records['scraped_content'].append(content)
                data_records['summary'].append(summary)
                data_records['political_bias'].append(political_bias)
                data_records['timestamp'].append(time.strftime('%Y-%m-%d %H:%M:%S'))
                data_records['content_length'].append(len(content))
                data_records['summary_length'].append(len(summary))
                
                log_message(f"βœ“ Analysis done ({len(summary)} chars)")
                log_message(f"πŸ“Š Bias: {political_bias}")
                
                if len(data_records['event_id']) % 3 == 0:
                    log_message(f"πŸ’Ύ Auto-saving...")
                    save_to_dataset(data_records)
                
                time.sleep(2)
            
            log_message(f"πŸ’Ύ Saving event {event_id} data...")
            save_to_dataset(data_records)
            
            log_message(f"βœ… Event {event_id} complete!")
            log_message(f"πŸ“ˆ Total records: {len(data_records['event_id'])}")
        
        log_message("\n" + "="*60)
        log_message("πŸŽ‰ ALL EVENTS COMPLETED!")
        log_message(f"πŸ“Š Total: {len(data_records['event_id'])} records")
        log_message(f"πŸ’Ύ Dataset: {HF_USERNAME}/{DATASET_NAME}")
        log_message("="*60)
        
    except Exception as e:
        log_message(f"❌ Error: {str(e)}")
    finally:
        processing_status["running"] = False
        processing_status["current_event"] = "Idle"
        processing_status["progress"] = "Complete"

def start_processing():
    if processing_status["running"]:
        return "⚠️ Already running! Stop first to restart."
    
    if model is None:
        return "❌ Load model first!"
    
    if not os.path.exists(CSV_FILE):
        return f"❌ CSV file '{CSV_FILE}' not found in space!"
    
    thread = threading.Thread(target=process_events_background, daemon=True)
    thread.start()
    
    return "βœ… Processing started! Check logs below."

def stop_processing():
    if not processing_status["running"]:
        return "⚠️ Not running"
    processing_status["running"] = False
    return "⏹️ Stopping after current URL..."

def get_model_status():
    if model is None:
        return "πŸ”„ Loading model... (2-3 minutes)"
    return "βœ… Model ready!"

def get_status():
    status = "🟒 RUNNING" if processing_status["running"] else "πŸ”΄ IDLE"
    current = processing_status["current_event"] or "No event"
    progress = processing_status["progress"] or "β€”"
    records = str(processing_status["total_records"])
    logs = "\n".join(processing_status["logs"][-40:]) if processing_status["logs"] else "Model loading in background..."
    model_stat = get_model_status()
    
    return status, current, progress, records, logs, model_stat

with gr.Blocks(title="Historical Research Processor") as demo:
    gr.Markdown("# πŸ›οΈ Historical Research Data Processor")
    gr.Markdown(f"**CSV File:** `{CSV_FILE}` | **Dataset:** `{HF_USERNAME}/{DATASET_NAME}`")
    
    with gr.Row():
        with gr.Column(scale=1):
            gr.Markdown("### πŸŽ›οΈ Controls")
            
            model_status_display = gr.Textbox(label="Model Status", value="πŸ”„ Loading...", interactive=False)
            
            gr.Markdown("---")
            
            start_btn = gr.Button("▢️ Start Processing", variant="primary", size="lg")
            stop_btn = gr.Button("⏹️ Stop", variant="stop", size="lg")
            action_status = gr.Textbox(label="Action Result", interactive=False)
            
        with gr.Column(scale=2):
            gr.Markdown("### πŸ“Š Live Status")
            with gr.Row():
                status_box = gr.Textbox(label="Status", value="πŸ”΄ IDLE", interactive=False)
                records_box = gr.Textbox(label="Total Records", value="0", interactive=False)
            
            current_event_box = gr.Textbox(label="Current Event", value="No event", interactive=False)
            progress_box = gr.Textbox(label="Progress", value="β€”", interactive=False)
    
    gr.Markdown("### πŸ“ Processing Logs (Auto-updates every 3 seconds)")
    logs_box = gr.Textbox(label="", lines=18, max_lines=25, interactive=False, show_label=False)
    
    start_btn.click(fn=start_processing, outputs=action_status)
    stop_btn.click(fn=stop_processing, outputs=action_status)
    
    demo.load(
        fn=get_status, 
        outputs=[status_box, current_event_box, progress_box, records_box, logs_box, model_status_display]
    )
    
    gr.Timer(3).tick(
        fn=get_status,
        outputs=[status_box, current_event_box, progress_box, records_box, logs_box, model_status_display]
    )

if __name__ == "__main__":
    demo.queue()
    demo.launch(server_name="0.0.0.0", server_port=7860, theme=gr.themes.Soft())