charantejapolavarapu commited on
Commit
d263152
·
verified ·
1 Parent(s): 029dac5

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +168 -110
src/streamlit_app.py CHANGED
@@ -1,143 +1,201 @@
 
1
  import streamlit as st
2
  import feedparser
3
  import requests
4
- from bs4 import BeautifulSoup
5
- from newspaper import Article
6
- import time
7
  import json
8
- import datetime
9
- import hashlib
10
  import os
 
 
 
 
11
 
12
- # --- Page Config ---
13
- st.set_page_config(
14
- page_title="భారత్ పల్స్ (BharatPulse)",
15
- page_icon="📰",
16
- layout="wide"
17
- )
18
-
19
- # --- Auth Setup ---
20
- USERS_FILE = "/tmp/users.json"
21
 
22
- def hash_password(password):
23
- return hashlib.sha256(password.encode()).hexdigest()
 
 
24
 
25
  def load_users():
26
- if os.path.exists(USERS_FILE):
27
- with open(USERS_FILE, "r") as f:
28
- return json.load(f)
29
- return {}
30
 
31
  def save_users(users):
32
  with open(USERS_FILE, "w") as f:
33
  json.dump(users, f, indent=2)
34
 
35
- def login_user(username, password):
36
  users = load_users()
37
- if username in users and users[username]["password"] == hash_password(password):
38
- return users[username]
39
- return None
40
-
41
- def register_user(username, email, password, location=""):
42
- users = load_users()
43
- if username in users:
44
- return False, "User already exists"
45
- users[username] = {
46
  "email": email,
47
- "password": hash_password(password),
48
- "location": location,
49
- "created": datetime.datetime.now().strftime("%Y-%m-%d")
50
  }
51
  save_users(users)
52
- return True, "Registration successful"
53
 
54
- # --- Session Init ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55
  if "logged_in" not in st.session_state:
56
  st.session_state.logged_in = False
57
- st.session_state.username = ""
58
-
59
- # --- Login/Register Page ---
60
- def show_login_page():
61
- st.title("🔐 లాగిన్ (Login)")
62
- username = st.text_input("వినియోగదారు పేరు (Username)")
63
- password = st.text_input("పాస్‌వర్డ్ (Password)", type="password")
64
-
65
- if st.button("లాగిన్ చేయండి (Login)"):
66
- user = login_user(username, password)
67
- if user:
68
- st.session_state.logged_in = True
69
- st.session_state.username = username
70
- st.session_state.user_email = user.get("email", "")
71
- st.session_state.user_location = user.get("location", "")
72
- st.rerun()
73
- else:
74
- st.error("చెల్లని లాగిన్ వివరాలు.")
75
-
76
- with st.expander("👉 ఖాతా రిజిస్టర్ (Register)"):
77
- new_username = st.text_input("కొత్త వినియోగదారు పేరు", key="register_username")
78
- new_email = st.text_input("ఇమెయిల్", key="register_email")
79
- new_password = st.text_input("పాస్‌వర్డ్", type="password", key="register_password")
80
- new_location = st.text_input("స్థానం (ఐచ్ఛికం)", key="register_location")
81
- if st.button("రిజిస్టర్ (Register)"):
82
- success, msg = register_user(new_username, new_email, new_password, new_location)
83
- st.success(msg) if success else st.error(msg)
84
-
85
- # --- Stop Here if Not Logged In ---
86
  if not st.session_state.logged_in:
87
- show_login_page()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
88
  st.stop()
89
 
90
- # --- Sidebar & Logout ---
91
- st.sidebar.title("సెట్టింగ్‌లు")
92
- if st.sidebar.button("🚪 లాగ్ అవుట్"):
 
 
93
  st.session_state.logged_in = False
94
- st.session_state.username = ""
95
  st.rerun()
96
 
97
- # --- BharatPulse UI ---
98
- st.title("🇮🇳 భారత్ పల్స్ (BharatPulse)")
99
- st.subheader(f"హాయ్, {st.session_state.username} 🌟")
100
-
101
- main_tabs = st.tabs(["📰 తాజా వార్తలు", "📍 నా ప్రాంతం", "🔍 నగర శోధన", "👤 ప్రొఫైల్"])
102
-
103
- # --- 1. Headlines Tab ---
104
- with main_tabs[0]:
105
- st.header("📰 తాజా వార్తలు (Top Headlines)")
106
- urls = [
107
- "https://www.sakshi.com/rss/district-news/medak.xml",
108
- "https://www.sakshi.com/rss/district-news/nizamabad.xml"
109
- ]
110
- for url in urls:
111
- st.subheader(f"📡 Feed: {url.split('/')[-1].replace('.xml','').capitalize()}")
112
  feed = feedparser.parse(url)
113
  for entry in feed.entries[:3]:
