File size: 37,329 Bytes
1371df5 46b30d5 1371df5 debd75a 46b30d5 1371df5 46b30d5 1371df5 46b30d5 1371df5 46b30d5 1371df5 46b30d5 1371df5 debd75a 1371df5 46b30d5 1371df5 46b30d5 1371df5 46b30d5 1371df5 46b30d5 1371df5 46b30d5 1371df5 46b30d5 1371df5 46b30d5 1371df5 46b30d5 1371df5 46b30d5 1371df5 46b30d5 1371df5 46b30d5 1371df5 46b30d5 1371df5 46b30d5 1371df5 46b30d5 1371df5 46b30d5 1371df5 46b30d5 debd75a 46b30d5 1371df5 46b30d5 1371df5 46b30d5 1371df5 46b30d5 1371df5 46b30d5 1371df5 46b30d5 1371df5 46b30d5 1371df5 46b30d5 1371df5 46b30d5 1371df5 46b30d5 1371df5 46b30d5 1371df5 46b30d5 debd75a 46b30d5 debd75a 1371df5 46b30d5 1371df5 46b30d5 1371df5 46b30d5 1371df5 46b30d5 1371df5 46b30d5 1371df5 46b30d5 1371df5 46b30d5 1371df5 46b30d5 1371df5 46b30d5 1371df5 46b30d5 1371df5 46b30d5 1371df5 46b30d5 debd75a 46b30d5 debd75a | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 | import json
import os
import datetime
import pandas as pd
import streamlit as st
from typing import List, Dict, Optional
import bcrypt
from deep_translator import GoogleTranslator
from gtts import gTTS
import speech_recognition as sr
from geopy.geocoders import Nominatim
import tempfile
# --- NEW: UI Text Translations ---
UI_TRANSLATIONS = {
"English": {
"app_title": "Farming Wisdom Archive",
"app_tagline": "Preserving Traditional Indian Farming Knowledge for Future Generations",
"about_platform_header": "About This Platform",
"about_platform_text": "This archive is a community-driven effort to document and share the rich, time-tested farming practices of India. By contributing, you help create a valuable open-source corpus for agricultural research and AI.",
"login_tab": "Login",
"register_tab": "Register",
"login_subheader": "Login to Your Account",
"username_label": "Username",
"password_label": "Password",
"login_button": "Login",
"login_success": "Login successful!",
"invalid_credentials": "Invalid username or password",
"enter_credentials": "Please enter both username and password",
"register_subheader": "Join Our Community",
"full_name_label": "Full Name",
"email_label": "Email",
"choose_username_label": "Choose Username",
"choose_password_label": "Choose Password",
"confirm_password_label": "Confirm Password",
"register_button": "Register",
"registration_success": "Registration successful! Please login.",
"registration_failed": "Username or Email may already exist.",
"passwords_no_match": "Passwords do not match",
"fill_all_fields": "Please fill in all fields",
"welcome_message": "Welcome",
"entries_submitted": "Entries Submitted",
"logout_button": "Logout",
"navigation_header": "Navigation",
"home_page": "🏠 Home",
"submit_page": "✍️ Submit Wisdom",
"browse_page": "📖 Browse Knowledge",
"map_page": "🗺️ Knowledge Map",
"search_page": "🔍 Search",
"translate_page": "🌐 Translation Hub",
"export_page": "📊 Export Data",
"profile_page": "👤 Profile",
"home_header": "🏠 Home Dashboard",
"stats_header": "📊 Archive Statistics",
"total_entries_metric": "Total Farming Entries",
"languages_metric": "Languages Represented",
"categories_metric": "Farming Categories",
"getting_started_header": "🚀 Getting Started",
"share_knowledge_card_header": "✍️ Share Knowledge",
"share_knowledge_card_text": "Contribute your traditional farming knowledge to the archive.",
"share_now_button": "Share Now",
"explore_entries_card_header": "📖 Explore Entries",
"explore_entries_card_text": "Explore wisdom shared by farmers from all across India.",
"explore_now_button": "Explore Now",
"discover_map_card_header": "🗺️ Discover on Map",
"discover_map_card_text": "Find location-specific farming practices on our interactive map.",
"view_map_button": "View Map",
"submit_header": "✍️ Submit New Farming Wisdom",
"submit_tagline": "Follow the steps below to contribute. Fields marked with `*` are required.",
"step1_header": "Step 1: Use Helper Tools (Optional)",
"pin_location_header": "**Pin a Location on the Map**",
"pin_location_caption": "Search for a location to automatically get its coordinates, which will update the map in the form below.",
"find_location_placeholder": "Search for a place (e.g., Hyderabad, Telangana)",
"find_location_button": "📍 Find Location",
"location_found_success": "Found and pinned: {location}",
"location_not_found_error": "Could not find coordinates for '{location}'",
"record_voice_header": "**Record Description with Voice**",
"record_voice_caption": "Select a language and press record. The transcribed text will appear in the 'Description' field below.",
"record_audio_button": "🎤 Record Audio",
"speech_recorded_success": "Text successfully recorded!",
"speech_record_error": "Could not record speech.",
"step2_header": "Step 2: Complete and Submit the Form",
"part1_header": "**Part 1: Essential Information**",
"part1_caption": "This is the core of your submission. Describe the farming wisdom clearly.",
"title_label": "Title*",
"title_placeholder": "e.g., Natural Pest Repellent using Neem Leaves",
"description_label": "Description*",
"description_placeholder": "Describe the wisdom, practice, or story in detail...",
"category_label": "Category*",
"language_entry_label": "Language of this Entry*",
"part2_header": "**Part 2: Geographic Context**",
"part2_caption": "Specify where this knowledge comes from. Use the helper tool above to search, or click the map to fine-tune.",
"location_name_label": "Location Name (e.g., Village, District, State)",
"latitude_label": "Latitude (Set by Map)",
"longitude_label": "Longitude (Set by Map)",
"part3_header": "**Part 3: Supporting Media (Optional)**",
"part3_caption": "Upload an image or a pre-recorded audio file that relates to this wisdom.",
"image_upload_label": "Upload an Image",
"audio_upload_label": "Upload an Audio Recording",
"submit_contribution_button": "✅ Submit My Contribution",
"submit_success": "Farming wisdom submitted successfully! Thank you.",
"submit_failed": "Failed to save entry. Please try again.",
"submit_validation_error": "Please fill in the required fields: Title and Description.",
"browse_header": "📖 Browse Farming Knowledge",
"browse_tagline": "Explore wisdom shared by the community. Use the filters to narrow your search.",
"filter_lang_label": "Filter by Language",
"filter_cat_label": "Filter by Category",
"sort_by_label": "Sort by",
"all_option": "All",
"newest_first_option": "Newest First",
"oldest_first_option": "Oldest First",
"title_az_option": "Title A-Z",
"showing_entries": "**Showing {count} of {total} entries**",
"category_display": "**Category:** {category}",
"language_display": "**Language:** {language}",
"location_display": "**Location:** {location}",
"submitted_display": "**Submitted:** {date}",
"view_details_expander": "View Details and Media",
"description_display": "**Description:**",
"listen_button": "🔊 Listen to Description",
"image_caption": "Attached Image",
"coords_display": "**Coords:** `{lat}, {lon}`",
"map_header": "🗺️ Farming Wisdom Map",
"map_tagline": "Explore traditional farming knowledge geographically. Click on a marker to see details.",
"map_popup_category": "Category:",
"map_popup_language": "Language:",
"map_info": "Showing {count} entries with location data on the map.",
"map_warning": "No entries with location data found. Submit entries with coordinates to see them on the map!",
"search_header": "🔍 Search Knowledge",
"search_tagline": "Use the search bar and filters to find specific farming techniques and wisdom.",
"search_placeholder": "🔎 Search for farming practices...",
"advanced_filters_expander": "Advanced Filters",
"has_media_checkbox": "Has Media (Image/Audio)",
"has_location_checkbox": "Has Location Data",
"search_results_header": "--- \n ### Found {count} results for '{query}'",
"translation_hub_header": "🌐 Translation Hub",
"translation_hub_tagline": "Translate farming knowledge between different Indian languages.",
"original_text_header": "Original Text",
"source_language_label": "Source Language",
"text_to_translate_label": "Text to translate",
"text_to_translate_placeholder": "Enter text here...",
"translated_text_header": "Translated Text",
"target_language_label": "Translate to",
"translate_button": "🌐 Translate",
"translation_output_label": "Translation",
"export_header": "📊 Export Data",
"export_tagline": "Export collected farming wisdom for research and analysis.",
"export_config_header": "Export Configuration",
"format_label": "Select Format",
"generate_export_button": "Generate Export File",
"export_no_match_warning": "No entries match the selected filters.",
"export_download_csv_button": "📥 Download CSV",
"export_download_jsonl_button": "📥 Download JSONL",
"export_ready_success": "Export file ready for {count} entries.",
"profile_header": "👤 User Profile: {name}",
"my_info_tab": "ℹ️ My Info",
"my_contributions_tab": "📜 My Contributions",
"settings_tab": "⚙️ Settings",
"profile_info_header": "Profile Information",
"full_name_display": "**Full Name:**\n\n`{name}`",
"username_display": "**Username:**\n\n`{username}`",
"email_display": "**Email:**\n\n`{email}`",
"member_since_display": "**Member Since:**\n\n`{date}`",
"total_entries_metric_profile": "Total Entries Submitted",
"my_recent_contributions_header": "My Recent Contributions",
"contributions_count_message": "You have contributed **{count}** farming knowledge entries. Here are the latest 5:",
"no_contributions_message": "You haven't submitted any entries yet. Go to the 'Submit Wisdom' page to share your knowledge!",
"account_prefs_header": "Account Preferences",
"preferred_language_label": "Preferred Language (for display)",
"email_notifications_checkbox": "Enable email notifications for new entries",
"update_profile_button": "Update Profile",
"profile_update_success": "Profile settings updated successfully! (Note: Feature is illustrative)",
"app_version_footer": "🌾 **Farming Wisdom Archive v1.1**",
"language_select_label": "Select Language"
},
"Hindi": {
"app_title": "कृषि ज्ञान पुरालेख",
"app_tagline": "आने वाली पीढ़ियों के लिए पारंपरिक भारतीय कृषि ज्ञान का संरक्षण",
"about_platform_header": "इस प्लेटफ़ॉर्म के बारे में",
"about_platform_text": "यह पुरालेख भारत की समृद्ध, समय-परीक्षित कृषि पद्धतियों का दस्तावेजीकरण और साझा करने का एक सामुदायिक प्रयास है। योगदान करके, आप कृषि अनुसंधान और एआई के लिए एक मूल्यवान ओपन-सोर्स कॉर्पस बनाने में मदद करते हैं।",
"login_tab": "लॉग इन करें",
"register_tab": "पंजीकरण करें",
"login_subheader": "अपने खाते में लॉग इन करें",
"username_label": "उपयोगकर्ता नाम",
"password_label": "पासवर्ड",
"login_button": "लॉग इन करें",
"login_success": "लॉगिन सफल!",
"invalid_credentials": "अमान्य उपयोगकर्ता नाम या पासवर्ड",
"enter_credentials": "कृपया उपयोगकर्ता नाम और पासवर्ड दोनों दर्ज करें",
"register_subheader": "हमारे समुदाय में शामिल हों",
"full_name_label": "पूरा नाम",
"email_label": "ईमेल",
"choose_username_label": "उपयोगकर्ता नाम चुनें",
"choose_password_label": "पासवर्ड चुनें",
"confirm_password_label": "पासवर्ड की पुष्टि करें",
"register_button": "पंजीकरण करें",
"registration_success": "पंजीकरण सफल! कृपया लॉग इन करें।",
"registration_failed": "उपयोगकर्ता नाम या ईमेल पहले से मौजूद हो सकता है।",
"passwords_no_match": "पासवर्ड मेल नहीं खाते",
"fill_all_fields": "कृपया सभी फ़ील्ड भरें",
"welcome_message": "स्वागत है",
"entries_submitted": "प्रविष्टियाँ प्रस्तुत की गईं",
"logout_button": "लॉग आउट",
"navigation_header": "नेविगेशन",
"home_page": "🏠 होम",
"submit_page": "✍️ ज्ञान प्रस्तुत करें",
"browse_page": "📖 ज्ञान ब्राउज़ करें",
"map_page": "🗺️ ज्ञान मानचित्र",
"search_page": "🔍 खोजें",
"translate_page": "🌐 अनुवाद हब",
"export_page": "📊 डेटा निर्यात करें",
"profile_page": "👤 प्रोफ़ाइल",
"home_header": "🏠 होम डैशबोर्ड",
"stats_header": "📊 पुरालेख सांख्यिकी",
"total_entries_metric": "कुल कृषि प्रविष्टियाँ",
"languages_metric": "प्रतिनिधित्व वाली भाषाएँ",
"categories_metric": "कृषि श्रेणियाँ",
"getting_started_header": "🚀 शुरुआत कैसे करें",
"share_knowledge_card_header": "✍️ ज्ञान साझा करें",
"share_knowledge_card_text": "पुरालेख में अपने पारंपरिक कृषि ज्ञान का योगदान करें।",
"share_now_button": "अभी साझा करें",
"explore_entries_card_header": "📖 प्रविष्टियाँ देखें",
"explore_entries_card_text": "पूरे भारत के किसानों द्वारा साझा किए गए ज्ञान का अन्वेषण करें।",
"explore_now_button": "अभी अन्वेषण करें",
"discover_map_card_header": "🗺️ मानचित्र पर खोजें",
"discover_map_card_text": "हमारे इंटरेक्टिव मानचित्र पर स्थान-विशिष्ट कृषि पद्धतियों का पता लगाएं।",
"view_map_button": "मानचित्र देखें",
"submit_header": "✍️ नई कृषि विशेषज्ञता प्रस्तुत करें",
"submit_tagline": "योगदान करने के लिए नीचे दिए गए चरणों का पालन करें। `*` से चिह्नित फ़ील्ड आवश्यक हैं।",
"step1_header": "चरण 1: सहायक उपकरणों का उपयोग करें (वैकल्पिक)",
"pin_location_header": "**मानचित्र पर एक स्थान पिन करें**",
"pin_location_caption": "किसी स्थान के निर्देशांक स्वचालित रूप से प्राप्त करने के लिए खोजें, जो नीचे दिए गए फॉर्म में मानचित्र को अपडेट करेगा।",
"find_location_placeholder": "एक जगह खोजें (जैसे, हैदराबाद, तेलंगाना)",
"find_location_button": "📍 स्थान खोजें",
"location_found_success": "मिल गया और पिन किया गया: {location}",
"location_not_found_error": "'{location}' के लिए निर्देशांक नहीं मिल सके",
"record_voice_header": "**आवाज के साथ विवरण रिकॉर्ड करें**",
"record_voice_caption": "एक भाषा चुनें और रिकॉर्ड दबाएं। लिखित पाठ नीचे 'विवरण' फ़ील्ड में दिखाई देगा।",
"record_audio_button": "🎤 ऑडियो रिकॉर्ड करें",
"speech_recorded_success": "पाठ सफलतापूर्वक रिकॉर्ड किया गया!",
"speech_record_error": "भाषण रिकॉर्ड नहीं किया जा सका।",
"step2_header": "चरण 2: फ़ॉर्म को पूरा करें और सबमिट करें",
"part1_header": "**भाग 1: आवश्यक जानकारी**",
"part1_caption": "यह आपके सबमिशन का मूल है। कृषि ज्ञान का स्पष्ट रूप से वर्णन करें।",
"title_label": "शीर्षक*",
"title_placeholder": "उदा., नीम के पत्तों का उपयोग करके प्राकृतिक कीट विकर्षक",
"description_label": "विवरण*",
"description_placeholder": "ज्ञान, अभ्यास, या कहानी का विस्तार से वर्णन करें...",
"category_label": "श्रेणी*",
"language_entry_label": "इस प्रविष्टि की भाषा*",
"part2_header": "**भाग 2: भौगोलिक संदर्भ**",
"part2_caption": "बताएं कि यह ज्ञान कहां से आता है। खोजने के लिए ऊपर दिए गए सहायक उपकरण का उपयोग करें, या पिन की स्थिति को ठीक करने के लिए मानचित्र पर क्लिक करें।",
"location_name_label": "स्थान का नाम (उदा., गाँव, जिला, राज्य)",
"latitude_label": "अक्षांश (मानचित्र द्वारा निर्धारित)",
"longitude_label": "देशांतर (मानचित्र द्वारा निर्धारित)",
"part3_header": "**भाग 3: सहायक मीडिया (वैकल्पिक)**",
"part3_caption": "एक छवि या पहले से रिकॉर्ड की गई ऑडियो फ़ाइल अपलोड करें जो इस ज्ञान से संबंधित हो।",
"image_upload_label": "एक छवि अपलोड करें",
"audio_upload_label": "एक ऑडियो रिकॉर्डिंग अपलोड करें",
"submit_contribution_button": "✅ मेरा योगदान जमा करें",
"submit_success": "कृषि ज्ञान सफलतापूर्वक प्रस्तुत किया गया! धन्यवाद।",
"submit_failed": "प्रविष्टि सहेजने में विफल। कृपया पुन: प्रयास करें।",
"submit_validation_error": "कृपया आवश्यक फ़ील्ड भरें: शीर्षक और विवरण।",
"browse_header": "📖 कृषि ज्ञान ब्राउज़ करें",
"browse_tagline": "समुदाय द्वारा साझा किए गए ज्ञान का अन्वेषण करें। अपनी खोज को सीमित करने के लिए फ़िल्टर का उपयोग करें।",
"filter_lang_label": "भाषा के अनुसार फ़िल्टर करें",
"filter_cat_label": "श्रेणी के अनुसार फ़िल्टर करें",
"sort_by_label": "इसके अनुसार क्रमबद्ध करें",
"all_option": "सभी",
"newest_first_option": "नवीनतम पहले",
"oldest_first_option": "सबसे पुराना पहले",
"title_az_option": "शीर्षक A-Z",
"showing_entries": "**{total} में से {count} प्रविष्टियाँ दिखा रहा है**",
"category_display": "**श्रेणी:** {category}",
"language_display": "**भाषा:** {language}",
"location_display": "**स्थान:** {location}",
"submitted_display": "**प्रस्तुत:** {date}",
"view_details_expander": "विवरण और मीडिया देखें",
"description_display": "**विवरण:**",
"listen_button": "🔊 विवरण सुनें",
"image_caption": "संलग्न छवि",
"coords_display": "**निर्देशांक:** `{lat}, {lon}`",
"map_header": "🗺️ कृषि ज्ञान मानचित्र",
"map_tagline": "भौगोलिक रूप से पारंपरिक कृषि ज्ञान का अन्वेषण करें। विवरण देखने के लिए एक मार्कर पर क्लिक करें।",
"map_popup_category": "श्रेणी:",
"map_popup_language": "भाषा:",
"map_info": "मानचित्र पर स्थान डेटा के साथ {count} प्रविष्टियाँ दिखा रहा है।",
"map_warning": "स्थान डेटा के साथ कोई प्रविष्टि नहीं मिली। उन्हें मानचित्र पर देखने के लिए निर्देशांक के साथ प्रविष्टियाँ जमा करें!",
"search_header": "🔍 ज्ञान खोजें",
"search_tagline": "विशिष्ट कृषि तकनीकों और ज्ञान को खोजने के लिए खोज बार और फ़िल्टर का उपयोग करें।",
"search_placeholder": "🔎 कृषि पद्धतियों के लिए खोजें...",
"advanced_filters_expander": "उन्नत फ़िल्टर",
"has_media_checkbox": "मीडिया है (छवि/ऑडियो)",
"has_location_checkbox": "स्थान डेटा है",
"search_results_header": "--- \n ### '{query}' के लिए {count} परिणाम मिले",
"translation_hub_header": "🌐 अनुवाद हब",
"translation_hub_tagline": "विभिन्न भारतीय भाषाओं के बीच कृषि ज्ञान का अनुवाद करें।",
"original_text_header": "मूल पाठ",
"source_language_label": "स्रोत भाषा",
"text_to_translate_label": "अनुवाद करने के लिए पाठ",
"text_to_translate_placeholder": "यहां पाठ दर्ज करें...",
"translated_text_header": "अनुवादित पाठ",
"target_language_label": "इसमें अनुवाद करें",
"translate_button": "🌐 अनुवाद करें",
"translation_output_label": "अनुवाद",
"export_header": "📊 डेटा निर्यात करें",
"export_tagline": "अनुसंधान और विश्लेषण के लिए एकत्रित कृषि ज्ञान का निर्यात करें।",
"export_config_header": "निर्यात कॉन्फ़िगरेशन",
"format_label": "प्रारूप चुनें",
"generate_export_button": "निर्यात फ़ाइल उत्पन्न करें",
"export_no_match_warning": "चयनित फ़िल्टर से कोई प्रविष्टि मेल नहीं खाती।",
"export_download_csv_button": "📥 CSV डाउनलोड करें",
"export_download_jsonl_button": "📥 JSONL डाउनलोड करें",
"export_ready_success": "{count} प्रविष्टियों के लिए निर्यात फ़ाइल तैयार है।",
"profile_header": "👤 उपयोगकर्ता प्रोफ़ाइल: {name}",
"my_info_tab": "ℹ️ मेरी जानकारी",
"my_contributions_tab": "📜 मेरे योगदान",
"settings_tab": "⚙️ सेटिंग्स",
"profile_info_header": "प्रोफ़ाइल जानकारी",
"full_name_display": "**पूरा नाम:**\n\n`{name}`",
"username_display": "**उपयोगकर्ता नाम:**\n\n`{username}`",
"email_display": "**ईमेल:**\n\n`{email}`",
"member_since_display": "**सदस्य जब से:**\n\n`{date}`",
"total_entries_metric_profile": "कुल प्रविष्टियाँ प्रस्तुत की गईं",
"my_recent_contributions_header": "मेरे हाल के योगदान",
"contributions_count_message": "आपने **{count}** कृषि ज्ञान प्रविष्टियों का योगदान दिया है। यहाँ नवीनतम 5 हैं:",
"no_contributions_message": "आपने अभी तक कोई प्रविष्टि जमा नहीं की है। अपना ज्ञान साझा करने के लिए 'ज्ञान जमा करें' पृष्ठ पर जाएं!",
"account_prefs_header": "खाता प्राथमिकताएं",
"preferred_language_label": "पसंदीदा भाषा (प्रदर्शन के लिए)",
"email_notifications_checkbox": "नए प्रविष्टियों के लिए ईमेल सूचनाएं सक्षम करें",
"update_profile_button": "प्रोफ़ाइल अपडेट करें",
"profile_update_success": "प्रोफ़ाइल सेटिंग्स सफलतापूर्वक अपडेट की गईं! (नोट: सुविधा उदाहरणात्मक है)",
"app_version_footer": "🌾 **कृषि ज्ञान पुरालेख v1.1**",
"language_select_label": "भाषा चुनें"
}
}
# --- NEW: UI Text Retriever Function ---
def get_ui_text(key, lang="English"):
"""
Retrieves UI text from the translations dictionary.
Defaults to English if a key is not found in the target language.
"""
return UI_TRANSLATIONS.get(lang, UI_TRANSLATIONS["English"]).get(key, UI_TRANSLATIONS["English"].get(key, key))
# --- Data Storage Functions ---
def load_entries() -> List[Dict]:
"""Load entries from JSON file."""
try:
os.makedirs("data_entries", exist_ok=True)
if os.path.exists("data_entries/entries.json"):
with open("data_entries/entries.json", "r", encoding="utf-8") as f:
return json.load(f)
return []
except Exception as e:
st.error(f"Error loading entries: {str(e)}")
return []
def save_entry(entry: Dict) -> bool:
"""Save a single entry by appending to the JSON file."""
try:
entries = load_entries()
entries.append(entry)
os.makedirs("data_entries", exist_ok=True)
with open("data_entries/entries.json", "w", encoding="utf-8") as f:
json.dump(entries, f, indent=4, ensure_ascii=False)
return True
except Exception as e:
st.error(f"Error saving entry: {str(e)}")
return False
# --- Category and Language Definitions ---
def get_categories() -> List[str]:
"""Get list of available categories."""
return [
"Seed Selection & Storage", "Soil Management", "Crop Rotation",
"Natural Fertilizers", "Pest Control", "Water Management",
"Harvest Techniques", "Seasonal Farming", "Traditional Tools",
"Weather Prediction", "Post-Harvest Processing", "Other"
]
def get_languages() -> List[str]:
"""Get list of supported languages for data entry."""
return [
"Hindi", "English", "Bengali", "Telugu", "Marathi", "Tamil",
"Gujarati", "Urdu", "Kannada", "Malayalam", "Oriya", "Other"
]
# --- Text-to-Speech & Speech-to-Text ---
def text_to_speech(text: str, language: str = "English") -> None:
"""Convert text to speech and play it in Streamlit."""
try:
lang_map = {
"English": "en", "Hindi": "hi", "Bengali": "bn", "Telugu": "te",
"Marathi": "mr", "Tamil": "ta", "Gujarati": "gu", "Urdu": "ur",
"Kannada": "kn", "Malayalam": "ml"
}
lang_code = lang_map.get(language, "en")
tts = gTTS(text=text, lang=lang_code, slow=False)
with tempfile.NamedTemporaryFile(delete=False, suffix=".mp3") as fp:
tts.save(fp.name)
st.audio(fp.name)
os.remove(fp.name) # Clean up the temp file
except Exception as e:
st.error(f"Error in text-to-speech: {str(e)}")
def speech_to_text(language: str = "English") -> Optional[str]:
"""Convert speech from microphone to text."""
lang_map = {
"English": "en-IN", "Hindi": "hi-IN", "Bengali": "bn-IN", "Telugu": "te-IN",
"Marathi": "mr-IN", "Tamil": "ta-IN", "Gujarati": "gu-IN", "Urdu": "ur-IN",
"Kannada": "kn-IN", "Malayalam": "ml-IN"
}
lang_code = lang_map.get(language, "en-IN")
r = sr.Recognizer()
try:
with sr.Microphone() as source:
st.info("Listening... Adjusting for ambient noise.")
r.adjust_for_ambient_noise(source, duration=1)
audio = r.listen(source)
st.info("Recognizing...")
text = r.recognize_google(audio, language=lang_code)
return text
except sr.UnknownValueError:
st.error("Could not understand audio.")
return None
except sr.RequestError as e:
st.error(f"Could not request results from speech recognition service; {e}")
return None
except Exception as e:
st.error(f"Mic error: {e}. Ensure microphone is enabled and permissions are granted.")
return None
# --- Geocoding & Search ---
def geocode_location(location_name: str) -> Optional[tuple]:
"""Get coordinates for a location name."""
try:
geolocator = Nominatim(user_agent="farming_wisdom_archive")
location = geolocator.geocode(location_name)
return (location.latitude, location.longitude) if location else None
except Exception as e:
st.error(f"Geocoding error: {e}")
return None
def search_entries(entries, query, language=None, category=None, has_media=False, has_location=False):
"""Search entries based on query and filters."""
query_lower = query.lower()
results = [
e for e in entries if query_lower in e.get('title', '').lower() or query_lower in e.get('description', '').lower()
]
if language and language != 'All': results = [e for e in results if e.get('language') == language]
if category and category != 'All': results = [e for e in results if e.get('category') == category]
if has_media: results = [e for e in results if e.get('image_path') or e.get('audio_path')]
if has_location: results = [e for e in results if e.get('latitude') and e.get('longitude')]
return results
# --- Data Export ---
def export_to_jsonl(entries, include_media, include_coords):
lines = []
for entry in entries:
data = entry.copy()
if not include_media: data.pop('image_path', None); data.pop('audio_path', None)
if not include_coords: data.pop('latitude', None); data.pop('longitude', None)
lines.append(json.dumps(data))
return "\n".join(lines)
def export_to_csv(entries, include_media, include_coords):
df = pd.DataFrame(entries)
if not include_media: df = df.drop(columns=['image_path', 'audio_path'], errors='ignore')
if not include_coords: df = df.drop(columns=['latitude', 'longitude'], errors='ignore')
return df.to_csv(index=False).encode('utf-8')
# --- User Authentication ---
def load_user_data() -> Dict:
"""Load user data from users.json."""
os.makedirs("data_entries", exist_ok=True)
users_file = "data_entries/users.json"
if not os.path.exists(users_file):
return {"users": {}}
try:
with open(users_file, "r", encoding="utf-8") as f:
return json.load(f)
except (json.JSONDecodeError, FileNotFoundError):
return {"users": {}}
def save_user_data(user_data: Dict) -> bool:
"""Save user data to users.json."""
try:
with open("data_entries/users.json", "w", encoding="utf-8") as f:
json.dump(user_data, f, indent=4)
return True
except Exception as e:
st.error(f"Error saving user data: {e}")
return False
def hash_password(password: str) -> bytes:
return bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt())
def verify_password(password: str, hashed: bytes) -> bool:
return bcrypt.checkpw(password.encode('utf-8'), hashed)
def register_user(username, email, password, full_name):
user_data = load_user_data()
if username in user_data['users']: return False
for user in user_data['users'].values():
if user['email'] == email:
return False
hashed_password = hash_password(password).decode('utf-8')
user_data['users'][username] = {
"email": email, "password": hashed_password, "full_name": full_name,
"registration_date": datetime.datetime.now(datetime.timezone.utc).isoformat(), "entries_submitted": 0
}
return save_user_data(user_data)
def authenticate_user(username, password):
user_data = load_user_data()
user_info = user_data['users'].get(username)
if not user_info: return False
return verify_password(password, user_info['password'].encode('utf-8'))
def get_user_info(username):
return load_user_data()['users'].get(username, {})
def update_user_entry_count(username):
user_data = load_user_data()
if username in user_data['users']:
user_data['users'][username]['entries_submitted'] += 1
save_user_data(user_data)
# --- Translation and Language Detection ---
def translate_text(text: str, target_lang: str, source_lang: str = "auto") -> str:
"""Translate text using deep_translator."""
lang_map = {
"Hindi": "hi", "English": "en", "Bengali": "bn", "Telugu": "te",
"Marathi": "mr", "Tamil": "ta", "Gujarati": "gu", "Urdu": "ur",
"Kannada": "kn", "Malayalam": "ml", "Oriya": "or"
}
target_code = lang_map.get(target_lang, "en")
source_code = lang_map.get(source_lang, "auto") if source_lang != "Auto-detect" else "auto"
try:
return GoogleTranslator(source=source_code, target=target_code).translate(text)
except Exception as e:
return f"Translation Error: {e}"
def detect_language(text: str) -> str:
"""Detect the language of the text."""
try:
code_map_rev = {
"hi": "Hindi", "en": "English", "bn": "Bengali", "te": "Telugu",
"mr": "Marathi", "ta": "Tamil", "gu": "Gujarati", "ur": "Urdu",
"kn": "Kannada", "ml": "Malayalam", "or": "Oriya"
}
detected_code = GoogleTranslator(source="auto", target="en").detect(text)
return code_map_rev.get(detected_code[0], f"Unknown ({detected_code[0]})")
except Exception:
return "Detection Error"
|