charantejapolavarapu commited on
Commit
2e17ce9
·
verified ·
1 Parent(s): 4e94959

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +81 -21
src/streamlit_app.py CHANGED
@@ -13,9 +13,7 @@ import feedparser
13
  import requests
14
  from bs4 import BeautifulSoup
15
  from newspaper import Article # Make sure newspaper3k and lxml_html_clean are installed
16
- # Removed torch, transformers imports for now to simplify
17
  import time
18
- # Removed geocoder import for now to simplify
19
  import json
20
  import datetime
21
 
@@ -33,22 +31,22 @@ TELUGU_CATEGORIES = {
33
  "వైరల్": "Viral",
34
  }
35
 
36
- # --- RSS Feed URLs ---
37
  # IMPORTANT: These URLs might be outdated or not provide full content.
38
  # You might need to find current, active RSS feeds for Telugu news sources.
39
- # Many news sites change their RSS feeds frequently or don't offer comprehensive ones.
40
  RSS_FEEDS = {
41
- "Sakshi": "https://www.sakshi.com/tags/rss", # Check if this still provides full content
42
- "Eenadu": "https://www.eenadu.net/telugu-news/rss", # This URL from search might be old/unofficial.
43
- # Add more reliable Telugu news RSS feeds here if the above don't work well
44
- # Example: "MyNewSource": "http://mynewsource.com/rss_feed_link",
45
  }
46
 
47
  # --- OpenWeatherMap API Configuration (for Realtime Weather) ---
48
- # YOUR ACTUAL API KEY IS SET HERE:
49
  OPENWEATHERMAP_API_KEY = "52f888dddede635f9b1d8a08141b5c49"
50
  OPENWEATHERMAP_API_URL = "http://api.openweathermap.org/data/2.5/weather"
51
 
 
 
 
 
52
  # --- Dummy Translation Function (Translation is temporarily disabled) ---
53
  def translate_en_to_te(text):
54
  return text # Just return the original text
@@ -66,20 +64,17 @@ def get_news_from_rss(url):
66
  published = entry.published if hasattr(entry, 'published') else "N/A"
67
  image_url = None
68
 
69
- # Attempt to find image from media_content (common in some RSS feeds)
70
  if hasattr(entry, 'media_content') and entry.media_content:
71
  for media in entry.media_content:
72
  if 'url' in media and media.get('type', '').startswith('image'):
73
  image_url = media['url']
74
  break
75
- # Attempt to find image from description HTML (common in others)
76
  elif hasattr(entry, 'description'):
77
  soup = BeautifulSoup(entry.description, 'html.parser')
78
  img_tag = soup.find('img')
79
  if img_tag and 'src' in img_tag.attrs:
80
  image_url = img_tag['src']
81
 
82
- # Fallback to newspaper3k for better image/summary extraction from the article link
83
  if link and "http" in link and link != "#" and (not image_url or not summary):
84
  try:
85
  article_parser = Article(link)
@@ -91,7 +86,7 @@ def get_news_from_rss(url):
91
  summary = article_parser.text[:200] + "..." if len(article_parser.text) > 200 else article_parser.text
92
 
93
  except Exception as e:
94
- pass # Silently fail if newspaper3k can't extract
95
 
96
  if title.strip() and link.strip() != "#":
97
  articles.append({
@@ -100,13 +95,55 @@ def get_news_from_rss(url):
100
  "summary": summary,
101
  "published": published,
102
  "image_url": image_url,
103
- "translated_title": None # Placeholder, will just be original title
104
  })
105
  return articles
106
  except Exception as e:
107
  st.error(f"Error fetching news from {url}: {e}")
108
  return []
109
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
110
  # --- Voice Search (Placeholder - requires a separate library/API) ---
111
  def voice_search_widget():
112
  st.write("### 🎙️ వాయిస్ సెర్చ్ (Voice Search)")
@@ -125,7 +162,7 @@ def get_user_location():
125
  # --- Weather Integration ---
