MathWizard1729 commited on
Commit
27ad88b
Β·
verified Β·
1 Parent(s): 76b0776

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +267 -61
app.py CHANGED
@@ -1,64 +1,270 @@
1
- import gradio as gr
2
- from huggingface_hub import InferenceClient
3
-
4
- """
5
- 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
6
- """
7
- client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
8
-
9
-
10
- def respond(
11
- message,
12
- history: list[tuple[str, str]],
13
- system_message,
14
- max_tokens,
15
- temperature,
16
- top_p,
17
- ):
18
- messages = [{"role": "system", "content": system_message}]
19
-
20
- for val in history:
21
- if val[0]:
22
- messages.append({"role": "user", "content": val[0]})
23
- if val[1]:
24
- messages.append({"role": "assistant", "content": val[1]})
25
-
26
- messages.append({"role": "user", "content": message})
27
-
28
- response = ""
29
-
30
- for message in client.chat_completion(
31
- messages,
32
- max_tokens=max_tokens,
33
- stream=True,
34
- temperature=temperature,
35
- top_p=top_p,
36
- ):
37
- token = message.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
- demo = gr.ChatInterface(
47
- respond,
48
- additional_inputs=[
49
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
50
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
51
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
52
- gr.Slider(
53
- minimum=0.1,
54
- maximum=1.0,
55
- value=0.95,
56
- step=0.05,
57
- label="Top-p (nucleus sampling)",
58
- ),
59
- ],
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60
  )
 
61
 
 
 
62
 
