File size: 13,187 Bytes
756d323
 
 
 
 
 
 
 
 
d6b8a8e
 
756d323
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e35eba6
 
 
 
 
 
 
 
bf5ca87
 
e35eba6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d6b8a8e
 
756d323
 
d6b8a8e
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
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()