import os import sys import json import time import asyncio import random import tempfile from urllib.parse import urlparse from tqdm import tqdm import gradio as gr # Import core libraries import pandas as pd import numpy as np import faiss from bson import ObjectId from pymongo import MongoClient from sentence_transformers import SentenceTransformer from openai import OpenAI from playwright.async_api import async_playwright from PIL import Image, ImageChops, ImageOps, ExifTags from reportlab.lib.pagesizes import A4 from reportlab.pdfgen import canvas from reportlab.lib import colors import nest_asyncio # Apply nest_asyncio to allow running asyncio in environments like Jupyter/Colab nest_asyncio.apply() # ============================================================================== # CONFIGURATION # ============================================================================== # NOTE: File paths are relative to the Hugging Face Space repository root. # You MUST upload your FAISS index and metadata file to your Space. FAISS_INDEX_FILE = "news_index.faiss" METADATA_FILE = "news_metadata.json" # --- Other Settings --- DB_NAME = "news_db" COLLECTION_NAME = "news_aggregator" EMBEDDING_MODEL = "google/embeddinggemma-300m" OPENAI_MODEL = "gpt-4o-mini" OUTPUT_DIR = "outputs" SCREENSHOT_DIR = os.path.join(OUTPUT_DIR, "screenshots") REPORTS_DIR = os.path.join(OUTPUT_DIR, "reports") TOP_K_RETRIEVAL = 10 MAX_ARTICLES_TO_PROCESS = 5 # Keep this low for a web demo to avoid timeouts WEB_HEADLESS = True TRUSTED_DOMAINS = { "reuters.com", "bbc.co.uk", "nytimes.com", "theguardian.com", "washingtonpost.com", "bloomberg.com", "wsj.com", "timesofindia.indiatimes.com", "thehindu.com", "hindustantimes.com", "indianexpress.com", "ndtv.com", } os.makedirs(SCREENSHOT_DIR, exist_ok=True) os.makedirs(REPORTS_DIR, exist_ok=True) # ============================================================================== # CORE LOGIC CLASSES (Adapted for Gradio) # ============================================================================== class NewsRetriever: """Handles retrieving articles. Models are loaded once on initialization.""" _instance = None def __new__(cls, *args, **kwargs): if cls._instance is None: cls._instance = super(NewsRetriever, cls).__new__(cls) # Initialize models and data files only once print("🔹 Initializing NewsRetriever singleton...") cls._instance.index = faiss.read_index(FAISS_INDEX_FILE) with open(METADATA_FILE, "r", encoding="utf-8") as f: cls._instance.metadata = json.load(f) cls._instance.model = SentenceTransformer(EMBEDDING_MODEL) print("✅ FAISS index, metadata, and embedding model loaded.") return cls._instance def retrieve_and_filter(self, query, mongo_uri, k=TOP_K_RETRIEVAL): client = MongoClient(mongo_uri) db_collection = client[DB_NAME][COLLECTION_NAME] qvec = self.model.encode([query], convert_to_numpy=True).astype('float32') faiss.normalize_L2(qvec) distances, indices = self.index.search(qvec, k) results = [{"_id": self.metadata[i]["_id"]} for i in indices[0] if i < len(self.metadata)] doc_ids = [ObjectId(res["_id"]) for res in results] mongo_docs = list(db_collection.find({"_id": {"$in": doc_ids}})) full_docs = [] for doc in mongo_docs: link = doc.get("link", "") host = urlparse(link).netloc.lower() if any(td in host for td in TRUSTED_DOMAINS): full_docs.append({ "_id": str(doc["_id"]), "headline": doc.get("headline_translated") or doc.get("headline_original") or "", "description": doc.get("description_translated") or doc.get("description_original") or "", "link": link, }) client.close() return full_docs class ArticleProcessor: """Handles web scraping and summarization.""" async def process_articles(self, articles: list, openai_key: str, progress: gr.Progress): out_rows = [] client = OpenAI(api_key=openai_key) async with async_playwright() as p: # On Hugging Face, Playwright needs to use the installed Chromium browser = await p.chromium.launch(headless=WEB_HEADLESS) for i, rec in enumerate(articles): progress(i / len(articles), desc=f"Processing article {i+1}/{len(articles)}: {rec['headline'][:30]}...") url = rec.get("link","") if not url: continue context = await browser.new_context() page = await context.new_page() try: await page.goto(url, timeout=45000) await asyncio.sleep(2) # Wait for page to settle fname = f"{rec['_id']}.png" out_path = os.path.join(SCREENSHOT_DIR, fname) await page.screenshot(path=out_path) article_text = await page.evaluate("document.body.innerText") # Summarize with OpenAI prompt = f"Summarize the following article in a neutral, factual paragraph:\n\nTitle: {rec['headline']}\n\n{article_text[:4000]}" response = client.chat.completions.create(model=OPENAI_MODEL, messages=[{"role": "user", "content": prompt}], temperature=0.0) narrative = response.choices[0].message.content.strip() out_rows.append({"id": rec["_id"], "title": rec["headline"], "narrative": narrative, "screenshot_path": out_path, "url": url}) except Exception as e: print(f"Failed to process {url}: {e}") out_rows.append({"id": rec["_id"], "title": rec["headline"], "narrative": "Could not process this article.", "screenshot_path": "", "url": url}) finally: await page.close() await context.close() await browser.close() return out_rows class PDFReportGenerator: """Generates the final PDF report.""" def _wrap_lines(self, c, text, fontname, fontsize, max_width): text = str(text or "") lines = [] for paragraph in text.split('\n'): words, line = paragraph.split(' '), '' for word in words: if c.stringWidth(word, fontname, fontsize) > max_width: if line: lines.append(line) temp_word = '' for char in word: if c.stringWidth(temp_word + char, fontname, fontsize) < max_width: temp_word += char else: lines.append(temp_word); temp_word = char line = temp_word elif c.stringWidth((line + ' ' + word).strip(), fontname, fontsize) <= max_width: line = (line + ' ' + word).strip() else: lines.append(line); line = word if line: lines.append(line) return lines def generate(self, df, query, progress: gr.Progress): final_pdf_path = tempfile.NamedTemporaryFile(delete=False, suffix=".pdf").name c = canvas.Canvas(final_pdf_path, pagesize=A4) PAGE_W, PAGE_H = A4; LEFT_PAD, RIGHT_PAD, TOP_PAD, BOTTOM_PAD = 50, 50, 50, 50 PRINTABLE_W = PAGE_W - LEFT_PAD - RIGHT_PAD # Fonts HEADER_FONT, HEADER_SIZE = "Helvetica-Bold", 16 TITLE_FONT, TITLE_SIZE, TITLE_LEADING = "Helvetica-Bold", 12, 16 NARRATIVE_FONT, NARRATIVE_SIZE, NARRATIVE_LEADING = "Helvetica", 10, 14 LINK_FONT, LINK_SIZE, LINK_COLOR = "Helvetica-Oblique", 9, colors.blue # Header c.setFont(HEADER_FONT, HEADER_SIZE) c.drawCentredString(PAGE_W / 2, PAGE_H - TOP_PAD, f"News Report: {query}") current_y = PAGE_H - TOP_PAD - 30 for i, row in df.iterrows(): progress(i / len(df), desc=f"Adding article {i+1}/{len(df)} to PDF...") title_lines = self._wrap_lines(c, row['title'], TITLE_FONT, TITLE_SIZE, PRINTABLE_W) narrative_lines = self._wrap_lines(c, row['narrative'], NARRATIVE_FONT, NARRATIVE_SIZE, PRINTABLE_W) link_lines = self._wrap_lines(c, row['url'], LINK_FONT, LINK_SIZE, PRINTABLE_W) # Estimate block height and check for page break img_h = 200 if os.path.exists(row['screenshot_path']) else 0 block_h = (len(title_lines) * TITLE_LEADING + len(narrative_lines) * NARRATIVE_LEADING + len(link_lines) * 12 + img_h + 40) if current_y - block_h < BOTTOM_PAD: c.showPage(); current_y = PAGE_H - TOP_PAD # Draw content c.setFont(TITLE_FONT, TITLE_SIZE); c.setFillColor(colors.black) for line in title_lines: c.drawString(LEFT_PAD, current_y, line); current_y -= TITLE_LEADING current_y -= 5 c.setFont(NARRATIVE_FONT, NARRATIVE_SIZE) for line in narrative_lines: c.drawString(LEFT_PAD, current_y, line); current_y -= NARRATIVE_LEADING current_y -= 10 if os.path.exists(row['screenshot_path']): try: c.drawImage(row['screenshot_path'], LEFT_PAD, current_y - 180, width=PRINTABLE_W, height=180, preserveAspectRatio=True) except Exception: pass current_y -= 190 c.setFont(LINK_FONT, LINK_SIZE); c.setFillColor(LINK_COLOR) for line in link_lines: c.drawString(LEFT_PAD, current_y, line); current_y -= 12 current_y -= 25 c.save() return final_pdf_path # ============================================================================== # GRADIO INTERFACE # ============================================================================== async def run_pipeline(query, mongo_uri, openai_key, progress=gr.Progress(track_tqdm=True)): if not all([query, mongo_uri, openai_key]): raise gr.Error("Please provide a query and both API keys.") try: # Step 1: Retrieve Articles progress(0, desc="Initializing and retrieving articles...") retriever = NewsRetriever() validated_articles = retriever.retrieve_and_filter(query, mongo_uri) if not validated_articles: raise gr.Error("No trusted articles found for the query.") # Step 2: Process Articles articles_to_process = validated_articles[:MAX_ARTICLES_TO_PROCESS] processor = ArticleProcessor() processed_results = await processor.process_articles(articles_to_process, openai_key, progress) if not processed_results: raise gr.Error("Failed to process articles.") # Step 3: Generate PDF processed_df = pd.DataFrame(processed_results) reporter = PDFReportGenerator() pdf_path = reporter.generate(processed_df, query, progress) return pdf_path except Exception as e: # Log the full error for debugging on the Space print(f"An error occurred: {e}") # Raise a user-friendly error in the Gradio UI raise gr.Error(f"An error occurred during processing. Please check the logs in the Space. Details: {str(e)}") # --- UI Layout --- with gr.Blocks(theme=gr.themes.Soft()) as demo: gr.Markdown("# 📰 AI-Powered News Report Generator") gr.Markdown("Enter a topic to generate a PDF report summarizing the latest news from trusted sources.") with gr.Row(): with gr.Column(scale=2): query_input = gr.Textbox(label="Enter News Topic", placeholder="e.g., 'Latest advancements in AI'") mongo_uri_input = gr.Textbox(label="MongoDB URI", type="password", placeholder="mongodb+srv://srinivasa_varahe:SiQZzpCDuENhbnPt@newsdatabase.5u5rsy.mongodb.net") openai_key_input = gr.Textbox(label="OpenAI API Key", type="password", placeholder="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") submit_button = gr.Button("Generate Report", variant="primary") with gr.Column(scale=3): gr.Markdown("### Your Report") output_file = gr.File(label="Download PDF Report") submit_button.click( fn=run_pipeline, inputs=[query_input, mongo_uri_input, openai_key_input], outputs=[output_file] ) gr.Examples( [["Impact of climate change on agriculture in India"], ["Global semiconductor industry trends"], ["Future of renewable energy in Europe"]], inputs=[query_input] ) if __name__ == "__main__": # To run locally, ensure you have your FAISS/metadata files in the same directory. # Also, ensure you have run 'playwright install chromium'. demo.launch()