sssravi commited on
Commit
e35eba6
·
1 Parent(s): 955bc6e

Update space

Browse files
Files changed (1) hide show
  1. app.py +290 -65
app.py CHANGED
@@ -1,70 +1,295 @@
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
2
- from huggingface_hub import InferenceClient
3
-
4
-
5
- def respond(
6
- message,
7
- history: list[dict[str, str]],
8
- system_message,
9
- max_tokens,
10
- temperature,
11
- top_p,
12
- hf_token: gr.OAuthToken,
13
- ):
14
- """
15
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
16
- """
17
- client = InferenceClient(token=hf_token.token, model="openai/gpt-oss-20b")
18
-
19
- messages = [{"role": "system", "content": system_message}]
20
-
21
- messages.extend(history)
22
-
23
- messages.append({"role": "user", "content": message})
24
-
25
- response = ""
26
-
27
- for message in client.chat_completion(
28
- messages,
29
- max_tokens=max_tokens,
30
- stream=True,
31
- temperature=temperature,
32
- top_p=top_p,
33
- ):
34
- choices = message.choices
35
- token = ""
36
- if len(choices) and choices[0].delta.content:
37
- token = choices[0].delta.content
38
-
39
- response += token
40
- yield response
41
-
42
-
43
- """
44
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
45
- """
46
- chatbot = gr.ChatInterface(
47
- respond,
48
- type="messages",
49
- additional_inputs=[
50
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
51
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
52
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
53
- gr.Slider(
54
- minimum=0.1,
55
- maximum=1.0,
56
- value=0.95,
57
- step=0.05,
58
- label="Top-p (nucleus sampling)",
59
- ),
60
- ],
61
- )
62
-
63
- with gr.Blocks() as demo:
64
- with gr.Sidebar():
65
- gr.LoginButton()
66
- chatbot.render()
67
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68
 
69
  if __name__ == "__main__":
 
 
70
  demo.launch()
 
1
+ import os
2
+ import sys
3
+ import json
4
+ import time
5
+ import asyncio
6
+ import random
7
+ import tempfile
8
+ from urllib.parse import urlparse
9
+ from tqdm import tqdm
10
  import gradio as gr
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
 