63
- if __name__ == "__main__":
64
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import requests
3
+ import boto3
4
+ import os
5
+ from dotenv import load_dotenv
6
+ import json
7
+
8
+ # ───────────────────────────────────────────────────────────────────────────────
9
+ # Load environment variables (make sure your .env has NEWS_API_KEY, SERPER_API_KEY, AWS_REGION, etc.)
10
+ load_dotenv()
11
+ NEWS_API_KEY = os.getenv("NEWS_API_KEY")
12
+ SERPER_API_KEY = os.getenv("SERPER_API_KEY")
13
+ AWS_REGION = os.getenv("AWS_REGION")
14
+
15
+ # Setup AWS Bedrock client
16
+ bedrock = boto3.client("bedrock-runtime", region_name=AWS_REGION)
17
+
18
+ # ───────────────────────────────────────────────────────────────────────────────
19
+ # Page configuration
20
+ st.set_page_config(
21
+ page_title="πŸ“° News Summarizer Agent",
22
+ page_icon="πŸ“°",
23
+ layout="wide", # wide layout for more room
24
+ initial_sidebar_state="expanded"
25
+ )
26
+
27
+ # ───────────────────────────────────────────────────────────────────────────────
28
+ # Custom CSS for vibrant UI
29
+ st.markdown(
30
+ """
31
+ <style>
32
+ /* Change background color of the main area */
33
+ .stApp {
34
+ background-color: #F7F9FC;
35
+ }
36
+ /* Style for the title */
37
+ .app-title {
38
+ font-size: 2.5rem;
39
+ color: #1E3A8A;
40
+ font-weight: 700;
41
+ margin-bottom: 0.2rem;
42
+ }
43
+ /* Style for the subtitle/description */
44
+ .app-subtitle {
45
+ font-size: 1.1rem;
46
+ color: #374151;
47
+ margin-bottom: 1.5rem;
48
+ }
49
+ /* Card container styling */
50
+ .news-card {
51
+ background-color: #FFFFFF;
52
+ border-radius: 10px;
53
+ padding: 1rem;
54
+ margin-bottom: 1.5rem;
55
+ box-shadow: 0px 4px 12px rgba(0, 0, 0, 0.05);
56
+ }
57
+ /* Header style inside each card */
58
+ .news-header {
59
+ background-color: #E0F2FE;
60
+ border-radius: 8px;
61
+ padding: 0.5rem 1rem;
62
+ margin-bottom: 0.8rem;
63
+ }
64
+ .news-header h4 {
65
+ margin: 0;
66
+ color: #0369A1;
67
+ }
68
+ /* Article title style */
69
+ .article-title {
70
+ font-size: 1.2rem;
71
+ font-weight: 600;
72
+ color: #1F2937;
73
+ margin-bottom: 0.5rem;
74
+ }
75
+ /* Summary text style */
76
+ .article-summary {
77
+ font-size: 1rem;
78
+ color: #4B5563;
79
+ margin-bottom: 0.7rem;
80
+ }
81
+ /* β€œRead more” link style */
82
+ .read-link {
83
+ font-size: 0.95rem;
84
+ color: #1D4ED8;
85
+ text-decoration: none;
86
+ font-weight: 500;
87
+ }
88
+ .read-link:hover {
89
+ text-decoration: underline;
90
+ }
91
+ /* Spinner/loading text */
92
+ .stSpinner > div {
93
+ background-color: #FFFFFF !important;
94
+ }
95
+ </style>
96
+ """,
97
+ unsafe_allow_html=True
98
+ )
99
+
100
+ # ───────────────────────────────────────────────────────────────────────────────
101
+ # Sidebar (for API info, instructions, etc.)
102
+ with st.sidebar:
103
+ st.markdown("## ℹ️ About This App")
104
+ st.markdown(
105
+ """
106
+ - Enter any **topic**, **company name**, or **keywords** above and click **Get News**.
107
+ - This app will fetch up to 3 articles from **NewsAPI** and 2 from **Serper**, then summarize them using AWS Bedrock (Claude).
108
+ - You need valid `NEWS_API_KEY`, `SERPER_API_KEY`, and AWS credentials / region configured.
109
+ """
110
+ )
111
+ st.markdown("---")
112
+ st.markdown("## πŸ”‘ API Keys")
113
+ st.markdown(
114
+ """
115
+ - **NEWS_API_KEY**: Used to fetch articles from NewsAPI.org
116
+ - **SERPER_API_KEY**: Used to fetch Google‐News‐style results via Serper.dev
117
+ - **AWS Credentials**: For invoking Claude on Bedrock
118
+ """
119
+ )
120
+ st.markdown("---")
121
+ st.markdown("## πŸ“š Resources")
122
+ st.markdown(
123
+ """
124
+ - [NewsAPI Documentation](https://newsapi.org/docs)
125
+ - [Serper.dev Docs](https://serper.dev/docs)
126
+ - [AWS Bedrock Claude Guide](https://docs.aws.amazon.com/bedrock/latest/developerguide/claude.html)
127
+ """
128
+ )
129
+
130
+ # ───────────────────────────────────────────────────────────────────────────────
131
+ # Main Title / Header
132
+ st.markdown('<div class="app-title">πŸ“° News Summarizer Agent</div>', unsafe_allow_html=True)
133
+ st.markdown(
134
+ '<div class="app-subtitle">Get the top 5 latest news with concise summaries on any topic or company you choose.</div>',
135
+ unsafe_allow_html=True
136
+ )
137
+
138
+ # Input box and button
139
+ query = st.text_input(
140
+ label="",
141
+ placeholder="e.g. Artificial Intelligence, Tesla, Global Markets...",
142
+ key="search_query"
143
  )
144
+ btn = st.button("Get News", use_container_width=True)
145
 
146
+ # ───────────────────────────────────────────────────────────────────────────────
147
+ # Functions to fetch articles and summarize
148
 
