gyanavedika / src /nano harsha4.py
GHarshasri's picture
Rename src/harsha4.py to src/nano harsha4.py
511d5ba verified
import streamlit as st
from PIL import Image
import os
import wikipedia
import requests
# ===== Session State Initialization =====
if "logged_in" not in st.session_state:
st.session_state.logged_in = False
if "email" not in st.session_state:
st.session_state.email = ""
# ===== Static Data =====
USERS = {}
UPLOAD_FOLDER = "uploads"
if not os.path.exists(UPLOAD_FOLDER):
os.makedirs(UPLOAD_FOLDER)
STATES = {
"Telangana": ["Hyderabad", "Warangal", "Nizamabad", "Karimnagar", "Khammam"],
"Maharashtra": ["Mumbai", "Pune", "Nagpur", "Nashik", "Aurangabad"],
"Tamil Nadu": ["Chennai", "Coimbatore", "Madurai", "Tiruchirappalli", "Salem"],
"Karnataka": ["Bangalore", "Mysore", "Mangalore", "Hubli", "Belgaum"],
"Uttar Pradesh": ["Lucknow", "Varanasi", "Agra", "Kanpur", "Allahabad"],
"West Bengal": ["Kolkata", "Darjeeling", "Durgapur", "Siliguri", "Asansol"],
"Rajasthan": ["Jaipur", "Udaipur", "Jodhpur", "Bikaner", "Ajmer"],
"Gujarat": ["Ahmedabad", "Surat", "Vadodara", "Rajkot", "Bhavnagar"],
"Andhra Pradesh": ["Visakhapatnam", "Vijayawada", "Guntur", "Tirupati", "Kurnool"],
}
# ===== Helper Functions =====
def save_uploaded_file(uploaded_file):
path = os.path.join(UPLOAD_FOLDER, uploaded_file.name)
with open(path, "wb") as f:
f.write(uploaded_file.getbuffer())
return path
def recognize_place(image_file):
name = image_file.name.lower()
keywords_map = {
"charminar": "Charminar",
"taj": "Taj Mahal",
"gateway": "Gateway of India",
"qutub": "Qutub Minar",
"mysore": "Mysore Palace",
"hampi": "Hampi",
"konark": "Konark Sun Temple",
"varanasi": "Varanasi",
"madurai": "Meenakshi Temple",
"ajanta": "Ajanta Caves",
"ellora": "Ellora Caves",
}
for kw, place in keywords_map.items():
if kw in name:
return place
return None
def fetch_wikipedia_summary(title, lang="en"):
try:
wikipedia.set_lang(lang)
summary = wikipedia.summary(title, sentences=4)
return summary
except wikipedia.exceptions.DisambiguationError as e:
return f"Multiple results found for '{title}': {e.options}"
except wikipedia.exceptions.PageError:
return f"No Wikipedia page found for '{title}' in selected language."
except Exception as e:
return f"Error fetching summary: {str(e)}"
# ===== Auth Pages =====
def signup():
st.header("πŸš€ Signup")
name = st.text_input("Name")
email = st.text_input("Email (Gmail)")
contact = st.text_input("Contact Number")
if st.button("Sign Up"):
if email in USERS:
st.error("User already exists, please login.")
return
USERS[email] = {"name": name, "email": email, "contact": contact}
st.success(f"User {name} registered! Please verify OTP sent to your email (simulated).")
st.session_state["otp_sent_to"] = email
st.session_state["otp_verified"] = False
def login():
st.header("πŸ” Login")
email = st.text_input("Email")
if st.button("Send OTP"):
if email in USERS:
st.session_state["otp_sent_to"] = email
st.session_state["otp_verified"] = False
st.info("OTP sent (simulated). Please enter OTP below.")
else:
st.error("Email not found. Please sign up first.")
def verify_otp():
st.header("πŸ”‘ OTP Verification")
otp = st.text_input("Enter OTP (use 1234 for demo)", type="password")
if st.button("Verify OTP"):
if otp == "1234" and st.session_state.get("otp_sent_to"):
st.session_state.logged_in = True
st.session_state.email = st.session_state["otp_sent_to"]
st.success("OTP verified! Logged in successfully.")
else:
st.error("Incorrect OTP or no OTP sent.")
def logout():
st.session_state.logged_in = False
st.session_state.email = ""
st.success("Logged out successfully.")
# ===== UI Styling =====
st.set_page_config(page_title="Gyana Vedika v2", layout="wide")
st.markdown("""
<style>
.stButton>button {background-color: #008080; color: white; font-weight: bold; border-radius:10px;}
.stTextInput>div>input, .stSelectbox>div>div>select, .stTextArea>div>textarea {
border: 2px solid #008080 !important; border-radius: 8px !important;
}
h1, h2, h3, h4, h5, h6 {
color: #004d4d;
}
</style>
""", unsafe_allow_html=True)
# ===== Main App Logic =====
if not st.session_state.logged_in:
page = st.sidebar.selectbox("Choose", ["Login", "Signup", "Verify OTP"])
if page == "Login":
login()
elif page == "Signup":
signup()
else:
verify_otp()
else:
st.sidebar.success(f"Logged in as {st.session_state.email}")
if st.sidebar.button("Logout"):
logout()
st.title("πŸ“š Gyana Vedika - Cultural Explorer v2")
state = st.selectbox("Select State", list(STATES.keys()))
district = st.selectbox("Select District", STATES[state])
st.subheader(f"Explore {district}, {state}")
uploaded_image = st.file_uploader("Upload an image of a cultural/historical place", type=["png", "jpg", "jpeg"])
recognized_place = None
if uploaded_image:
st.image(uploaded_image, caption="Uploaded Image", use_column_width=True)
recognized_place = recognize_place(uploaded_image)
if recognized_place:
st.success(f"Recognized Place: {recognized_place}")
else:
st.warning("Could not recognize place. Try renaming the image file with landmark name, e.g., charminar.jpg")
st.markdown("### Or manually enter place name to search info")
manual_place = st.text_input("Enter place name")
place_to_search = recognized_place or manual_place.strip()
if place_to_search:
language = st.selectbox("Select Wikipedia summary language", ["English", "Hindi", "Telugu", "Tamil", "Marathi", "Bengali"], key="lang2")
lang_codes = {"English": "en", "Hindi": "hi", "Telugu": "te", "Tamil": "ta", "Marathi": "mr", "Bengali": "bn"}
lang_code = lang_codes.get(language, "en")
with st.spinner(f"Fetching Wikipedia summary for {place_to_search} in {language}..."):
summary = fetch_wikipedia_summary(place_to_search, lang=lang_code)
st.markdown(f"### Summary of {place_to_search}")
st.write(summary)
st.markdown("---")
st.subheader("Feedback about this place")
feedback_text = st.text_area("Share your experience or info about this place")
uploaded_images = st.file_uploader("Upload Images", type=["png", "jpg", "jpeg"], accept_multiple_files=True, key="fb_images")
uploaded_audio = st.file_uploader("Upload Audio", type=["mp3", "wav"], accept_multiple_files=True, key="fb_audio")
uploaded_videos = st.file_uploader("Upload Videos", type=["mp4", "mov", "avi"], accept_multiple_files=True, key="fb_videos")
if st.button("Submit Feedback"):
feedback_folder = os.path.join(UPLOAD_FOLDER, "feedback")
if not os.path.exists(feedback_folder):
os.makedirs(feedback_folder)
saved_files = []
for file_list in [uploaded_images, uploaded_audio, uploaded_videos]:
if file_list:
for f in file_list:
path = save_uploaded_file(f)
saved_files.append(path)
st.success("Thank you for your feedback and uploads!")