Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -9,6 +9,8 @@ from huggingface_hub import HfApi, login
|
|
| 9 |
import re
|
| 10 |
import torch
|
| 11 |
from transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig
|
|
|
|
|
|
|
| 12 |
|
| 13 |
HF_TOKEN = os.environ.get("HF_TOKEN")
|
| 14 |
if HF_TOKEN:
|
|
@@ -17,50 +19,65 @@ if HF_TOKEN:
|
|
| 17 |
DATASET_NAME = "historical_research_data"
|
| 18 |
HF_USERNAME = os.environ.get("HF_USERNAME", "your_username")
|
| 19 |
|
| 20 |
-
|
| 21 |
-
|
|
|
|
| 22 |
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
)
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
trust_remote_code=True
|
| 39 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 40 |
|
| 41 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 42 |
|
| 43 |
def search_duckduckgo(query, max_results=10):
|
| 44 |
search_url = "https://html.duckduckgo.com/html/"
|
| 45 |
headers = {
|
| 46 |
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
|
| 47 |
}
|
| 48 |
-
|
| 49 |
params = {'q': query}
|
| 50 |
|
| 51 |
try:
|
| 52 |
response = requests.post(search_url, data=params, headers=headers, timeout=10)
|
| 53 |
soup = BeautifulSoup(response.text, 'html.parser')
|
| 54 |
-
|
| 55 |
results = []
|
| 56 |
for result in soup.find_all('a', class_='result__a', limit=max_results):
|
| 57 |
url = result.get('href')
|
| 58 |
if url:
|
| 59 |
results.append(url)
|
| 60 |
-
|
| 61 |
return results
|
| 62 |
except Exception as e:
|
| 63 |
-
|
| 64 |
return []
|
| 65 |
|
| 66 |
def scrape_website(url):
|
|
@@ -85,13 +102,15 @@ def scrape_website(url):
|
|
| 85 |
|
| 86 |
full_text = ' '.join(text_content)
|
| 87 |
full_text = re.sub(r'\s+', ' ', full_text).strip()
|
| 88 |
-
|
| 89 |
return full_text[:20000] if full_text else ""
|
| 90 |
except Exception as e:
|
| 91 |
-
|
| 92 |
return ""
|
| 93 |
|
| 94 |
def summarize_with_qwen(text, event_title, query):
|
|
|
|
|
|
|
|
|
|
| 95 |
prompt = f"""You are an expert historian and researcher. Analyze the following text about "{event_title}" related to query "{query}".
|
| 96 |
|
| 97 |
CRITICAL INSTRUCTIONS:
|
|
@@ -171,11 +190,10 @@ BEGIN COMPREHENSIVE ANALYSIS:"""
|
|
| 171 |
]
|
| 172 |
|
| 173 |
response = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]
|
| 174 |
-
|
| 175 |
return response.strip()
|
| 176 |
|
| 177 |
except Exception as e:
|
| 178 |
-
|
| 179 |
return f"Summary generation failed. Raw text captured ({len(text)} chars). Error: {str(e)}"
|
| 180 |
|
| 181 |
def extract_political_bias(summary):
|
|
@@ -220,95 +238,169 @@ def save_to_dataset(data_records):
|
|
| 220 |
private=False,
|
| 221 |
token=HF_TOKEN
|
| 222 |
)
|
| 223 |
-
|
| 224 |
|
| 225 |
except Exception as e:
|
| 226 |
-
|
| 227 |
backup_file = f'backup_data_{int(time.time())}.json'
|
| 228 |
with open(backup_file, 'w', encoding='utf-8') as f:
|
| 229 |
json.dump(data_records, f, indent=2, ensure_ascii=False)
|
| 230 |
-
|
| 231 |
|
| 232 |
-
def
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
events = list(reader)
|
| 236 |
-
|
| 237 |
-
data_records = {
|
| 238 |
-
'event_id': [],
|
| 239 |
-
'title': [],
|
| 240 |
-
'query': [],
|
| 241 |
-
'url': [],
|
| 242 |
-
'scraped_content': [],
|
| 243 |
-
'summary': [],
|
| 244 |
-
'political_bias': [],
|
| 245 |
-
'timestamp': [],
|
| 246 |
-
'content_length': [],
|
| 247 |
-
'summary_length': []
|
| 248 |
-
}
|
| 249 |
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
print(f"\n{'='*80}")
|
| 256 |
-
print(f"π Processing Event {event_id}: {title}")
|
| 257 |
-
print(f"π Query: {query}")
|
| 258 |
-
print(f"{'='*80}\n")
|
| 259 |
|
| 260 |
-
|
| 261 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 262 |
|
| 263 |
-
for
|
| 264 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 265 |
|
| 266 |
-
|
| 267 |
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
|
|
|
|
| 271 |
|
| 272 |
-
|
| 273 |
-
|
| 274 |
|
| 275 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 276 |
|
| 277 |
-
|
|
|
|
| 278 |
|
| 279 |
-
|
| 280 |
-
data_records['
|
| 281 |
-
data_records['query'].append(query)
|
| 282 |
-
data_records['url'].append(url)
|
| 283 |
-
data_records['scraped_content'].append(content)
|
| 284 |
-
data_records['summary'].append(summary)
|
| 285 |
-
data_records['political_bias'].append(political_bias)
|
| 286 |
-
data_records['timestamp'].append(time.strftime('%Y-%m-%d %H:%M:%S'))
|
| 287 |
-
data_records['content_length'].append(len(content))
|
| 288 |
-
data_records['summary_length'].append(len(summary))
|
| 289 |
-
|
| 290 |
-
print(f"β Analysis complete ({len(summary)} chars)")
|
| 291 |
-
print(f"π Political perspective: {political_bias}")
|
| 292 |
-
|
| 293 |
-
if len(data_records['event_id']) % 3 == 0:
|
| 294 |
-
print(f"\nπΎ Auto-saving progress...")
|
| 295 |
-
save_to_dataset(data_records)
|
| 296 |
-
|
| 297 |
-
time.sleep(2)
|
| 298 |
|
| 299 |
-
|
| 300 |
-
|
|
|
|
|
|
|
|
|
|
| 301 |
|
| 302 |
-
|
| 303 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 304 |
|
| 305 |
-
|
| 306 |
-
|
| 307 |
-
|
| 308 |
-
|
| 309 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 310 |
|
| 311 |
-
|
| 312 |
-
|
|
|
|
|
|
|
|
|
|
| 313 |
|
| 314 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
import re
|
| 10 |
import torch
|
| 11 |
from transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig
|
| 12 |
+
import gradio as gr
|
| 13 |
+
import threading
|
| 14 |
|
| 15 |
HF_TOKEN = os.environ.get("HF_TOKEN")
|
| 16 |
if HF_TOKEN:
|
|
|
|
| 19 |
DATASET_NAME = "historical_research_data"
|
| 20 |
HF_USERNAME = os.environ.get("HF_USERNAME", "your_username")
|
| 21 |
|
| 22 |
+
model = None
|
| 23 |
+
tokenizer = None
|
| 24 |
+
processing_status = {"running": False, "logs": [], "current_event": "", "progress": ""}
|
| 25 |
|
| 26 |
+
def load_model():
|
| 27 |
+
global model, tokenizer
|
| 28 |
+
if model is not None:
|
| 29 |
+
return "Model already loaded"
|
| 30 |
+
|
| 31 |
+
log_message("Loading Qwen 2.5 7B model...")
|
| 32 |
+
model_id = "Qwen/Qwen2.5-7B-Instruct"
|
| 33 |
+
|
| 34 |
+
quantization_config = BitsAndBytesConfig(
|
| 35 |
+
load_in_4bit=True,
|
| 36 |
+
bnb_4bit_compute_dtype=torch.float16,
|
| 37 |
+
bnb_4bit_use_double_quant=True,
|
| 38 |
+
bnb_4bit_quant_type="nf4"
|
| 39 |
+
)
|
| 40 |
+
|
| 41 |
+
tokenizer = AutoTokenizer.from_pretrained(model_id, token=HF_TOKEN, trust_remote_code=True)
|
| 42 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 43 |
+
model_id,
|
| 44 |
+
quantization_config=quantization_config,
|
| 45 |
+
device_map="auto",
|
| 46 |
+
token=HF_TOKEN,
|
| 47 |
+
low_cpu_mem_usage=True,
|
| 48 |
+
torch_dtype=torch.float16,
|
| 49 |
+
trust_remote_code=True
|
| 50 |
+
)
|
| 51 |
+
|
| 52 |
+
log_message(f"β
Model loaded! Context window: 128K tokens")
|
| 53 |
+
return "Model loaded successfully!"
|
| 54 |
|
| 55 |
+
def log_message(msg):
|
| 56 |
+
timestamp = time.strftime('%Y-%m-%d %H:%M:%S')
|
| 57 |
+
log_entry = f"[{timestamp}] {msg}"
|
| 58 |
+
processing_status["logs"].append(log_entry)
|
| 59 |
+
if len(processing_status["logs"]) > 200:
|
| 60 |
+
processing_status["logs"] = processing_status["logs"][-200:]
|
| 61 |
+
print(log_entry)
|
| 62 |
|
| 63 |
def search_duckduckgo(query, max_results=10):
|
| 64 |
search_url = "https://html.duckduckgo.com/html/"
|
| 65 |
headers = {
|
| 66 |
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
|
| 67 |
}
|
|
|
|
| 68 |
params = {'q': query}
|
| 69 |
|
| 70 |
try:
|
| 71 |
response = requests.post(search_url, data=params, headers=headers, timeout=10)
|
| 72 |
soup = BeautifulSoup(response.text, 'html.parser')
|
|
|
|
| 73 |
results = []
|
| 74 |
for result in soup.find_all('a', class_='result__a', limit=max_results):
|
| 75 |
url = result.get('href')
|
| 76 |
if url:
|
| 77 |
results.append(url)
|
|
|
|
| 78 |
return results
|
| 79 |
except Exception as e:
|
| 80 |
+
log_message(f"Search error: {e}")
|
| 81 |
return []
|
| 82 |
|
| 83 |
def scrape_website(url):
|
|
|
|
| 102 |
|
| 103 |
full_text = ' '.join(text_content)
|
| 104 |
full_text = re.sub(r'\s+', ' ', full_text).strip()
|
|
|
|
| 105 |
return full_text[:20000] if full_text else ""
|
| 106 |
except Exception as e:
|
| 107 |
+
log_message(f"Scraping error for {url}: {e}")
|
| 108 |
return ""
|
| 109 |
|
| 110 |
def summarize_with_qwen(text, event_title, query):
|
| 111 |
+
if model is None or tokenizer is None:
|
| 112 |
+
return "Error: Model not loaded"
|
| 113 |
+
|
| 114 |
prompt = f"""You are an expert historian and researcher. Analyze the following text about "{event_title}" related to query "{query}".
|
| 115 |
|
| 116 |
CRITICAL INSTRUCTIONS:
|
|
|
|
| 190 |
]
|
| 191 |
|
| 192 |
response = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]
|
|
|
|
| 193 |
return response.strip()
|
| 194 |
|
| 195 |
except Exception as e:
|
| 196 |
+
log_message(f"Generation error: {e}")
|
| 197 |
return f"Summary generation failed. Raw text captured ({len(text)} chars). Error: {str(e)}"
|
| 198 |
|
| 199 |
def extract_political_bias(summary):
|
|
|
|
| 238 |
private=False,
|
| 239 |
token=HF_TOKEN
|
| 240 |
)
|
| 241 |
+
log_message(f"β Saved {len(data_records['event_id'])} records to dataset")
|
| 242 |
|
| 243 |
except Exception as e:
|
| 244 |
+
log_message(f"Dataset save error: {e}")
|
| 245 |
backup_file = f'backup_data_{int(time.time())}.json'
|
| 246 |
with open(backup_file, 'w', encoding='utf-8') as f:
|
| 247 |
json.dump(data_records, f, indent=2, ensure_ascii=False)
|
| 248 |
+
log_message(f"β Backup saved to {backup_file}")
|
| 249 |
|
| 250 |
+
def process_events_background(csv_content):
|
| 251 |
+
processing_status["running"] = True
|
| 252 |
+
processing_status["logs"] = []
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 253 |
|
| 254 |
+
try:
|
| 255 |
+
lines = csv_content.strip().split('\n')
|
| 256 |
+
reader = csv.DictReader(lines)
|
| 257 |
+
events = list(reader)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 258 |
|
| 259 |
+
data_records = {
|
| 260 |
+
'event_id': [],
|
| 261 |
+
'title': [],
|
| 262 |
+
'query': [],
|
| 263 |
+
'url': [],
|
| 264 |
+
'scraped_content': [],
|
| 265 |
+
'summary': [],
|
| 266 |
+
'political_bias': [],
|
| 267 |
+
'timestamp': [],
|
| 268 |
+
'content_length': [],
|
| 269 |
+
'summary_length': []
|
| 270 |
+
}
|
| 271 |
|
| 272 |
+
for event in events:
|
| 273 |
+
if not processing_status["running"]:
|
| 274 |
+
log_message("β οΈ Processing stopped by user")
|
| 275 |
+
break
|
| 276 |
+
|
| 277 |
+
event_id = event['event_id']
|
| 278 |
+
title = event['title']
|
| 279 |
+
query = event['query']
|
| 280 |
|
| 281 |
+
processing_status["current_event"] = f"Event {event_id}: {title}"
|
| 282 |
|
| 283 |
+
log_message(f"\n{'='*80}")
|
| 284 |
+
log_message(f"π Processing Event {event_id}: {title}")
|
| 285 |
+
log_message(f"π Query: {query}")
|
| 286 |
+
log_message(f"{'='*80}\n")
|
| 287 |
|
| 288 |
+
urls = search_duckduckgo(query, max_results=15)
|
| 289 |
+
log_message(f"π Found {len(urls)} URLs to process")
|
| 290 |
|
| 291 |
+
for idx, url in enumerate(urls):
|
| 292 |
+
if not processing_status["running"]:
|
| 293 |
+
break
|
| 294 |
+
|
| 295 |
+
processing_status["progress"] = f"URL {idx+1}/{len(urls)}"
|
| 296 |
+
log_message(f"\n[{idx+1}/{len(urls)}] Processing: {url[:100]}...")
|
| 297 |
+
|
| 298 |
+
content = scrape_website(url)
|
| 299 |
+
|
| 300 |
+
if len(content) < 200:
|
| 301 |
+
log_message("β οΈ Content too short, skipping...")
|
| 302 |
+
continue
|
| 303 |
+
|
| 304 |
+
log_message(f"β Scraped {len(content)} characters")
|
| 305 |
+
log_message("π€ Generating comprehensive analysis...")
|
| 306 |
+
|
| 307 |
+
summary = summarize_with_qwen(content, title, query)
|
| 308 |
+
political_bias = extract_political_bias(summary)
|
| 309 |
+
|
| 310 |
+
data_records['event_id'].append(event_id)
|
| 311 |
+
data_records['title'].append(title)
|
| 312 |
+
data_records['query'].append(query)
|
| 313 |
+
data_records['url'].append(url)
|
| 314 |
+
data_records['scraped_content'].append(content)
|
| 315 |
+
data_records['summary'].append(summary)
|
| 316 |
+
data_records['political_bias'].append(political_bias)
|
| 317 |
+
data_records['timestamp'].append(time.strftime('%Y-%m-%d %H:%M:%S'))
|
| 318 |
+
data_records['content_length'].append(len(content))
|
| 319 |
+
data_records['summary_length'].append(len(summary))
|
| 320 |
+
|
| 321 |
+
log_message(f"β Analysis complete ({len(summary)} chars)")
|
| 322 |
+
log_message(f"π Political perspective: {political_bias}")
|
| 323 |
+
|
| 324 |
+
if len(data_records['event_id']) % 3 == 0:
|
| 325 |
+
log_message(f"\nπΎ Auto-saving progress...")
|
| 326 |
+
save_to_dataset(data_records)
|
| 327 |
+
|
| 328 |
+
time.sleep(2)
|
| 329 |
|
| 330 |
+
log_message(f"\nπΎ Saving all data for event {event_id}...")
|
| 331 |
+
save_to_dataset(data_records)
|
| 332 |
|
| 333 |
+
log_message(f"\nβ
Completed event {event_id}: {title}")
|
| 334 |
+
log_message(f"π Total records collected: {len(data_records['event_id'])}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 335 |
|
| 336 |
+
log_message("\n" + "="*80)
|
| 337 |
+
log_message("π ALL EVENTS PROCESSED SUCCESSFULLY")
|
| 338 |
+
log_message(f"π Total records: {len(data_records['event_id'])}")
|
| 339 |
+
log_message(f"πΎ Dataset: {HF_USERNAME}/{DATASET_NAME}")
|
| 340 |
+
log_message("="*80)
|
| 341 |
|
| 342 |
+
except Exception as e:
|
| 343 |
+
log_message(f"β Error: {str(e)}")
|
| 344 |
+
finally:
|
| 345 |
+
processing_status["running"] = False
|
| 346 |
+
processing_status["current_event"] = "Idle"
|
| 347 |
+
processing_status["progress"] = ""
|
| 348 |
+
|
| 349 |
+
def start_processing(csv_file):
|
| 350 |
+
if processing_status["running"]:
|
| 351 |
+
return "Already processing! Stop current job first."
|
| 352 |
|
| 353 |
+
if csv_file is None:
|
| 354 |
+
return "Please upload a CSV file"
|
| 355 |
+
|
| 356 |
+
csv_content = csv_file.decode('utf-8')
|
| 357 |
+
|
| 358 |
+
thread = threading.Thread(target=process_events_background, args=(csv_content,))
|
| 359 |
+
thread.daemon = True
|
| 360 |
+
thread.start()
|
| 361 |
+
|
| 362 |
+
return "β
Processing started! Check logs below for progress."
|
| 363 |
+
|
| 364 |
+
def stop_processing():
|
| 365 |
+
processing_status["running"] = False
|
| 366 |
+
return "β οΈ Stopping after current URL completes..."
|
| 367 |
|
| 368 |
+
def get_status():
|
| 369 |
+
status = "π’ Running" if processing_status["running"] else "π΄ Stopped"
|
| 370 |
+
current = processing_status["current_event"] or "Idle"
|
| 371 |
+
progress = processing_status["progress"] or ""
|
| 372 |
+
logs = "\n".join(processing_status["logs"][-50:])
|
| 373 |
|
| 374 |
+
return status, current, progress, logs
|
| 375 |
+
|
| 376 |
+
with gr.Blocks(title="Historical Research Processor") as demo:
|
| 377 |
+
gr.Markdown("# ποΈ Historical Research Data Processor")
|
| 378 |
+
gr.Markdown("Upload your CSV file and click Start to begin continuous processing")
|
| 379 |
+
|
| 380 |
+
with gr.Row():
|
| 381 |
+
with gr.Column():
|
| 382 |
+
csv_input = gr.File(label="Upload CSV File", file_types=[".csv"])
|
| 383 |
+
load_btn = gr.Button("1οΈβ£ Load Model First", variant="secondary")
|
| 384 |
+
load_status = gr.Textbox(label="Model Status", value="Not loaded")
|
| 385 |
+
|
| 386 |
+
with gr.Column():
|
| 387 |
+
start_btn = gr.Button("2οΈβ£ Start Processing", variant="primary")
|
| 388 |
+
stop_btn = gr.Button("β Stop Processing", variant="stop")
|
| 389 |
+
result = gr.Textbox(label="Action Result")
|
| 390 |
+
|
| 391 |
+
gr.Markdown("### π Processing Status")
|
| 392 |
+
with gr.Row():
|
| 393 |
+
status_box = gr.Textbox(label="Status", value="π΄ Stopped")
|
| 394 |
+
current_event_box = gr.Textbox(label="Current Event")
|
| 395 |
+
progress_box = gr.Textbox(label="Progress")
|
| 396 |
+
|
| 397 |
+
logs_box = gr.Textbox(label="Recent Logs (auto-updates)", lines=20, max_lines=30)
|
| 398 |
+
|
| 399 |
+
load_btn.click(fn=load_model, outputs=load_status)
|
| 400 |
+
start_btn.click(fn=start_processing, inputs=csv_input, outputs=result)
|
| 401 |
+
stop_btn.click(fn=stop_processing, outputs=result)
|
| 402 |
+
|
| 403 |
+
demo.load(fn=get_status, outputs=[status_box, current_event_box, progress_box, logs_box], every=3)
|
| 404 |
+
|
| 405 |
+
demo.queue()
|
| 406 |
+
demo.launch(server_name="0.0.0.0", server_port=7860, share=False)
|