GHarshasri commited on
Commit
d903b86
Β·
verified Β·
1 Parent(s): 0ccec8a

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +75 -53
src/streamlit_app.py CHANGED
@@ -1,15 +1,14 @@
1
  import streamlit as st
2
  from PIL import Image
3
- import os
4
  import wikipedia
5
  import csv
6
  from datetime import datetime
7
  import tempfile
 
8
 
9
  # ====== Setup ======
10
  USERS = {}
11
 
12
- # Use a writable temporary directory to avoid permission issues
13
  UPLOAD_FOLDER = tempfile.mkdtemp()
14
  MEDIA_FOLDER = os.path.join(UPLOAD_FOLDER, "feedback_media")
15
  FEEDBACK_FILE = os.path.join(UPLOAD_FOLDER, "feedback.csv")
@@ -40,7 +39,6 @@ for key, default in {
40
  st.session_state[key] = default
41
 
42
  # ====== Helper Functions ======
43
-
44
  def send_otp(email):
45
  st.session_state.otp_sent_to = email
46
  st.session_state.otp_verified = False
@@ -71,15 +69,12 @@ def fetch_wikipedia_summary(title, lang="en"):
71
  return f"Error fetching summary: {str(e)}"
72
 
73
  def save_temp_file(uploaded_file, filetype):
74
- if uploaded_file is not None:
75
  filename = f"{filetype}_{datetime.now().strftime('%Y%m%d%H%M%S')}_{uploaded_file.name}"
76
  filepath = os.path.join(MEDIA_FOLDER, filename)
77
- try:
78
- with open(filepath, "wb") as f:
79
- f.write(uploaded_file.getbuffer())
80
- return filepath
81
- except Exception as e:
82
- st.error(f"Failed to save {filetype} file: {e}")
83
  return ""
84
 
85
  def save_feedback(email, place, state, district, text, img_path="", audio_path="", video_path=""):
@@ -90,6 +85,7 @@ def save_feedback(email, place, state, district, text, img_path="", audio_path="
90
  "user_email", "place_name", "state", "district", "feedback_text",
91
  "image_file", "audio_file", "video_file", "timestamp"
92
  ])
 
93
  with open(FEEDBACK_FILE, 'a', newline='', encoding='utf-8') as f:
94
  writer = csv.writer(f)
