ChakriYamasani commited on
Commit
155c70c
Β·
verified Β·
1 Parent(s): df84150

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +72 -75
app.py CHANGED
@@ -39,7 +39,6 @@ if not st.session_state.authenticated:
39
  col1, col2 = st.columns([1, 1])
40
 
41
  with col1:
42
- # FIXED: Changed use_column_width to use_container_width
43
  st.image("https://images.pexels.com/photos/265216/pexels-photo-265216.jpeg",
44
  caption="Photo by Pixabay", use_container_width=True)
45
  st.markdown("""
@@ -111,19 +110,23 @@ with col2:
111
  st.session_state.username = None
112
  st.rerun()
113
 
114
- # Sidebar navigation
115
  st.sidebar.title("Navigation")
116
- page = st.sidebar.radio("Go to", [
117
- "🏠 Home",
118
- "✍️ Submit Wisdom",
119
- "πŸ“– Browse Knowledge",
120
- "πŸ—ΊοΈ Knowledge Map",
121
- "πŸ” Search",
122
- "🌐 Translation Hub",
123
- "πŸ“Š Export Data",
124
- "πŸ‘€ Profile"
125
- ], label_visibility="collapsed")
126
-
 
 
 
 
127
 
128
  # --- Home Page ---
129
  if page == "🏠 Home":
@@ -144,38 +147,40 @@ if page == "🏠 Home":
144
  st.markdown("### πŸš€ Getting Started")
145
  gs_cols = st.columns(3)
146
  with gs_cols[0]:
147
- with st.container(border=True):
148
  st.markdown("#### ✍️ Share Knowledge")
149
- st.markdown("Go to the **Submit Wisdom** page to contribute your traditional farming knowledge.")
 
 
150
  with gs_cols[1]:
151
- with st.container(border=True):
152
  st.markdown("#### πŸ“– Explore Entries")
153
- st.markdown("Visit the **Browse Knowledge** page to explore wisdom shared by the community.")
 
154
  with gs_cols[2]:
155
- with st.container(border=True):
156
  st.markdown("#### πŸ—ΊοΈ Discover on Map")
157
- st.markdown("Use the **Knowledge Map** to find location-specific farming practices.")
 
158
 
159
- # --- Submit Wisdom Page ---
160
  elif page == "✍️ Submit Wisdom":
161
- st.header("✍️ Submit Farming Wisdom")
162
- st.markdown("Use the helpers to set your location or record audio, then fill out the form and submit.")
163
 
164
  if 'form_data' not in st.session_state:
165
  st.session_state.form_data = {
166
- 'title': '', 'description': '', 'language': get_languages()[0],
167
- 'category': get_categories()[0], 'location_name': '',
168
- 'manual_lat': 20.5937, 'manual_lon': 78.9629 # Default to India
169
  }
170
 
171
- # --- HELPER TOOLS (OUTSIDE THE FORM) ---
172
- st.subheader("Helper Tools (Optional)")
173
  with st.container(border=True):
174
- # Geocode Helper
175
- st.markdown("**1. Find Location on Map**")
176
  geocode_cols = st.columns([3, 1])
177
- geocode_input = geocode_cols[0].text_input("Search for a place to pin on the map...", label_visibility="collapsed")
178
- if geocode_cols[1].button("🌍 Geocode", use_container_width=True):
179
  if geocode_input:
180
  coords = geocode_location(geocode_input)
181
  if coords:
@@ -183,65 +188,60 @@ elif page == "✍️ Submit Wisdom":
183
  st.success(f"Found and pinned: {geocode_input}")
184
  else:
185
  st.error(f"Could not find coordinates for '{geocode_input}'")
186
-
187
- # Speech-to-Text Helper
188
- st.markdown("**2. Record Description with Voice**")
189
  speech_cols = st.columns([3, 1])
190
  speech_language = speech_cols[0].selectbox("Language for Speech Recognition", get_languages(), key="speech_lang")
191
- if speech_cols[1].button("🎀 Record", use_container_width=True):
192
  with st.spinner("Listening..."):
193
  recorded_text = speech_to_text(speech_language)
194
  if recorded_text:
195
  st.session_state.form_data['description'] = recorded_text
196
- st.success(f"Recorded text has been added to the description field.")
197
- st.rerun() # Rerun to update the text_area in the form
198
  else:
199
- st.error("Could not record speech. Please try again.")
200
 
201
  st.markdown("---")
202
 
203
- # --- MAIN SUBMISSION FORM ---
204
- st.subheader("Entry Details Form")
205
  with st.form("entry_form", clear_on_submit=True):
206
- tab1, tab2, tab3 = st.tabs(["**✍️ Content**", "**πŸ“ Location**", "**πŸ“ Media Files**"])
207
-
208
- with tab1:
209
- st.markdown("##### Main Information")
210
- title = st.text_input("Title*", value=st.session_state.form_data.get('title', ''), placeholder="e.g., Natural Pest Repellent using Neem")
211
- # Use .get() for description to handle reruns from speech-to-text
212
- description = st.text_area("Description*", value=st.session_state.form_data.get('description', ''), height=200, placeholder="Describe the wisdom, practice, or story in detail...")
213
 
214
  col1, col2 = st.columns(2)
215
- language = col1.selectbox("Language*", get_languages(), index=get_languages().index(st.session_state.form_data.get('language', get_languages()[0])))
216
- category = col2.selectbox("Category*", get_categories(), index=get_categories().index(st.session_state.form_data.get('category', get_categories()[0])))
 
 
 
 
217
 
218
- with tab2:
219
- st.markdown("##### Geographic Details")
220
- location_name = st.text_input("Location Name", value=st.session_state.form_data.get('location_name', ''), placeholder="e.g., Warangal, Telangana")
221
-
222
- # Map for location selection
223
  map_center = [st.session_state.form_data['manual_lat'], st.session_state.form_data['manual_lon']]
224
- m = folium.Map(location=map_center, zoom_start=6)
225
- folium.Marker(map_center, popup="Your Selected Location").add_to(m)
226
  map_data = st_folium(m, width=700, height=400)
227
 
228
  if map_data and map_data['last_clicked']:
229
  st.session_state.form_data['manual_lat'] = map_data['last_clicked']['lat']
230
  st.session_state.form_data['manual_lon'] = map_data['last_clicked']['lng']
231
- st.rerun() # Rerun to update the number inputs below
232
-
233
- col3, col4 = st.columns(2)
234
- manual_lat = col3.number_input("Latitude", value=st.session_state.form_data['manual_lat'], format="%.6f")
235
- manual_lon = col4.number_input("Longitude", value=st.session_state.form_data['manual_lon'], format="%.6f")
236
 
237
- with tab3:
238
- st.markdown("##### Upload Files (Optional)")
 
 
 
 
239
  uploaded_image = st.file_uploader("Upload an Image", type=['jpg', 'jpeg', 'png'])
240
  uploaded_audio = st.file_uploader("Upload an Audio Recording", type=['mp3', 'wav', 'ogg'])
241
 
242
- # Form submission button (outside tabs)
243
  st.markdown("---")
244
- submitted = st.form_submit_button("βœ… Submit Entry", type="primary", use_container_width=True)
245
 
246
  if submitted:
247
  if title and description:
@@ -260,10 +260,10 @@ elif page == "✍️ Submit Wisdom":
260
  entry = {
261
  'id': len(st.session_state.entries) + 1, 'title': title, 'description': description,
262
  'language': language, 'category': category, 'location_name': location_name,
263
- 'latitude': manual_lat if manual_lat != 0.0 else None,
264
- 'longitude': manual_lon if manual_lon != 0.0 else None,
265
  'image_path': image_path, 'audio_path': audio_path,
266
- 'timestamp': datetime.datetime.now().isoformat(),
267
  'contributor': st.session_state.username,
268
  'contributor_full_name': user_info.get('full_name', st.session_state.username)
269
  }
@@ -271,15 +271,12 @@ elif page == "✍️ Submit Wisdom":
271
  if save_entry(entry):
272
  st.session_state.entries.append(entry)
273
  update_user_entry_count(st.session_state.username)
274
- st.success("Farming wisdom submitted successfully!")
275
- # Clear form data from session state
276
  st.session_state.pop('form_data', None)
277
  else:
278
  st.error("Failed to save entry. Please try again.")
279
  else:
280
- st.error("Please fill in all required fields marked with * in the 'Content' tab.")
281
-
282
- # All other pages remain unchanged from the previous version...
283
 
284
  # --- Browse Knowledge Page ---
285
  elif page == "πŸ“– Browse Knowledge":
@@ -427,7 +424,7 @@ elif page == "πŸ“Š Export Data":
427
  if not filtered_entries:
428
  st.warning("No entries match the selected filters.")
429
  else:
430
- timestamp = datetime.datetime.now().strftime('%Y%m%d')
431
  if export_format == "CSV":
432
  export_data = export_to_csv(filtered_entries, True, True)
433
  st.download_button(
@@ -480,4 +477,4 @@ elif page == "πŸ‘€ Profile":
480
 
481
  # --- Footer ---
482
  st.sidebar.markdown("---")
483
- st.sidebar.info("🌾 **Farming Wisdom Archive v1.1**")
 
39
  col1, col2 = st.columns([1, 1])
40
 
41
  with col1:
 
42
  st.image("https://images.pexels.com/photos/265216/pexels-photo-265216.jpeg",
43
  caption="Photo by Pixabay", use_container_width=True)
44
  st.markdown("""
 
110
  st.session_state.username = None
111
  st.rerun()
112
 
113
+ # --- NAVIGATION LOGIC ---
114
  st.sidebar.title("Navigation")
115
+ # NEW: Define a callback function to change pages
116
+ def set_page(page_name):
117
+ st.session_state.page_selection = page_name
118
+
119
+ page_options = [
120
+ "🏠 Home", "✍️ Submit Wisdom", "πŸ“– Browse Knowledge",
121
+ "πŸ—ΊοΈ Knowledge Map", "πŸ” Search", "🌐 Translation Hub",
122
+ "πŸ“Š Export Data", "πŸ‘€ Profile"
123
+ ]
124
+ page = st.sidebar.radio(
125
+ "Go to",
126
+ page_options,
127
+ key="page_selection", # NEW: Assign a key to the radio button
128
+ label_visibility="collapsed"
129
+ )
130
 
131
  # --- Home Page ---
132
  if page == "🏠 Home":
 
147
  st.markdown("### πŸš€ Getting Started")
148
  gs_cols = st.columns(3)
149
  with gs_cols[0]:
150
+ with st.container(border=True, height=180):
151
  st.markdown("#### ✍️ Share Knowledge")
152
+ st.markdown("Contribute your traditional farming knowledge to the archive.")
153
+ # NEW: Clickable button to navigate
154
+ st.button("Share Now", on_click=set_page, args=("✍️ Submit Wisdom",), use_container_width=True)
155
  with gs_cols[1]:
156
+ with st.container(border=True, height=180):
157
  st.markdown("#### πŸ“– Explore Entries")
158
+ st.markdown("Explore wisdom shared by farmers from all across India.")
159
+ st.button("Explore Now", on_click=set_page, args=("πŸ“– Browse Knowledge",), use_container_width=True)
160
  with gs_cols[2]:
161
+ with st.container(border=True, height=180):
162
  st.markdown("#### πŸ—ΊοΈ Discover on Map")
163
+ st.markdown("Find location-specific farming practices on our interactive map.")
164
+ st.button("View Map", on_click=set_page, args=("πŸ—ΊοΈ Knowledge Map",), use_container_width=True)
165
 
166
+ # --- Submit Wisdom Page (LOGICALLY REDESIGNED WITH EXPANDERS) ---
167
  elif page == "✍️ Submit Wisdom":
168
+ st.header("✍️ Submit New Farming Wisdom")
169
+ st.markdown("Follow the steps below to contribute. Fields marked with `*` are required.")
170
 
171
  if 'form_data' not in st.session_state:
172
  st.session_state.form_data = {
173
+ 'title': '', 'description': '', 'language': 'English', 'category': 'Other Farming Practices',
174
+ 'location_name': '', 'manual_lat': 20.5937, 'manual_lon': 78.9629
 
175
  }
176
 
177
+ # Helper Tools remain outside the form
178
+ st.subheader("Step 1: Use Helper Tools (Optional)")
179
  with st.container(border=True):
180
+ st.markdown("**Pin a Location on the Map**")
 
181
  geocode_cols = st.columns([3, 1])
182
+ geocode_input = geocode_cols[0].text_input("Search for a place to pin on the map", label_visibility="collapsed", placeholder="e.g., Hyderabad, Telangana")
183
+ if geocode_cols[1].button("πŸ“ Find Location", use_container_width=True):
184
  if geocode_input:
185
  coords = geocode_location(geocode_input)
186
  if coords:
 
188
  st.success(f"Found and pinned: {geocode_input}")
189
  else:
190
  st.error(f"Could not find coordinates for '{geocode_input}'")
191
+
192
+ st.markdown("---")
193
+ st.markdown("**Record Description with Voice**")
194
  speech_cols = st.columns([3, 1])
195
  speech_language = speech_cols[0].selectbox("Language for Speech Recognition", get_languages(), key="speech_lang")
196
+ if speech_cols[1].button("🎀 Record Audio", use_container_width=True):
197
  with st.spinner("Listening..."):
198
  recorded_text = speech_to_text(speech_language)
199
  if recorded_text:
200
  st.session_state.form_data['description'] = recorded_text
201
+ st.success(f"Text successfully recorded!")
202
+ st.rerun()
203
  else:
204
+ st.error("Could not record speech.")
205
 
206
  st.markdown("---")
207
 
208
+ # NEW: The form now uses an accordion-style layout with expanders
209
+ st.subheader("Step 2: Complete and Submit the Form")
210
  with st.form("entry_form", clear_on_submit=True):
211
+ with st.expander("**Part 1: Essential Information**", expanded=True):
212
+ st.caption("This is the core of your submission. Describe the farming wisdom clearly.")
213
+ title = st.text_input("Title*", value=st.session_state.form_data.get('title', ''), placeholder="e.g., Natural Pest Repellent using Neem Leaves")
214
+ description = st.text_area("Description*", value=st.session_state.form_data.get('description', ''), height=250, placeholder="Describe the wisdom, practice, or story in detail...")
 
 
 
215
 
216
  col1, col2 = st.columns(2)
217
+ category = col1.selectbox("Category*", get_categories(), index=get_categories().index(st.session_state.form_data.get('category', 'Other Farming Practices')))
218
+ language = col2.selectbox("Language of this Entry*", get_languages(), index=get_languages().index(st.session_state.form_data.get('language', 'English')))
219
+
220
+ with st.expander("**Part 2: Geographic Context**"):
221
+ st.caption("Specify where this knowledge comes from. Use the helper tool above to search, or click the map to fine-tune.")
222
+ location_name = st.text_input("Location Name (e.g., Village, District, State)", value=st.session_state.form_data.get('location_name', ''))
223
 
 
 
 
 
 
224
  map_center = [st.session_state.form_data['manual_lat'], st.session_state.form_data['manual_lon']]
225
+ m = folium.Map(location=map_center, zoom_start=7)
226
+ folium.Marker(map_center, popup="Your Selected Location", tooltip="Current Location").add_to(m)
227
  map_data = st_folium(m, width=700, height=400)
228
 
229
  if map_data and map_data['last_clicked']:
230
  st.session_state.form_data['manual_lat'] = map_data['last_clicked']['lat']
231
  st.session_state.form_data['manual_lon'] = map_data['last_clicked']['lng']
232
+ st.rerun()
 
 
 
 
233
 
234
+ loc_cols = st.columns(2)
235
+ manual_lat = loc_cols[0].text_input("Latitude (Set by Map)", value=f"{st.session_state.form_data['manual_lat']:.6f}", disabled=True)
236
+ manual_lon = loc_cols[1].text_input("Longitude (Set by Map)", value=f"{st.session_state.form_data['manual_lon']:.6f}", disabled=True)
237
+
238
+ with st.expander("**Part 3: Supporting Media (Optional)**"):
239
+ st.caption("Upload an image or a pre-recorded audio file that relates to this wisdom.")
240
  uploaded_image = st.file_uploader("Upload an Image", type=['jpg', 'jpeg', 'png'])
241
  uploaded_audio = st.file_uploader("Upload an Audio Recording", type=['mp3', 'wav', 'ogg'])
242
 
 
243
  st.markdown("---")
244
+ submitted = st.form_submit_button("βœ… Submit My Contribution", type="primary", use_container_width=True)
245
 
246
  if submitted:
247
  if title and description:
 
260
  entry = {
261
  'id': len(st.session_state.entries) + 1, 'title': title, 'description': description,
262
  'language': language, 'category': category, 'location_name': location_name,
263
+ 'latitude': st.session_state.form_data['manual_lat'],
264
+ 'longitude': st.session_state.form_data['manual_lon'],
265
  'image_path': image_path, 'audio_path': audio_path,
266
+ 'timestamp': datetime.datetime.now(datetime.timezone.utc).isoformat(),
267
  'contributor': st.session_state.username,
268
  'contributor_full_name': user_info.get('full_name', st.session_state.username)
269
  }
 
271
  if save_entry(entry):
272
  st.session_state.entries.append(entry)
273
  update_user_entry_count(st.session_state.username)
274
+ st.success("Farming wisdom submitted successfully! Thank you.")
 
275
  st.session_state.pop('form_data', None)
276
  else:
277
  st.error("Failed to save entry. Please try again.")
278
  else:
279
+ st.error("Please fill in the required fields: Title and Description.")
 
 
280
 
281
  # --- Browse Knowledge Page ---
282
  elif page == "πŸ“– Browse Knowledge":
 
424
  if not filtered_entries:
425
  st.warning("No entries match the selected filters.")
426
  else:
427
+ timestamp = datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%d')
428
  if export_format == "CSV":
429
  export_data = export_to_csv(filtered_entries, True, True)
430
  st.download_button(
 
477
 
478
  # --- Footer ---
479
  st.sidebar.markdown("---")
480
+ st.sidebar.info("🌾 **Farming Wisdom Archive v1.4**")