12
+ # Import core libraries
13
+ import pandas as pd
14
+ import numpy as np
15
+ import faiss
16
+ from bson import ObjectId
17
+ from pymongo import MongoClient
18
+ from sentence_transformers import SentenceTransformer
19
+ from openai import OpenAI
20
+ from playwright.async_api import async_playwright
21
+ from PIL import Image, ImageChops, ImageOps, ExifTags
22
+ from reportlab.lib.pagesizes import A4
23
+ from reportlab.pdfgen import canvas
24
+ from reportlab.lib import colors
25
+ import nest_asyncio
26
+
27
+ # Apply nest_asyncio to allow running asyncio in environments like Jupyter/Colab
28
+ nest_asyncio.apply()
29
+
30
+ # ==============================================================================
31
+ # CONFIGURATION
32
+ # ==============================================================================
33
+ # NOTE: File paths are relative to the Hugging Face Space repository root.
34
+ # You MUST upload your FAISS index and metadata file to your Space.
35
+ FAISS_INDEX_FILE = "news_index.faiss"
36
+ METADATA_FILE = "news_metadata.json"
37
+
38
+ # --- Other Settings ---
39
+ DB_NAME = "news_db"
40
+ COLLECTION_NAME = "news_aggregator"
41
+ EMBEDDING_MODEL = "google/embeddinggemma-300m"
42
+ OPENAI_MODEL = "gpt-4o-mini"
43
+ OUTPUT_DIR = "outputs"
44
+ SCREENSHOT_DIR = os.path.join(OUTPUT_DIR, "screenshots")
45
+ REPORTS_DIR = os.path.join(OUTPUT_DIR, "reports")
46
+ TOP_K_RETRIEVAL = 10
47
+ MAX_ARTICLES_TO_PROCESS = 5 # Keep this low for a web demo to avoid timeouts
48
+ WEB_HEADLESS = True
49
+
50
+ TRUSTED_DOMAINS = {
51
+ "reuters.com", "bbc.co.uk", "nytimes.com", "theguardian.com",
52
+ "washingtonpost.com", "bloomberg.com", "wsj.com", "timesofindia.indiatimes.com",
53
+ "thehindu.com", "hindustantimes.com", "indianexpress.com", "ndtv.com",
54
+ }
55
+
56
+ os.makedirs(SCREENSHOT_DIR, exist_ok=True)
57
+ os.makedirs(REPORTS_DIR, exist_ok=True)
58
+
59
+ # ==============================================================================
60
+ # CORE LOGIC CLASSES (Adapted for Gradio)
61
+ # ==============================================================================
62
+
63
+ class NewsRetriever:
64
+ """Handles retrieving articles. Models are loaded once on initialization."""
65
+ _instance = None
66
+
67
+ def __new__(cls, *args, **kwargs):
68
+ if cls._instance is None:
69
+ cls._instance = super(NewsRetriever, cls).__new__(cls)
70
+ # Initialize models and data files only once
71
+ print("🔹 Initializing NewsRetriever singleton...")
72
+ cls._instance.index = faiss.read_index(FAISS_INDEX_FILE)
73
+ with open(METADATA_FILE, "r", encoding="utf-8") as f:
74
+ cls._instance.metadata = json.load(f)
75
+ cls._instance.model = SentenceTransformer(EMBEDDING_MODEL)
76
+ print("✅ FAISS index, metadata, and embedding model loaded.")
77
+ return cls._instance
78
+
79
+ def retrieve_and_filter(self, query, mongo_uri, k=TOP_K_RETRIEVAL):
80
+ client = MongoClient(mongo_uri)
81
+ db_collection = client[DB_NAME][COLLECTION_NAME]
82
+
83
+ qvec = self.model.encode([query], convert_to_numpy=True).astype('float32')
84
+ faiss.normalize_L2(qvec)
85
+
86
+ distances, indices = self.index.search(qvec, k)
87
+ results = [{"_id": self.metadata[i]["_id"]} for i in indices[0] if i < len(self.metadata)]
88
+
89
+ doc_ids = [ObjectId(res["_id"]) for res in results]
90
+ mongo_docs = list(db_collection.find({"_id": {"$in": doc_ids}}))
91
+
92
+ full_docs = []
93
+ for doc in mongo_docs:
94
+ link = doc.get("link", "")
95
+ host = urlparse(link).netloc.lower()
96
+ if any(td in host for td in TRUSTED_DOMAINS):
97
+ full_docs.append({
98
+ "_id": str(doc["_id"]),
99
+ "headline": doc.get("headline_translated") or doc.get("headline_original") or "",
100
+ "description": doc.get("description_translated") or doc.get("description_original") or "",
101
+ "link": link,
102
+ })
103
+ client.close()
104
+ return full_docs
105
+
106
+ class ArticleProcessor:
107
+ """Handles web scraping and summarization."""
108
+ async def process_articles(self, articles: list, openai_key: str, progress: gr.Progress):
109
+ out_rows = []
110
+ client = OpenAI(api_key=openai_key)
111
+
112
+ async with async_playwright() as p:
113
+ # On Hugging Face, Playwright needs to use the installed Chromium
114
+ browser = await p.chromium.launch(headless=WEB_HEADLESS)
115
+ for i, rec in enumerate(articles):
116
+ progress(i / len(articles), desc=f"Processing article {i+1}/{len(articles)}: {rec['headline'][:30]}...")
117
+
118
+ url = rec.get("link","")
119
+ if not url: continue
120
+
121
+ context = await browser.new_context()
122
+ page = await context.new_page()
123
+
124
+ try:
125
+ await page.goto(url, timeout=45000)
126
+ await asyncio.sleep(2) # Wait for page to settle
127
+
128
+ fname = f"{rec['_id']}.png"
129
+ out_path = os.path.join(SCREENSHOT_DIR, fname)
130
+ await page.screenshot(path=out_path)
131
+
132
+ article_text = await page.evaluate("document.body.innerText")
133
+
134
+ # Summarize with OpenAI
135
+ prompt = f"Summarize the following article in a neutral, factual paragraph:\n\nTitle: {rec['headline']}\n\n{article_text[:4000]}"
136
+ response = client.chat.completions.create(model=OPENAI_MODEL, messages=[{"role": "user", "content": prompt}], temperature=0.0)
137
+ narrative = response.choices[0].message.content.strip()
138
+
139
+ out_rows.append({"id": rec["_id"], "title": rec["headline"], "narrative": narrative, "screenshot_path": out_path, "url": url})
140
+
141
+ except Exception as e:
142
+ print(f"Failed to process {url}: {e}")
143
+ out_rows.append({"id": rec["_id"], "title": rec["headline"], "narrative": "Could not process this article.", "screenshot_path": "", "url": url})
144
+
145
+ finally:
146
+ await page.close()
147
+ await context.close()
148
+
149
+ await browser.close()
150
+ return out_rows
151
+
152
+ class PDFReportGenerator:
153
+ """Generates the final PDF report."""
154
+ def _wrap_lines(self, c, text, fontname, fontsize, max_width):
155
+ text = str(text or "")
156
+ lines = []
157
+ for paragraph in text.split('\n'):
158
+ words, line = paragraph.split(' '), ''
159
+ for word in words:
160
+ if c.stringWidth(word, fontname, fontsize) > max_width:
161
+ if line: lines.append(line)
162
+ temp_word = ''
163
+ for char in word:
164
+ if c.stringWidth(temp_word + char, fontname, fontsize) < max_width: temp_word += char
165
+ else: lines.append(temp_word); temp_word = char
166
+ line = temp_word
167
+ elif c.stringWidth((line + ' ' + word).strip(), fontname, fontsize) <= max_width:
168
+ line = (line + ' ' + word).strip()
169
+ else: lines.append(line); line = word
170
+ if line: lines.append(line)
171
+ return lines
172
+
173
+ def generate(self, df, query, progress: gr.Progress):
174
+ final_pdf_path = tempfile.NamedTemporaryFile(delete=False, suffix=".pdf").name
175
+ c = canvas.Canvas(final_pdf_path, pagesize=A4)
176
+ PAGE_W, PAGE_H = A4; LEFT_PAD, RIGHT_PAD, TOP_PAD, BOTTOM_PAD = 50, 50, 50, 50
177
+ PRINTABLE_W = PAGE_W - LEFT_PAD - RIGHT_PAD
178
+
179
+ # Fonts
180
+ HEADER_FONT, HEADER_SIZE = "Helvetica-Bold", 16
181
+ TITLE_FONT, TITLE_SIZE, TITLE_LEADING = "Helvetica-Bold", 12, 16
182
+ NARRATIVE_FONT, NARRATIVE_SIZE, NARRATIVE_LEADING = "Helvetica", 10, 14
183
+ LINK_FONT, LINK_SIZE, LINK_COLOR = "Helvetica-Oblique", 9, colors.blue
184
+
185
+ # Header
186
+ c.setFont(HEADER_FONT, HEADER_SIZE)
187
+ c.drawCentredString(PAGE_W / 2, PAGE_H - TOP_PAD, f"News Report: {query}")
188
+ current_y = PAGE_H - TOP_PAD - 30
189
+
190
+ for i, row in df.iterrows():
191
+ progress(i / len(df), desc=f"Adding article {i+1}/{len(df)} to PDF...")
192
+
193
+ title_lines = self._wrap_lines(c, row['title'], TITLE_FONT, TITLE_SIZE, PRINTABLE_W)
194
+ narrative_lines = self._wrap_lines(c, row['narrative'], NARRATIVE_FONT, NARRATIVE_SIZE, PRINTABLE_W)
195
+ link_lines = self._wrap_lines(c, row['url'], LINK_FONT, LINK_SIZE, PRINTABLE_W)
196
+
197
+ # Estimate block height and check for page break
198
+ img_h = 200 if os.path.exists(row['screenshot_path']) else 0
199
+ block_h = (len(title_lines) * TITLE_LEADING + len(narrative_lines) * NARRATIVE_LEADING +
200
+ len(link_lines) * 12 + img_h + 40)
201
+
202
+ if current_y - block_h < BOTTOM_PAD:
203
+ c.showPage(); current_y = PAGE_H - TOP_PAD
204
+
205
+ # Draw content
206
+ c.setFont(TITLE_FONT, TITLE_SIZE); c.setFillColor(colors.black)
207
+ for line in title_lines: c.drawString(LEFT_PAD, current_y, line); current_y -= TITLE_LEADING
208
+ current_y -= 5
209
+
210
+ c.setFont(NARRATIVE_FONT, NARRATIVE_SIZE)
211
+ for line in narrative_lines: c.drawString(LEFT_PAD, current_y, line); current_y -= NARRATIVE_LEADING
212
+ current_y -= 10
213
+
214
+ if os.path.exists(row['screenshot_path']):
215
+ try: c.drawImage(row['screenshot_path'], LEFT_PAD, current_y - 180, width=PRINTABLE_W, height=180, preserveAspectRatio=True)
216
+ except Exception: pass
217
+ current_y -= 190
218
+
219
+ c.setFont(LINK_FONT, LINK_SIZE); c.setFillColor(LINK_COLOR)
220
+ for line in link_lines: c.drawString(LEFT_PAD, current_y, line); current_y -= 12
221
+ current_y -= 25
222
+
223
+ c.save()
224
+ return final_pdf_path
225
+
226
+ # ==============================================================================
227
+ # GRADIO INTERFACE
228
+ # ==============================================================================
229
+
230
+ async def run_pipeline(query, mongo_uri, openai_key, progress=gr.Progress(track_tqdm=True)):
231
+ if not all([query, mongo_uri, openai_key]):
232
+ raise gr.Error("Please provide a query and both API keys.")
233
+
234
+ try:
235
+ # Step 1: Retrieve Articles
236
+ progress(0, desc="Initializing and retrieving articles...")
237
+ retriever = NewsRetriever()
238
+ validated_articles = retriever.retrieve_and_filter(query, mongo_uri)
239
+ if not validated_articles:
240
+ raise gr.Error("No trusted articles found for the query.")
241
+
242
+ # Step 2: Process Articles
243
+ articles_to_process = validated_articles[:MAX_ARTICLES_TO_PROCESS]
244
+ processor = ArticleProcessor()
245
+ processed_results = await processor.process_articles(articles_to_process, openai_key, progress)
246
+ if not processed_results:
247
+ raise gr.Error("Failed to process articles.")
248
+
249
+ # Step 3: Generate PDF
250
+ processed_df = pd.DataFrame(processed_results)
251
+ reporter = PDFReportGenerator()
252
+ pdf_path = reporter.generate(processed_df, query, progress)
253
+
254
+ return pdf_path
255
+
256
+ except Exception as e:
257
+ # Log the full error for debugging on the Space
258
+ print(f"An error occurred: {e}")
259
+ # Raise a user-friendly error in the Gradio UI
260
+ raise gr.Error(f"An error occurred during processing. Please check the logs in the Space. Details: {str(e)}")
261
+
262
+
263
+ # --- UI Layout ---
264
+ with gr.Blocks(theme=gr.themes.Soft()) as demo:
265
+ gr.Markdown("# 📰 AI-Powered News Report Generator")
266
+ gr.Markdown("Enter a topic to generate a PDF report summarizing the latest news from trusted sources.")
267
+
268
+ with gr.Row():
269
+ with gr.Column(scale=2):
270
+ query_input = gr.Textbox(label="Enter News Topic", placeholder="e.g., 'Latest advancements in AI'")
271
+ mongo_uri_input = gr.Textbox(label="MongoDB URI", type="password", placeholder="Enter your MongoDB connection string")
272
+ openai_key_input = gr.Textbox(label="OpenAI API Key", type="password", placeholder="Enter your OpenAI API key")
273
+ submit_button = gr.Button("Generate Report", variant="primary")
274
+
275
+ with gr.Column(scale=3):
276
+ gr.Markdown("### Your Report")
277
+ output_file = gr.File(label="Download PDF Report")
278
+
279
+ submit_button.click(
280
+ fn=run_pipeline,
281
+ inputs=[query_input, mongo_uri_input, openai_key_input],
282
+ outputs=[output_file]
283
+ )
284
+
285
+ gr.Examples(
286
+ [["Impact of climate change on agriculture in India"],
287
+ ["Global semiconductor industry trends"],
288
+ ["Future of renewable energy in Europe"]],
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()