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())