95
  writer.writerow([
@@ -98,7 +94,6 @@ def save_feedback(email, place, state, district, text, img_path="", audio_path="
98
  ])
99
 
100
  # ====== Pages ======
101
-
102
  def signup_page():
103
  st.header("πŸš€ Signup")
104
  name = st.text_input("Name")
@@ -112,7 +107,7 @@ def signup_page():
112
  else:
113
  USERS[email] = {"name": name, "email": email, "contact": contact}
114
  send_otp(email)
115
- st.success(f"User {name} registered! OTP sent to {email} (simulated).")
116
  st.session_state.login_email = email
117
 
118
  def login_page():
@@ -121,15 +116,15 @@ def login_page():
121
  if st.button("Send OTP"):
122
  if email in USERS:
123
  send_otp(email)
124
- st.success(f"OTP sent to {email} (simulated).")
125
  st.session_state.login_email = email
126
  else:
127
  st.error("Email not found. Please sign up first.")
128
  if st.session_state.login_email == email:
129
- otp = st.text_input("Enter OTP (use 1234)", type="password")
130
  if st.button("Verify OTP"):
131
  if verify_otp(otp):
132
- st.success("Logged in successfully.")
133
  else:
134
  st.error("Incorrect OTP or no OTP sent.")
135
 
@@ -138,52 +133,61 @@ def main_app():
138
  if st.sidebar.button("Logout"):
139
  logout()
140
  st.experimental_rerun()
 
 
141
  st.sidebar.markdown("---")
142
  st.sidebar.subheader("πŸ“ Give Feedback")
143
- feedback_text = st.sidebar.text_area("Your thoughts", height=100)
144
- feedback_image = st.sidebar.file_uploader("Upload image", type=["jpg","jpeg","png"])
145
- feedback_audio = st.sidebar.file_uploader("Upload audio", type=["mp3","wav","m4a"])
146
- feedback_video = st.sidebar.file_uploader("Upload video", type=["mp4","mov","avi"])
147
-
148
- if feedback_image: st.sidebar.image(feedback_image, caption="Preview", use_container_width=True)
149
- if feedback_audio: st.sidebar.audio(feedback_audio)
150
- if feedback_video: st.sidebar.video(feedback_video)
 
 
 
151
 
152
  st.title("πŸ“š Gyana Vedika - Cultural Explorer")
153
  state = st.selectbox("Select State", list(STATES.keys()))
154
  district = st.selectbox("Select District", STATES[state])
155
  st.subheader(f"Explore {district}, {state}")
156
 
157
- uploaded_image = st.file_uploader("Upload cultural place image", type=["png","jpg","jpeg"])
158
  place_to_search = None
159
  if uploaded_image:
160
- st.image(uploaded_image, use_container_width=True)
161
- fn = uploaded_image.name.lower()
162
- keywords = {
163
- "charminar":"Charminar","golconda":"Golconda Fort","taj":"Taj Mahal",
164
- "gateway":"Gateway of India","qutub":"Qutub Minar","mysore":"Mysore Palace",
165
- "hampi":"Hampi","konark":"Konark Sun Temple","varanasi":"Varanasi",
166
- "madurai":"Meenakshi Temple","ajanta":"Ajanta Caves","ellora":"Ellora Caves"
 
 
 
167
  }
168
- for kw, place in keywords.items():
169
- if kw in fn:
170
  place_to_search = place
171
- st.success(f"Recognized: {place}")
172
  break
173
  if not place_to_search:
174
- st.warning("Could not recognize place. Rename your file.")
175
 
176
- manual_place = st.text_input("Or enter place name manually")
177
  if manual_place.strip():
178
  place_to_search = manual_place.strip()
179
 
180
  if place_to_search:
181
- lang = st.selectbox("Wikipedia language", ["English","Hindi","Telugu","Tamil","Marathi","Bengali"])
182
- codes = {"English":"en","Hindi":"hi","Telugu":"te","Tamil":"ta","Marathi":"mr","Bengali":"bn"}
183
- if st.button(f"Get info: {place_to_search}"):
184
- with st.spinner("Fetching..."):
185
- summary = fetch_wikipedia_summary(place_to_search, lang=codes[lang])
186
- st.markdown(f"### {place_to_search} ({lang})")
 
187
  st.write(summary)
188
 
189
  if st.sidebar.button("Submit Feedback"):
@@ -191,24 +195,42 @@ def main_app():
191
  img_path = save_temp_file(feedback_image, "img")
192
  audio_path = save_temp_file(feedback_audio, "audio")
193
  video_path = save_temp_file(feedback_video, "video")
194
- st.sidebar.write(f"Saved files:\nβ€’ Image: {img_path}\nβ€’ Audio: {audio_path}\nβ€’ Video: {video_path}")
195
- save_feedback(st.session_state.email, place_to_search or "Unknown", state, district, feedback_text.strip(), img_path, audio_path, video_path)
196
- st.sidebar.success("Thanks for your feedback!")
 
 
 
 
 
 
 
 
197
  else:
198
- st.sidebar.warning("Please enter feedback text.")
199
 
200
  # ====== UI Styling ======
201
  st.set_page_config(page_title="Gyana Vedika", layout="wide")
 
202
  st.markdown("""
203
  <style>
204
- .stButton>button { background-color: #008080; color: white; font-weight: bold; border-radius: 8px; }
205
- .stTextInput>div>input, .stSelectbox>div>div>select, .stTextArea>div>textarea { border:2px solid #008080!important; border-radius:6px!important; }
206
- h1, h2, h3, h4 { color:#004d4d; }
207
- </style>""", unsafe_allow_html=True)
 
 
 
 
 
 
 
208
 
209
- # ====== Run App ======
210
  if not st.session_state.logged_in:
211
- page = st.sidebar.radio("Choose Option", ["Signup","Login"])
212
- signup_page() if page=="Signup" else login_page()
 
 
 
213
  else:
214
  main_app()
 
1
  import streamlit as st
2
  from PIL import Image
 
3
  import wikipedia
4
  import csv
5
  from datetime import datetime
6
  import tempfile
7
+ import os
8
 
9
  # ====== Setup ======
10
  USERS = {}
11
 
 
12
  UPLOAD_FOLDER = tempfile.mkdtemp()
13
  MEDIA_FOLDER = os.path.join(UPLOAD_FOLDER, "feedback_media")
14
  FEEDBACK_FILE = os.path.join(UPLOAD_FOLDER, "feedback.csv")
 
39
  st.session_state[key] = default
40
 
41
  # ====== Helper Functions ======
 
42
  def send_otp(email):
43
  st.session_state.otp_sent_to = email
44
  st.session_state.otp_verified = False
 
69
  return f"Error fetching summary: {str(e)}"
70
 
71
  def save_temp_file(uploaded_file, filetype):
72
+ if uploaded_file:
73
  filename = f"{filetype}_{datetime.now().strftime('%Y%m%d%H%M%S')}_{uploaded_file.name}"
74
  filepath = os.path.join(MEDIA_FOLDER, filename)
75
+ with open(filepath, "wb") as f:
76
+ f.write(uploaded_file.getbuffer())
77
+ return filepath
 
 
 
78
  return ""
79
 
80
  def save_feedback(email, place, state, district, text, img_path="", audio_path="", video_path=""):
 
85
  "user_email", "place_name", "state", "district", "feedback_text",
86
  "image_file", "audio_file", "video_file", "timestamp"
87
  ])