149
+ def get_newsapi_articles(q: str):
150
+ """
151
+ Fetch up to 3 articles from NewsAPI based on query,
152
+ sorted by published date (newest first).
153
+ """
154
+ url = "https://newsapi.org/v2/everything"
155
+ params = {
156
+ "q": q,
157
+ "sortBy": "publishedAt",
158
+ "pageSize": 3,
159
+ "apiKey": NEWS_API_KEY
160
+ }
161
+ try:
162
+ response = requests.get(url, params=params, timeout=10)
163
+ response.raise_for_status()
164
+ data = response.json()
165
+ return data.get("articles", [])
166
+ except Exception as e:
167
+ st.error(f"Error fetching from NewsAPI: {e}")
168
+ return []
169
+
170
+ def get_serper_articles(q: str):
171
+ """
172
+ Fetch up to 2 news snippets from Serper (Google News API wrapper).
173
+ """
174
+ url = "https://google.serper.dev/news"
175
+ headers = {"X-API-KEY": SERPER_API_KEY}
176
+ data = {"q": q}
177
+ try:
178
+ response = requests.post(url, headers=headers, json=data, timeout=10)
179
+ response.raise_for_status()
180
+ data = response.json()
181
+ return data.get("news", [])[:2]
182
+ except Exception as e:
183
+ st.error(f"Error fetching from Serper: {e}")
184
+ return []
185
+
186
+ def summarize_with_bedrock(title: str, content: str) -> str:
187
+ """
188
+ Send the article title + content to AWS Bedrock (Claude) and get a 3–5 line summary.
189
+ """
190
+ prompt = (
191
+ f"Summarize the following news article in 3–5 lines:\n\n"
192
+ f"Title: {title}\n\nContent: {content}\n\nSummary:"
193
+ )
194
+ body = {
195
+ "anthropic_version": "bedrock-2023-05-31",
196
+ "messages": [{"role": "user", "content": prompt}],
197
+ "max_tokens": 300,
198
+ "temperature": 0.7
199
+ }
200
+ try:
201
+ response = bedrock.invoke_model(
202
+ modelId="anthropic.claude-3-sonnet-20240229-v1:0",
203
+ body=json.dumps(body),
204
+ contentType="application/json",
205
+ )
206
+ result = json.loads(response["body"].read())
207
+ # The response format may vary; adjust indexing if necessary
208
+ return result["content"][0]["text"].strip()
209
+ except Exception as e:
210
+ return f"⚠️ Failed to summarize: {e}"
211
+
212
+ # ───────────────────────────────────────────────────────────────────────────────
213
+ # When button is clicked
214
+ if btn and query:
215
+ st.info(f"πŸ” Searching for news on <b>{query}</b>...", unsafe_allow_html=True)
216
+
217
+ # Fetch articles concurrently / sequentially
218
+ newsapi_articles = get_newsapi_articles(query)
219
+ serper_articles = get_serper_articles(query)
220
+
221
+ # Collect and normalize
222
+ all_articles = []
223
+ # From NewsAPI
224
+ for art in newsapi_articles:
225
+ title = art.get("title") or "No Title"
226
+ content = art.get("description") or art.get("content") or ""
227
+ url = art.get("url") or ""
228
+ if content:
229
+ all_articles.append({"title": title, "content": content, "url": url})
230
+ # From Serper
231
+ for art in serper_articles:
232
+ title = art.get("title") or "No Title"
233
+ content = art.get("snippet") or ""
234
+ url = art.get("link") or ""
235
+ if content:
236
+ all_articles.append({"title": title, "content": content, "url": url})
237
+
238
+ # If no articles found
239
+ if not all_articles:
240
+ st.warning("No articles found for that query. Try something else?")
241
+ else:
242
+ # Loop through each article and display as a β€œcard”
243
+ for i, article in enumerate(all_articles, start=1):
244
+ with st.spinner(f"πŸ–‹οΈ Summarizing Article {i}..."):
245
+ summary = summarize_with_bedrock(article["title"], article["content"])
246
+
247
+ # Build a β€œcard” using HTML inside st.markdown
248
+ card_html = f"""
249
+ <div class="news-card">
250
+ <div class="news-header">
251
+ <h4>πŸ—žοΈ News {i}</h4>
252
+ </div>
253
+ <div class="article-title">{article['title']}</div>
254
+ <div class="article-summary">{summary}</div>
255
+ <a class="read-link" href="{article['url']}" target="_blank">Read Full Article &raquo;</a>
256
+ </div>
257
+ """
258
+ st.markdown(card_html, unsafe_allow_html=True)
259
+
260
+ # ───────────────────────────────────────────────────────────────────────────────
261
+ # Footer (optional)
262
+ st.markdown(
263
+ """
264
+ <hr>
265
+ <div style="text-align:center; font-size:0.9rem; color:#6B7280; padding-top:1rem;">
266
+ Built with ❀️ using Streamlit β€’ Data sources: NewsAPI.org, Serper.dev β€’ Summarization via AWS Bedrock Claude
267
+ </div>
268
+ """,
269
+ unsafe_allow_html=True
270
+ )