GHarshasri commited on
Commit
c5a42d9
·
verified ·
1 Parent(s): c0d00b5

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +19 -252
src/streamlit_app.py CHANGED
@@ -1,252 +1,19 @@
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
-
8
- # ====== Setup ======
9
- USERS = {}
10
- UPLOAD_FOLDER = "uploads"
11
- MEDIA_FOLDER = os.path.join(UPLOAD_FOLDER, "feedback_media")
12
- FEEDBACK_FILE = os.path.join(UPLOAD_FOLDER, "feedback.csv")
13
-
14
- # ====== Ensure Upload Folders Exist ======
15
- os.makedirs(MEDIA_FOLDER, exist_ok=True)
16
-
17
- STATES = {
18
- "Telangana": ["Hyderabad", "Warangal", "Nizamabad", "Karimnagar", "Khammam"],
19
- "Maharashtra": ["Mumbai", "Pune", "Nagpur", "Nashik", "Aurangabad"],
20
- "Tamil Nadu": ["Chennai", "Coimbatore", "Madurai", "Tiruchirappalli", "Salem"],
21
- "Karnataka": ["Bangalore", "Mysore", "Mangalore", "Hubli", "Belgaum"],
22
- "Uttar Pradesh": ["Lucknow", "Varanasi", "Agra", "Kanpur", "Allahabad"],
23
- "West Bengal": ["Kolkata", "Darjeeling", "Durgapur", "Siliguri", "Asansol"],
24
- "Rajasthan": ["Jaipur", "Udaipur", "Jodhpur", "Bikaner", "Ajmer"],
25
- "Gujarat": ["Ahmedabad", "Surat", "Vadodara", "Rajkot", "Bhavnagar"],
26
- "Andhra Pradesh": ["Visakhapatnam", "Vijayawada", "Guntur", "Tirupati", "Kurnool"],
27
- }
28
-
29
- # ====== Session State Initialization ======
30
- for key, default in {
31
- "logged_in": False,
32
- "email": "",
33
- "otp_sent_to": None,
34
- "otp_verified": False,
35
- "login_email": None,
36
- }.items():
37
- if key not in st.session_state:
38
- st.session_state[key] = default
39
-
40
- # ====== Helper Functions ======
41
-
42
- def send_otp(email):
43
- st.session_state.otp_sent_to = email
44
- st.session_state.otp_verified = False
45
- return "1234"
46
-
47
- def verify_otp(entered_otp):
48
- if st.session_state.otp_sent_to and entered_otp == "1234":
49
- st.session_state.logged_in = True
50
- st.session_state.email = st.session_state.otp_sent_to
51
- st.session_state.otp_verified = True
52
- st.session_state.login_email = None
53
- return True
54
- return False
55
-
56
- def logout():
57
- for key in ["logged_in", "email", "otp_sent_to", "otp_verified", "login_email"]:
58
- st.session_state[key] = False if isinstance(st.session_state.get(key), bool) else None
59
-
60
- def fetch_wikipedia_summary(title, lang="en"):
61
- try:
62
- wikipedia.set_lang(lang)
63
- return wikipedia.summary(title, sentences=4)
64
- except wikipedia.exceptions.DisambiguationError as e:
65
- return f"Multiple results found for '{title}': {e.options}"
66
- except wikipedia.exceptions.PageError:
67
- return f"No Wikipedia page found for '{title}' in selected language."
68
- except Exception as e:
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.read())
77
- return filepath
78
- return ""
79
-
80
- def save_feedback(email, place, state, district, text, img_path="", audio_path="", video_path=""):
81
- if not os.path.exists(FEEDBACK_FILE):
82
- with open(FEEDBACK_FILE, 'w', newline='', encoding='utf-8') as f:
83
- writer = csv.writer(f)
84
- writer.writerow([
85
- "user_email", "place_name", "state", "district", "feedback_text",
86
- "image_file", "audio_file", "video_file", "timestamp"
87
- ])
88
- with open(FEEDBACK_FILE, 'a', newline='', encoding='utf-8') as f:
89
- writer = csv.writer(f)
90
- writer.writerow([
91
- email, place, state, district, text,
92
- img_path, audio_path, video_path, datetime.now().isoformat()
93
- ])
94
-
95
- # ====== Pages ======
96
-
97
- def signup_page():
98
- st.header("🚀 Signup")
99
- name = st.text_input("Name")
100
- email = st.text_input("Email (Gmail)")
101
- contact = st.text_input("Contact Number")
102
- if st.button("Sign Up"):
103
- if email in USERS:
104
- st.error("User already exists, please login.")
105
- elif not email or not name:
106
- st.error("Please enter name and email.")
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():
114
- st.header("🔐 Login")
115
- email = st.text_input("Email", key="login_email_input")
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
-
131
- def main_app():
132
- st.sidebar.success(f"Logged in as {st.session_state.email}")
133
- if st.sidebar.button("Logout"):
134
- logout()
135
- st.experimental_rerun()
136
-
137
- st.sidebar.markdown("---")
138
- st.sidebar.subheader("📝 Give Feedback")
139
- feedback_text = st.sidebar.text_area("Your thoughts about this place", height=100)
140
- feedback_image = st.sidebar.file_uploader("Upload an image", type=["jpg", "jpeg", "png"])
141
- feedback_audio = st.sidebar.file_uploader("Upload audio", type=["mp3", "wav", "m4a"])
142
- feedback_video = st.sidebar.file_uploader("Upload video", type=["mp4", "mov", "avi"])
143
-
144
- if feedback_image:
145
- st.sidebar.image(feedback_image, caption="Your uploaded image", use_container_width=True)
146
- if feedback_audio:
147
- st.sidebar.audio(feedback_audio, format=feedback_audio.type)
148
- if feedback_video:
149
- st.sidebar.video(feedback_video)
150
-
151
- st.title("📚 Gyana Vedika - Cultural Explorer")
152
-
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",
164
- "golconda": "Golconda Fort",
165
- "qutubshahi": "Qutb Shahi Tombs",
166
- "birla": "Birla Mandir",
167
- "salarjung": "Salar Jung Museum",
168
- "warangal": "Warangal Fort",
169
- "ramappa": "Ramappa Temple",
170
- "bhadrakali": "Bhadra Kali Temple",
171
- "kakatiya": "Kakatiya Kala Thoranam",
172
- "pakhal": "Pakhal Lake",
173
- "medak": "Medak Cathedral",
174
- "nagarjuna": "Nagarjuna Sagar Dam",
175
- "taj": "Taj Mahal",
176
- "gateway": "Gateway of India",
177
- "qutub": "Qutub Minar",
178
- "mysore": "Mysore Palace",
179
- "hampi": "Hampi",
180
- "konark": "Konark Sun Temple",
181
- "varanasi": "Varanasi",
182
- "madurai": "Meenakshi Temple",
183
- "ajanta": "Ajanta Caves",
184
- "ellora": "Ellora Caves",
185
- }
186
- for kw, place in keywords_map.items():
187
- if kw in filename:
188
- place_to_search = place
189
- st.success(f"Recognized Place: {place_to_search}")
190
- break
191
- if not place_to_search:
192
- st.warning("Could not recognize place. Try renaming the image file with landmark name.")
193
-
194
- manual_place = st.text_input("Or manually enter place name to search info")
195
- if manual_place.strip():
196
- place_to_search = manual_place.strip()
197
-
198
- if place_to_search:
199
- language = st.selectbox("Select Wikipedia summary language", ["English", "Hindi", "Telugu", "Tamil", "Marathi", "Bengali"])
200
- lang_codes = {"English": "en", "Hindi": "hi", "Telugu": "te", "Tamil": "ta", "Marathi": "mr", "Bengali": "bn"}
201
- lang_code = lang_codes.get(language, "en")
202
- if st.button(f"Get info about {place_to_search}"):
203
- with st.spinner(f"Fetching Wikipedia summary for {place_to_search}..."):
204
- summary = fetch_wikipedia_summary(place_to_search, lang=lang_code)
205
- st.markdown(f"### Summary of {place_to_search}")
206
- st.write(summary)
207
-
208
- if st.sidebar.button("Submit Feedback"):
209
- if feedback_text.strip():
210
- img_path = save_temp_file(feedback_image, "img")
211
- audio_path = save_temp_file(feedback_audio, "audio")
212
- video_path = save_temp_file(feedback_video, "video")
213
-
214
- save_feedback(
215
- email=st.session_state.email,
216
- place=place_to_search or "Unknown",
217
- state=state,
218
- district=district,
219
- text=feedback_text.strip(),
220
- img_path=img_path,
221
- audio_path=audio_path,
222
- video_path=video_path
223
- )
224
- st.sidebar.success("Thank you! Feedback submitted.")
225
- else:
226
- st.sidebar.warning("Please enter your feedback text.")
227
-
228
- # ====== UI Styling ======
229
- st.set_page_config(page_title="Gyana Vedika", layout="wide")
230
-
231
- st.markdown("""
232
- <style>
233
- .stButton>button {
234
- background-color: #008080; color: white; font-weight: bold; border-radius: 10px;
235
- }
236
- .stTextInput>div>input, .stSelectbox>div>div>select, .stTextArea>div>textarea {
237
- border: 2px solid #008080 !important; border-radius: 8px !important;
238
- }
239
- h1, h2, h3, h4, h5, h6 {
240
- color: #004d4d;
241
- }
242
- </style>
243
- """, unsafe_allow_html=True)
244
-
245
- if not st.session_state.logged_in:
246
- page = st.sidebar.radio("Choose Option", ["Signup", "Login"])
247
- if page == "Signup":
248
- signup_page()
249
- elif page == "Login":
250
- login_page()
251
- else:
252
- main_app()
 
1
+ if st.sidebar.button("Submit Feedback"):
2
+ if feedback_text.strip():
3
+ img_path = save_temp_file(feedback_image, "img")
4
+ audio_path = save_temp_file(feedback_audio, "audio")
5
+ video_path = save_temp_file(feedback_video, "video")
6
+
7
+ save_feedback(
8
+ email=st.session_state.email,
9
+ place=place_to_search or "Unknown",
10
+ state=state,
11
+ district=district,
12
+ text=feedback_text.strip(),
13
+ img_path=img_path,
14
+ audio_path=audio_path,
15
+ video_path=video_path
16
+ )
17
+ st.sidebar.success("Thank you! Feedback submitted.")
18
+ else:
19
+ st.sidebar.warning("Please enter your feedback text.")