88
+
89
  with open(FEEDBACK_FILE, 'a', newline='', encoding='utf-8') as f:
90
  writer = csv.writer(f)
91
  writer.writerow([
 
94
  ])
95
 
96
  # ====== Pages ======
 
97
  def signup_page():
98
  st.header("πŸš€ Signup")
99
  name = st.text_input("Name")
 
107
  else:
108
  USERS[email] = {"name": name, "email": email, "contact": contact}
109
  send_otp(email)
110
+ st.success(f"User {name} registered! OTP sent to {email} (simulated). Please verify OTP on Login page.")
111
  st.session_state.login_email = email
112
 
113
  def login_page():
 
116
  if st.button("Send OTP"):
117
  if email in USERS:
118
  send_otp(email)
119
+ st.success(f"OTP sent to {email} (simulated). Please enter OTP below.")
120
  st.session_state.login_email = email
121
  else:
122
  st.error("Email not found. Please sign up first.")
123
  if st.session_state.login_email == email:
124
+ otp = st.text_input("Enter OTP (use 1234 for demo)", type="password")
125
  if st.button("Verify OTP"):
126
  if verify_otp(otp):
127
+ st.success("OTP verified! Logged in successfully.")
128
  else:
129
  st.error("Incorrect OTP or no OTP sent.")
130
 
 
133
  if st.sidebar.button("Logout"):
134
  logout()
135
  st.experimental_rerun()
136
+
137
+ # Feedback inputs on left sidebar
138
  st.sidebar.markdown("---")
139
  st.sidebar.subheader("πŸ“ Give Feedback")
140
+ feedback_text = st.sidebar.text_area("Your thoughts about this place", height=100)
141
+ feedback_image = st.sidebar.file_uploader("Upload an image", type=["jpg", "jpeg", "png"])
142
+ feedback_audio = st.sidebar.file_uploader("Upload audio", type=["mp3", "wav", "m4a"])
143
+ feedback_video = st.sidebar.file_uploader("Upload video", type=["mp4", "mov", "avi"])
144
+
145
+ if feedback_image:
146
+ st.sidebar.image(feedback_image, caption="Your uploaded image", use_container_width=True)
147
+ if feedback_audio:
148
+ st.sidebar.audio(feedback_audio, format=feedback_audio.type)
149
+ if feedback_video:
150
+ st.sidebar.video(feedback_video)
151
 
152
  st.title("πŸ“š Gyana Vedika - Cultural Explorer")
153
  state = st.selectbox("Select State", list(STATES.keys()))
154
  district = st.selectbox("Select District", STATES[state])
155
  st.subheader(f"Explore {district}, {state}")
156
 
