sssravi commited on
Commit
6d2b8ea
·
1 Parent(s): cb2801d

Added new files

Browse files
Files changed (1) hide show
  1. app.py +0 -291
app.py CHANGED
@@ -7,15 +7,6 @@ import random
7
  import tempfile
8
  from urllib.parse import urlparse
9
  from tqdm import tqdm
10
- import os
11
- import sys
12
- import json
13
- import time
14
- import asyncio
15
- import random
16
- import tempfile
17
- from urllib.parse import urlparse
18
- from tqdm import tqdm
19
  import gradio as gr
20
 
21
  # Import core libraries
@@ -298,289 +289,7 @@ with gr.Blocks(theme=gr.themes.Soft()) as demo:
298
  inputs=[query_input]
299
  )
300
 
301
- # Import core libraries
302
- import pandas as pd
303
- import numpy as np
304
- import faiss
305
- from bson import ObjectId
306
- from pymongo import MongoClient
307
- from sentence_transformers import SentenceTransformer
308
- from openai import OpenAI
309
- from playwright.async_api import async_playwright
310
- from PIL import Image, ImageChops, ImageOps, ExifTags
311
- from reportlab.lib.pagesizes import A4
312
- from reportlab.pdfgen import canvas
313
- from reportlab.lib import colors
314
- import nest_asyncio
315
-
316
- # Apply nest_asyncio to allow running asyncio in environments like Jupyter/Colab
317
- nest_asyncio.apply()
318
-
319
- # ==============================================================================
320
- # CONFIGURATION
321
- # ==============================================================================
322
- # NOTE: File paths are relative to the Hugging Face Space repository root.
323
- # You MUST upload your FAISS index and metadata file to your Space.
324
- FAISS_INDEX_FILE = "news_index.faiss"
325
- METADATA_FILE = "news_metadata.json"
326
-
327
- # --- Other Settings ---
328
- DB_NAME = "news_db"
329
- COLLECTION_NAME = "news_aggregator"
330
- EMBEDDING_MODEL = "google/embeddinggemma-300m"
331
- OPENAI_MODEL = "gpt-4o-mini"
332
- OUTPUT_DIR = "outputs"
333
- SCREENSHOT_DIR = os.path.join(OUTPUT_DIR, "screenshots")
334
- REPORTS_DIR = os.path.join(OUTPUT_DIR, "reports")
335
- TOP_K_RETRIEVAL = 10
336
- MAX_ARTICLES_TO_PROCESS = 5 # Keep this low for a web demo to avoid timeouts
337
- WEB_HEADLESS = True
338
-
339
- TRUSTED_DOMAINS = {
340
- "reuters.com", "bbc.co.uk", "nytimes.com", "theguardian.com",
341
- "washingtonpost.com", "bloomberg.com", "wsj.com", "timesofindia.indiatimes.com",
342
- "thehindu.com", "hindustantimes.com", "indianexpress.com", "ndtv.com",
343
- }
344
-
345
- os.makedirs(SCREENSHOT_DIR, exist_ok=True)
346
- os.makedirs(REPORTS_DIR, exist_ok=True)
347
-
348
- # ==============================================================================
349
- # CORE LOGIC CLASSES (Adapted for Gradio)
350
- # ==============================================================================
351
-
352
- class NewsRetriever:
353
- """Handles retrieving articles. Models are loaded once on initialization."""
354
- _instance = None
355
-
356
- def __new__(cls, *args, **kwargs):
357
- if cls._instance is None:
358
- cls._instance = super(NewsRetriever, cls).__new__(cls)
359
- # Initialize models and data files only once
360
- print("🔹 Initializing NewsRetriever singleton...")
361
- cls._instance.index = faiss.read_index(FAISS_INDEX_FILE)
362
- with open(METADATA_FILE, "r", encoding="utf-8") as f:
363
- cls._instance.metadata = json.load(f)
364
- cls._instance.model = SentenceTransformer(EMBEDDING_MODEL)
365
- print("✅ FAISS index, metadata, and embedding model loaded.")
366
- return cls._instance
367
-
368
- def retrieve_and_filter(self, query, mongo_uri, k=TOP_K_RETRIEVAL):
369
- client = MongoClient(mongo_uri)
370
- db_collection = client[DB_NAME][COLLECTION_NAME]
371
-
372
- qvec = self.model.encode([query], convert_to_numpy=True).astype('float32')
373
- faiss.normalize_L2(qvec)
374
-
375
- distances, indices = self.index.search(qvec, k)
376
- results = [{"_id": self.metadata[i]["_id"]} for i in indices[0] if i < len(self.metadata)]
377
-
378
- doc_ids = [ObjectId(res["_id"]) for res in results]
379
- mongo_docs = list(db_collection.find({"_id": {"$in": doc_ids}}))
380
-
381
- full_docs = []
382
- for doc in mongo_docs:
383
- link = doc.get("link", "")
384
- host = urlparse(link).netloc.lower()
385
- if any(td in host for td in TRUSTED_DOMAINS):
386
- full_docs.append({
387
- "_id": str(doc["_id"]),
388
- "headline": doc.get("headline_translated") or doc.get("headline_original") or "",
389
- "description": doc.get("description_translated") or doc.get("description_original") or "",
390
- "link": link,
391
- })
392
- client.close()
393
- return full_docs
394
-
395
- class ArticleProcessor:
396
- """Handles web scraping and summarization."""
397
- async def process_articles(self, articles: list, openai_key: str, progress: gr.Progress):
398
- out_rows = []
399
- client = OpenAI(api_key=openai_key)
400
-
401
- async with async_playwright() as p:
402
- # On Hugging Face, Playwright needs to use the installed Chromium
403
- browser = await p.chromium.launch(headless=WEB_HEADLESS)
404
- for i, rec in enumerate(articles):
405
- progress(i / len(articles), desc=f"Processing article {i+1}/{len(articles)}: {rec['headline'][:30]}...")
406
-
407
- url = rec.get("link","")
408
- if not url: continue
409
-
410
- context = await browser.new_context()
411
- page = await context.new_page()
412
-
413
- try:
414
- await page.goto(url, timeout=45000)
415
- await asyncio.sleep(2) # Wait for page to settle
416
-
417
- fname = f"{rec['_id']}.png"
418
- out_path = os.path.join(SCREENSHOT_DIR, fname)
419
- await page.screenshot(path=out_path)
420
-
421
- article_text = await page.evaluate("document.body.innerText")
422
-
423
- # Summarize with OpenAI
424
- prompt = f"Summarize the following article in a neutral, factual paragraph:\n\nTitle: {rec['headline']}\n\n{article_text[:4000]}"
425
- response = client.chat.completions.create(model=OPENAI_MODEL, messages=[{"role": "user", "content": prompt}], temperature=0.0)
426
- narrative = response.choices[0].message.content.strip()
427
-
428
- out_rows.append({"id": rec["_id"], "title": rec["headline"], "narrative": narrative, "screenshot_path": out_path, "url": url})
429
-
430
- except Exception as e:
431
- print(f"Failed to process {url}: {e}")
432
- out_rows.append({"id": rec["_id"], "title": rec["headline"], "narrative": "Could not process this article.", "screenshot_path": "", "url": url})
433
-
434
- finally:
435
- await page.close()
436
- await context.close()
437
-
438
- await browser.close()
439
- return out_rows
440
-
441
- class PDFReportGenerator:
442
- """Generates the final PDF report."""
443
- def _wrap_lines(self, c, text, fontname, fontsize, max_width):
444
- text = str(text or "")
445
- lines = []
446
- for paragraph in text.split('\n'):
447
- words, line = paragraph.split(' '), ''
448
- for word in words:
449
- if c.stringWidth(word, fontname, fontsize) > max_width:
450
- if line: lines.append(line)
451
- temp_word = ''
452
- for char in word:
453
- if c.stringWidth(temp_word + char, fontname, fontsize) < max_width: temp_word += char
454
- else: lines.append(temp_word); temp_word = char
455
- line = temp_word
456
- elif c.stringWidth((line + ' ' + word).strip(), fontname, fontsize) <= max_width:
457
- line = (line + ' ' + word).strip()
458
- else: lines.append(line); line = word
459
- if line: lines.append(line)
460
- return lines
461
-
462
- def generate(self, df, query, progress: gr.Progress):
463
- final_pdf_path = tempfile.NamedTemporaryFile(delete=False, suffix=".pdf").name
464
- c = canvas.Canvas(final_pdf_path, pagesize=A4)
465
- PAGE_W, PAGE_H = A4; LEFT_PAD, RIGHT_PAD, TOP_PAD, BOTTOM_PAD = 50, 50, 50, 50
466
- PRINTABLE_W = PAGE_W - LEFT_PAD - RIGHT_PAD
467
-
468
- # Fonts
469
- HEADER_FONT, HEADER_SIZE = "Helvetica-Bold", 16
470
- TITLE_FONT, TITLE_SIZE, TITLE_LEADING = "Helvetica-Bold", 12, 16
471
- NARRATIVE_FONT, NARRATIVE_SIZE, NARRATIVE_LEADING = "Helvetica", 10, 14
472
- LINK_FONT, LINK_SIZE, LINK_COLOR = "Helvetica-Oblique", 9, colors.blue
473
-
474
- # Header
475
- c.setFont(HEADER_FONT, HEADER_SIZE)
476
- c.drawCentredString(PAGE_W / 2, PAGE_H - TOP_PAD, f"News Report: {query}")
477
- current_y = PAGE_H - TOP_PAD - 30
478
-
479
- for i, row in df.iterrows():
480
- progress(i / len(df), desc=f"Adding article {i+1}/{len(df)} to PDF...")
481
-
482
- title_lines = self._wrap_lines(c, row['title'], TITLE_FONT, TITLE_SIZE, PRINTABLE_W)
483
- narrative_lines = self._wrap_lines(c, row['narrative'], NARRATIVE_FONT, NARRATIVE_SIZE, PRINTABLE_W)
484
- link_lines = self._wrap_lines(c, row['url'], LINK_FONT, LINK_SIZE, PRINTABLE_W)
485
-
486
- # Estimate block height and check for page break
487
- img_h = 200 if os.path.exists(row['screenshot_path']) else 0
488
- block_h = (len(title_lines) * TITLE_LEADING + len(narrative_lines) * NARRATIVE_LEADING +
489
- len(link_lines) * 12 + img_h + 40)
490
-
491
- if current_y - block_h < BOTTOM_PAD:
492
- c.showPage(); current_y = PAGE_H - TOP_PAD
493
-
494
- # Draw content
495
- c.setFont(TITLE_FONT, TITLE_SIZE); c.setFillColor(colors.black)
496
- for line in title_lines: c.drawString(LEFT_PAD, current_y, line); current_y -= TITLE_LEADING
497
- current_y -= 5
498
-
499
- c.setFont(NARRATIVE_FONT, NARRATIVE_SIZE)
500
- for line in narrative_lines: c.drawString(LEFT_PAD, current_y, line); current_y -= NARRATIVE_LEADING
501
- current_y -= 10
502
-
503
- if os.path.exists(row['screenshot_path']):
504
- try: c.drawImage(row['screenshot_path'], LEFT_PAD, current_y - 180, width=PRINTABLE_W, height=180, preserveAspectRatio=True)
505
- except Exception: pass
506
- current_y -= 190
507
-
508
- c.setFont(LINK_FONT, LINK_SIZE); c.setFillColor(LINK_COLOR)
509
- for line in link_lines: c.drawString(LEFT_PAD, current_y, line); current_y -= 12
510
- current_y -= 25
511
-
512
- c.save()
513
- return final_pdf_path
514
-
515
- # ==============================================================================
516
- # GRADIO INTERFACE
517
- # ==============================================================================
518
-
519
- async def run_pipeline(query, mongo_uri, openai_key, progress=gr.Progress(track_tqdm=True)):
520
- if not all([query, mongo_uri, openai_key]):
521
- raise gr.Error("Please provide a query and both API keys.")
522
-
523
- try:
524
- # Step 1: Retrieve Articles
525
- progress(0, desc="Initializing and retrieving articles...")
526
- retriever = NewsRetriever()
527
- validated_articles = retriever.retrieve_and_filter(query, mongo_uri)
528
- if not validated_articles:
529
- raise gr.Error("No trusted articles found for the query.")
530
-
531
- # Step 2: Process Articles
532
- articles_to_process = validated_articles[:MAX_ARTICLES_TO_PROCESS]
533
- processor = ArticleProcessor()
534
- processed_results = await processor.process_articles(articles_to_process, openai_key, progress)
535
- if not processed_results:
536
- raise gr.Error("Failed to process articles.")
537
-
538
- # Step 3: Generate PDF
539
- processed_df = pd.DataFrame(processed_results)
540
- reporter = PDFReportGenerator()
541
- pdf_path = reporter.generate(processed_df, query, progress)
542
-
543
- return pdf_path
544
-
545
- except Exception as e:
546
- # Log the full error for debugging on the Space
547
- print(f"An error occurred: {e}")
548
- # Raise a user-friendly error in the Gradio UI
549
- raise gr.Error(f"An error occurred during processing. Please check the logs in the Space. Details: {str(e)}")
550
-
551
-
552
- # --- UI Layout ---
553
- with gr.Blocks(theme=gr.themes.Soft()) as demo:
554
- gr.Markdown("# 📰 AI-Powered News Report Generator")
555
- gr.Markdown("Enter a topic to generate a PDF report summarizing the latest news from trusted sources.")
556
-
557
- with gr.Row():
558
- with gr.Column(scale=2):
559
- query_input = gr.Textbox(label="Enter News Topic", placeholder="e.g., 'Latest advancements in AI'")
560
- mongo_uri_input = gr.Textbox(label="MongoDB URI", type="password", placeholder="mongodb+srv://srinivasa_varahe:SiQZzpCDuENhbnPt@newsdatabase.5u5rsy.mongodb.net")
561
- openai_key_input = gr.Textbox(label="OpenAI API Key", type="password", placeholder="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")
562
- submit_button = gr.Button("Generate Report", variant="primary")
563
-
564
- with gr.Column(scale=3):
565
- gr.Markdown("### Your Report")
566
- output_file = gr.File(label="Download PDF Report")
567
-
568
- submit_button.click(
569
- fn=run_pipeline,
570
- inputs=[query_input, mongo_uri_input, openai_key_input],
571
- outputs=[output_file]
572
- )
573
-
574
- gr.Examples(
575
- [["Impact of climate change on agriculture in India"],
576
- ["Global semiconductor industry trends"],
577
- ["Future of renewable energy in Europe"]],
578
- inputs=[query_input]
579
- )
580
-
581
  if __name__ == "__main__":
582
- # To run locally, ensure you have your FAISS/metadata files in the same directory.
583
- # Also, ensure you have run 'playwright install chromium'.
584
  # To run locally, ensure you have your FAISS/metadata files in the same directory.
585
  # Also, ensure you have run 'playwright install chromium'.
586
  demo.launch()
 
7
  import tempfile
8
  from urllib.parse import urlparse
9
  from tqdm import tqdm
 
 
 
 
 
 
 
 
 
10
  import gradio as gr
11
 
12
  # Import core libraries
 
289
  inputs=[query_input]
290
  )
291
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
292
  if __name__ == "__main__":
 
 
293
  # To run locally, ensure you have your FAISS/metadata files in the same directory.
294
  # Also, ensure you have run 'playwright install chromium'.
295
  demo.launch()