126
  @st.cache_data(ttl=600)
127
  def get_current_weather(city_name, api_key):
128
- if not api_key: # Check if API key is empty or None
129
  return None
130
 
131
  params = {
@@ -323,7 +360,6 @@ with main_tabs[0]:
323
  articles = get_news_from_rss(rss_url)
324
 
325
  for article in articles:
326
- # Since translation is disabled, translated_title is just the original title
327
  article['translated_title'] = article['title']
328
 
329
  all_articles.extend(articles)
@@ -346,7 +382,7 @@ with main_tabs[0]:
346
  if article['image_url']:
347
  st.image(article['image_url'], use_column_width="always", caption="")
348
 
349
- st.markdown(f"### {article['title']}") # Always display original title
350
 
351
  st.markdown(f"<p>{article['summary']}</p>", unsafe_allow_html=True)
352
  st.markdown(f"[పూర్తిగా చదవండి (Read More)]({article['link']})", unsafe_allow_html=True)
@@ -373,6 +409,7 @@ with main_tabs[1]:
373
  st.info(f"'{user_city}' కోసం వాతావరణ డేటా అందుబాటులో లేదు. (Weather data not available for '{user_city}').")
374
 
375
  st.subheader("స్థానిక వార్తలు (Local News)")
 
376
  st.info(f"'{user_city}' కు సంబంధించిన స్థానిక వార్తలు ఇక్కడ ప్రదర్శించబడతాయి. (Local news for '{user_city}' will be displayed here.)")
377
 
378
  st.subheader("అలర్ట్స్ (Alerts)")
@@ -399,9 +436,33 @@ with main_tabs[2]:
399
  else:
400
  st.info(f"'{search_city}' కోసం వాతావరణ డేటా అందుబాటులో లేదు. (Weather data not available for '{search_city}').")
401
 
402
- st.subheader("స్థానిక వార్తలు (Local News)")
403
- st.warning("ఈ ఫీచర్ కోసం స్థానిక వార్తా వనరులను అనుసంధానించడం అవసరం. (This feature requires integration with local news sources.)")
404
- st.info(f"'{search_city}' కు సంబంధించిన వార్తలు ఇక్కడ ప్రదర్శించబడతాయి. (News for '{search_city}' will be displayed here.)")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
405
 
406
 
407
  # --- Tab 4: Voice Search ---
@@ -483,7 +544,6 @@ st.sidebar.info("ఇక్కడ మీరు యాప్ సెట్టిం
483
 
484
  if st.sidebar.button("రీఫ్రెష్ వార్తలు", key="refresh_news_button"):
485
  st.cache_data.clear() # Clear all data caches (news, location, weather)
486
- # st.cache_resource.clear() # Commented out as translation model is removed
487
  st.rerun() # Rerun the app to load fresh data
488
  st.sidebar.success("వార్తలు రీఫ్రెష్ చేయబడ్డాయి!")
489
 
 
13
  import requests
14
  from bs4 import BeautifulSoup
15
  from newspaper import Article # Make sure newspaper3k and lxml_html_clean are installed
 
16
  import time
 
17
  import json
18
  import datetime
19
 
 
31
  "వైరల్": "Viral",
32
  }
33
 
34
+ # --- RSS Feed URLs (for general headlines) ---
35
  # IMPORTANT: These URLs might be outdated or not provide full content.
36
  # You might need to find current, active RSS feeds for Telugu news sources.
 
37
  RSS_FEEDS = {
38
+ "Sakshi": "https://www.sakshi.com/tags/rss",
39
+ "Eenadu": "https://www.eenadu.net/telugu-news/rss",
 
 
40
  }
41
 
42
  # --- OpenWeatherMap API Configuration (for Realtime Weather) ---
 
43
  OPENWEATHERMAP_API_KEY = "52f888dddede635f9b1d8a08141b5c49"
44
  OPENWEATHERMAP_API_URL = "http://api.openweathermap.org/data/2.5/weather"
45
 
46
+ # --- NewsAPI.org Configuration (for Local News Search) ---
47
+ NEWSAPI_API_KEY = "54035029265744dab172f28d58a93b56" # Your NewsAPI.org Key
48
+ NEWSAPI_EVERYTHING_URL = "https://newsapi.org/v2/everything"
49
+
50
  # --- Dummy Translation Function (Translation is temporarily disabled) ---
51
  def translate_en_to_te(text):
52
  return text # Just return the original text
 
64
  published = entry.published if hasattr(entry, 'published') else "N/A"
65
  image_url = None
66
 
 
67
  if hasattr(entry, 'media_content') and entry.media_content:
68
  for media in entry.media_content:
69
  if 'url' in media and media.get('type', '').startswith('image'):
70
  image_url = media['url']
71
  break
 
72
  elif hasattr(entry, 'description'):
73
  soup = BeautifulSoup(entry.description, 'html.parser')
74
  img_tag = soup.find('img')
75
  if img_tag and 'src' in img_tag.attrs:
76
  image_url = img_tag['src']
77
 
 
78
  if link and "http" in link and link != "#" and (not image_url or not summary):
79
  try:
80
  article_parser = Article(link)
 
86
  summary = article_parser.text[:200] + "..." if len(article_parser.text) > 200 else article_parser.text
87
 
88
  except Exception as e:
89
+ pass
90
 
91
  if title.strip() and link.strip() != "#":
92
  articles.append({
 
95
  "summary": summary,
96
  "published": published,
97
  "image_url": image_url,
98
+ "translated_title": None
99
  })
100
  return articles
101
  except Exception as e:
102
  st.error(f"Error fetching news from {url}: {e}")
103
  return []
104
 
105
+ # --- NewsAPI.org Fetching for Local News (Cached for performance) ---
106
+ @st.cache_data(ttl=600) # Cache for 10 minutes
107
+ def get_news_from_newsapi(query, api_key, language='en', page_size=10):
108
+ if not api_key:
109
+ return None
110
+
111
+ params = {
112
+ 'q': query + " news", # Add " news" to the query for better results
113
+ 'apiKey': api_key,
114
+ 'language': language, # Can try 'te' but English coverage is better
115
+ 'pageSize': page_size,
116
+ 'sortBy': 'relevancy'
117
+ }
118
+ try:
119
+ response = requests.get(NEWSAPI_EVERYTHING_URL, params=params)
120
+ response.raise_for_status() # Raise an HTTPError for bad responses (4xx or 5xx)
121
+ news_data = response.json()
122
+
123
+ articles = []
124
+ if news_data['status'] == 'ok' and news_data['articles']:
125
+ for article in news_data['articles']:
126
+ if article['title'] and article['url']: # Basic validation
127
+ articles.append({
128
+ "title": article.get('title', 'No Title'),
129
+ "link": article.get('url', '#'),
130
+ "summary": article.get('description', article.get('content', 'No description available.')),
131
+ "published": article.get('publishedAt', 'N/A'),
132
+ "image_url": article.get('urlToImage'),
133
+ "source": article['source']['name'] if article.get('source') else 'Unknown Source',
134
+ "translated_title": None # Placeholder
135
+ })
136
+ return articles
137
+ except requests.exceptions.RequestException as e:
138
+ st.error(f"Error fetching news from NewsAPI for '{query}': {e}. Check API key or network.")
139
+ return None
140
+ except json.JSONDecodeError:
141
+ st.error(f"Error decoding NewsAPI response for '{query}'.")
142
+ return None
143
+ except Exception as e:
144
+ st.error(f"An unexpected error occurred with NewsAPI for '{query}': {e}")
145
+ return None
146
+
147
  # --- Voice Search (Placeholder - requires a separate library/API) ---
148
  def voice_search_widget():
149
  st.write("### 🎙️ వాయిస్ సెర్చ్ (Voice Search)")
 
162
  # --- Weather Integration ---
163
  @st.cache_data(ttl=600)
164
  def get_current_weather(city_name, api_key):
165
+ if not api_key:
166
  return None
167
 
168
  params = {
 
360
  articles = get_news_from_rss(rss_url)
361
 
362
  for article in articles:
 
363
  article['translated_title'] = article['title']
364
 
365
  all_articles.extend(articles)
 
382
  if article['image_url']:
383
  st.image(article['image_url'], use_column_width="always", caption="")
384
 
385
+ st.markdown(f"### {article['title']}")
386
 
387
  st.markdown(f"<p>{article['summary']}</p>", unsafe_allow_html=True)
388
  st.markdown(f"[పూర్తిగా చదవండి (Read More)]({article['link']})", unsafe_allow_html=True)
 
409
  st.info(f"'{user_city}' కోసం వాతావరణ డేటా అందుబాటులో లేదు. (Weather data not available for '{user_city}').")
410
 
411
  st.subheader("స్థానిక వార్తలు (Local News)")
412
+ # Local news for "My Location" still uses the RSS feeds, or you'd need another API for this
413
  st.info(f"'{user_city}' కు సంబంధించిన స్థానిక వార్తలు ఇక్కడ ప్రదర్శించబడతాయి. (Local news for '{user_city}' will be displayed here.)")
414
 
415
  st.subheader("అలర్ట్స్ (Alerts)")
 
436
  else:
437
  st.info(f"'{search_city}' కోసం వాతావరణ డేటా అందుబాటులో లేదు. (Weather data not available for '{search_city}').")
438
 
439
+ st.subheader(f"స్థానిక వార్తలు: {search_city} (Local News: {search_city})")
440
+
441
+ # --- NEW: Fetch and display local news using NewsAPI.org ---
442
+ local_news_articles = get_news_from_newsapi(search_city, NEWSAPI_API_KEY, language='en') # Use 'en' for broader coverage
443
+
444
+ if local_news_articles:
445
+ num_cols = 3
446
+ rows = []
447
+ for i in range(0, len(local_news_articles), num_cols):
448
+ rows.append(local_news_articles[i:i + num_cols])
449
+
450
+ for row_articles in rows:
451
+ cols = st.columns(num_cols)
452
+ for i, article in enumerate(row_articles):
453
+ with cols[i]:
454
+ with st.container():
455
+ st.markdown(f'<div class="news-card">', unsafe_allow_html=True)
456
+ if article['image_url']:
457
+ st.image(article['image_url'], use_column_width="always", caption="")
458
+
459
+ st.markdown(f"### {article['title']}")
460
+ st.markdown(f"**Source:** {article.get('source', 'Unknown')} | **Published:** {article['published']}")
461
+ st.markdown(f"<p>{article['summary']}</p>", unsafe_allow_html=True)
462
+ st.markdown(f"[పూర్తిగా చదవండి (Read More)]({article['link']})", unsafe_allow_html=True)
463
+ st.markdown('</div>', unsafe_allow_html=True)
464
+ else:
465
+ st.info(f"'{search_city}' కోసం స్థానిక వార్తలు అందుబాటులో లేవు. దయచేసి మరొక నగరాన్ని ప్రయత్నించండి లేదా మీ NewsAPI.org కీని తనిఖి చేయండి. (No local news available for '{search_city}'. Please try another city or check your NewsAPI.org key.)")
466
 
467
 
468
  # --- Tab 4: Voice Search ---
 
544
 
545
  if st.sidebar.button("రీఫ్రెష్ వార్తలు", key="refresh_news_button"):
546
  st.cache_data.clear() # Clear all data caches (news, location, weather)
 
547
  st.rerun() # Rerun the app to load fresh data
548
  st.sidebar.success("వార్తలు రీఫ్రెష్ చేయబడ్డాయి!")
549