157
+ uploaded_image = st.file_uploader("Upload a cultural/historical place image", type=["png", "jpg", "jpeg"])
158
  place_to_search = None
159
  if uploaded_image:
160
+ st.image(uploaded_image, caption="Uploaded Image", use_container_width=True)
161
+ filename = uploaded_image.name.lower()
162
+ keywords_map = {
163
+ "charminar": "Charminar", "golconda": "Golconda Fort", "qutubshahi": "Qutb Shahi Tombs",
164
+ "birla": "Birla Mandir", "salarjung": "Salar Jung Museum", "warangal": "Warangal Fort",
165
+ "ramappa": "Ramappa Temple", "bhadrakali": "Bhadra Kali Temple", "kakatiya": "Kakatiya Kala Thoranam",
166
+ "pakhal": "Pakhal Lake", "medak": "Medak Cathedral", "nagarjuna": "Nagarjuna Sagar Dam",
167
+ "taj": "Taj Mahal", "gateway": "Gateway of India", "qutub": "Qutub Minar",
168
+ "mysore": "Mysore Palace", "hampi": "Hampi", "konark": "Konark Sun Temple",
169
+ "varanasi": "Varanasi", "madurai": "Meenakshi Temple", "ajanta": "Ajanta Caves", "ellora": "Ellora Caves"
170
  }
171
+ for kw, place in keywords_map.items():
172
+ if kw in filename:
173
  place_to_search = place
174
+ st.success(f"Recognized Place: {place_to_search}")
175
  break
176
  if not place_to_search:
177
+ st.warning("Could not recognize place. Try renaming the image file with landmark name.")
178
 
179
+ manual_place = st.text_input("Or manually enter place name to search info")
180
  if manual_place.strip():
181
  place_to_search = manual_place.strip()
182
 
183
  if place_to_search:
184
+ language = st.selectbox("Select Wikipedia summary language", ["English", "Hindi", "Telugu", "Tamil", "Marathi", "Bengali"])
185
+ lang_codes = {"English": "en", "Hindi": "hi", "Telugu": "te", "Tamil": "ta", "Marathi": "mr", "Bengali": "bn"}
186
+ lang_code = lang_codes.get(language, "en")
187
+ if st.button(f"Get info about {place_to_search}"):
188
+ with st.spinner(f"Fetching Wikipedia summary for {place_to_search}..."):
189
+ summary = fetch_wikipedia_summary(place_to_search, lang=lang_code)
190
+ st.markdown(f"### Summary of {place_to_search}")
191
  st.write(summary)
192
 
193
  if st.sidebar.button("Submit Feedback"):
 
195
  img_path = save_temp_file(feedback_image, "img")
196
  audio_path = save_temp_file(feedback_audio, "audio")
197
  video_path = save_temp_file(feedback_video, "video")
198
+ save_feedback(
199
+ email=st.session_state.email,
200
+ place=place_to_search or "Unknown",
201
+ state=state,
202
+ district=district,
203
+ text=feedback_text.strip(),
204
+ img_path=img_path,
205
+ audio_path=audio_path,
206
+ video_path=video_path
207
+ )
208
+ st.sidebar.success("Thank you! Feedback submitted.")
209
  else:
210
+ st.sidebar.warning("Please enter your feedback text.")
211
 
212
  # ====== UI Styling ======
213
  st.set_page_config(page_title="Gyana Vedika", layout="wide")
214
+
215
  st.markdown("""
216
  <style>
217
+ .stButton>button {
218
+ background-color: #008080; color: white; font-weight: bold; border-radius: 10px;
219
+ }
220
+ .stTextInput>div>input, .stSelectbox>div>div>select, .stTextArea>div>textarea {
221
+ border: 2px solid #008080 !important; border-radius: 8px !important;
222
+ }
223
+ h1, h2, h3, h4, h5, h6 {
224
+ color: #004d4d;
225
+ }
226
+ </style>
227
+ """, unsafe_allow_html=True)
228
 
 
229
  if not st.session_state.logged_in:
230
+ page = st.sidebar.radio("Choose Option", ["Signup", "Login"])
231
+ if page == "Signup":
232
+ signup_page()
233
+ elif page == "Login":
234
+ login_page()
235
  else:
236
  main_app()