114
- st.markdown(f"### 📰 {entry.title}")
115
  st.write(entry.published)
116
- st.write(entry.link)
 
 
 
 
117
  st.markdown("---")
118
 
119
- # --- 2. Location Tab ---
120
- with main_tabs[1]:
121
- st.header("📍 మీ ప్రాంతానికి సంబంధించిన వార్తలు")
122
- user_location = st.session_state.get("user_location", "")
123
- if user_location:
124
- st.write(f"మీ స్థానం: **{user_location}**")
125
- st.write("ఇక్కడ మీ స్థానిక వార్తలు చూపించబడతాయి (గత ఇంటిగ్రేషన్ ఆధారంగా).")
126
- else:
127
- st.info("దయచేసి ప్రొఫైల్‌లో మీ స్థానం జోడించండి.")
128
-
129
- # --- 3. City Search Tab ---
130
- with main_tabs[2]:
131
- st.header("🔍 నగర శోధన")
132
- city = st.text_input("Search your city/town name:")
133
  if city:
134
- st.write(f"Showing news for: **{city}** (dummy results)")
135
- # Later: map city to RSS or Wikidata
136
-
137
- # --- 4. Profile Tab ---
138
- with main_tabs[3]:
139
- st.header("👤 మీ ప్రొఫైల్")
140
- st.write(f"**Username:** {st.session_state.username}")
141
- st.write(f"**Email:** {st.session_state.get('user_email', '')}")
142
- st.write(f"**Location:** {st.session_state.get('user_location', '')}")
143
- st.write(f"**Account Created On:** {load_users().get(st.session_state.username, {}).get('created', 'NA')}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
  import streamlit as st
3
  import feedparser
4
  import requests
 
 
 
5
  import json
 
 
6
  import os
7
+ from bs4 import BeautifulSoup
8
+ from transformers import MarianMTModel, MarianTokenizer
9
+ import whisper
10
+ from streamlit_audio_recorder import st_audiorec
11
 
12
+ st.set_page_config(page_title="📍 BharatPulse - Local News & Sentiment", layout="wide")
 
 
 
 
 
 
 
 
13
 
14
+ # ------------------------------
15
+ # User Auth Functions
16
+ # ------------------------------
17
+ USERS_FILE = "users.json"
18
 
19
  def load_users():
20
+ if not os.path.exists(USERS_FILE):
21
+ return {}
22
+ with open(USERS_FILE, "r") as f:
23
+ return json.load(f)
24
 
25
  def save_users(users):
26
  with open(USERS_FILE, "w") as f:
27
  json.dump(users, f, indent=2)
28
 
29
+ def register_user(username, email, password, location):
30
  users = load_users()
31
+ if email in users:
32
+ return False, "User already exists."
33
+ users[email] = {
34
+ "username": username,
 
 
 
 
 
35
  "email": email,
36
+ "password": password,
37
+ "location": location
 
38
  }
39
  save_users(users)
40
+ return True, "Registration successful."
41
 
42
+ def login_user(email, password):
43
+ users = load_users()
44
+ user = users.get(email)
45
+ if user and user["password"] == password:
46
+ return True, user
47
+ return False, "Invalid credentials."
48
+
49
+ # ------------------------------
50
+ # Whisper Model
51
+ # ------------------------------
52
+ @st.cache_resource
53
+ def load_whisper_model():
54
+ return whisper.load_model("base")
55
+
56
+ def transcribe_audio(audio_bytes):
57
+ path = "/tmp/voice.wav"
58
+ with open(path, "wb") as f:
59
+ f.write(audio_bytes)
60
+ model = load_whisper_model()
61
+ result = model.transcribe(path, language="te")
62
+ return result["text"]
63
+
64
+ # ------------------------------
65
+ # Translation Model
66
+ # ------------------------------
67
+ @st.cache_resource
68
+ def load_translation_model():
69
+ model_name = "Helsinki-NLP/opus-mt-en-te"
70
+ tokenizer = MarianTokenizer.from_pretrained(model_name)
71
+ model = MarianMTModel.from_pretrained(model_name)
72
+ return tokenizer, model
73
+
74
+ def translate_to_telugu(text):
75
+ tokenizer, model = load_translation_model()
76
+ tokens = tokenizer.prepare_seq2seq_batch([text], return_tensors="pt", truncation=True, max_length=512)
77
+ translated = model.generate(**tokens)
78
+ return tokenizer.decode(translated[0], skip_special_tokens=True)
79
+
80
+ # ------------------------------
81
+ # Extract Article Summary
82
+ # ------------------------------
83
+ def extract_article_content(url):
84
+ try:
85
+ response = requests.get(url, timeout=5)
86
+ soup = BeautifulSoup(response.text, "html.parser")
87
+ paragraphs = soup.find_all('p')
88
+ content = ' '.join([p.get_text() for p in paragraphs[:5]])
89
+ return content
90
+ except Exception as e:
91
+ return str(e)
92
+
93
+ # ------------------------------
94
+ # Auth UI
95
+ # ------------------------------
96
  if "logged_in" not in st.session_state:
97
  st.session_state.logged_in = False
98
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
99
  if not st.session_state.logged_in:
100
+ st.title("🔐 Login to BharatPulse")
101
+
102
+ tab1, tab2 = st.tabs(["🔑 Login", "📝 Register"])
103
+
104
+ with tab1:
105
+ email = st.text_input("Email")
106
+ password = st.text_input("Password", type="password")
107
+ if st.button("Login"):
108
+ success, user_or_msg = login_user(email, password)
109
+ if success:
110
+ st.session_state.logged_in = True
111
+ st.session_state.user = user_or_msg
112
+ st.rerun()
113
+ else:
114
+ st.error(user_or_msg)
115
+
116
+ with tab2:
117
+ new_username = st.text_input("Username")
118
+ new_email = st.text_input("New Email")
119
+ new_password = st.text_input("New Password", type="password")
120
+ new_location = st.text_input("Location")
121
+ if st.button("Register"):
122
+ success, message = register_user(new_username, new_email, new_password, new_location)
123
+ if success:
124
+ st.success(message)
125
+ else:
126
+ st.error(message)
127
  st.stop()
128
 
129
+ # ------------------------------
130
+ # Main News UI
131
+ # ------------------------------
132
+ st.sidebar.success(f"Logged in as: {st.session_state.user['username']}")
133
+ if st.sidebar.button("🚪 Logout"):
134
  st.session_state.logged_in = False
135
+ st.session_state.user = None
136
  st.rerun()
137
 
138
+ st.title("📍 BharatPulse")
139
+ tabs = st.tabs(["📰 Headlines", "🔍 Search by City", "🎤 Voice Search"])
140
+
141
+ feeds = {
142
+ "Sakshi - Medak": "https://www.sakshi.com/rss/district-news/medak.xml",
143
+ "Eenadu - AP": "https://www.eenadu.net/rss/andhra-pradesh.xml"
144
+ }
145
+
146
+ # ------------------------------
147
+ # 📰 Headlines Tab
148
+ # ------------------------------
149
+ with tabs[0]:
150
+ st.header("📰 Local Telugu News")
151
+ for name, url in feeds.items():
152
+ st.subheader(name)
153
  feed = feedparser.parse(url)
154
  for entry in feed.entries[:3]:
155
+ st.markdown(f"### {entry.title}")
156
  st.write(entry.published)
157
+ st.markdown(f"[Read Full Article]({entry.link})")
158
+ summary = extract_article_content(entry.link)
159
+ st.markdown("**English Summary:** " + summary)
160
+ telugu_summary = translate_to_telugu(summary)
161
+ st.markdown("**తెలుగు అనువాదం:** " + telugu_summary)
162
  st.markdown("---")
163
 
164
+ # ------------------------------
165
+ # 🔍 Search by City
166
+ # ------------------------------
167
+ with tabs[1]:
168
+ st.header("🔎 Search by City / District")
169
+ city = st.text_input("Enter your city/district name in Telugu or English")
170
+
 
 
 
 
 
 
 
171
  if city:
172
+ st.success(f"Showing news for: {city}")
173
+ for name, url in feeds.items():
174
+ if city.lower() in name.lower():
175
+ st.subheader(name)
176
+ feed = feedparser.parse(url)
177
+ for entry in feed.entries[:2]:
178
+ st.markdown(f"**🗞️ {entry.title}**")
179
+ summary = extract_article_content(entry.link)
180
+ telugu_summary = translate_to_telugu(summary)
181
+ st.markdown("**తెలుగు అనువాదం:** " + telugu_summary)
182
+
183
+ # ------------------------------
184
+ # 🎤 Voice Search Tab
185
+ # ------------------------------
186
+ with tabs[2]:
187
+ st.header("🎤 Search by Telugu Voice")
188
+ audio = st_audiorec()
189
+ if audio:
190
+ transcribed = transcribe_audio(audio)
191
+ st.success(f"Voice Input Recognized: {transcribed}")
192
+ city = transcribed
193
+ for name, url in feeds.items():
194
+ if city.lower() in name.lower():
195
+ st.subheader(name)
196
+ feed = feedparser.parse(url)
197
+ for entry in feed.entries[:2]:
198
+ st.markdown(f"**🗞️ {entry.title}**")
199
+ summary = extract_article_content(entry.link)
200
+ telugu_summary = translate_to_telugu(summary)
201
+ st.markdown("**తెలుగు అనువాదం:** " + telugu_summary)