VSDatta's picture
Update src/app.py
e49dd64 verified
import streamlit as st
from datetime import datetime
from ai_classifier import classify_proverb
from pymongo import MongoClient
import pandas as pd
# --- MongoDB Setup & Caching (Best Practice) ---
# Use @st.cache_resource to establish the database connection only once.
@st.cache_resource
def init_connection():
"""Initializes a connection to the MongoDB database."""
return MongoClient(st.secrets["MONGO_URI"])
client = init_connection()
collection = client["proverbs_and_meanings"]["proverbs"]
# Use @st.cache_data to load data only when it changes.
@st.cache_data
def load_proverbs():
"""Retrieves all proverbs, sorted by newest first."""
data = list(collection.find({}, {'_id': 0}).sort("Timestamp", -1))
return pd.DataFrame(data) if data else pd.DataFrame()
def save_proverb(proverb, meaning, context):
"""Saves a new proverb to the database and clears the data cache."""
text_for_classification = proverb + " " + meaning
category = classify_proverb(text_for_classification)
new_entry = {
"Proverb": proverb.strip(),
"Meaning": meaning.strip(),
"Context": context.strip(),
"Category": category,
"Timestamp": datetime.now() # Store as a native datetime object
}
collection.insert_one(new_entry)
# Clear the cache so the gallery updates immediately
load_proverbs.clear()
# --- Streamlit Page Configuration ---
st.set_page_config(
page_title="తెలుగు సామెతల ఖజానా",
page_icon="📜",
layout="centered"
)
# --- Title & Introduction ---
st.title("📜 తెలుగు సామెతల ఖజానా")
st.markdown("### మీకు తెలిసిన సామెతను పంచుకోండి ✍️")
st.markdown("వెనుక తరాల నుంచి ముందుకు, మనం భద్రపరిద్దాం మన తెలుగు జ్ఞానం.")
st.markdown("<hr style='border:1px solid #555'>", unsafe_allow_html=True)
# --- Form UI (Simplified) ---
# The `clear_on_submit=True` parameter handles clearing the form automatically.
with st.form("proverb_form", clear_on_submit=True):
st.subheader("📥 కొత్త సామెతను జత చేయండి")
proverb = st.text_area("**సామెత (Proverb)**", height=100, max_chars=150)
meaning = st.text_area("**భావం (Meaning)**", height=100, max_chars=500)
context = st.text_input("**సందర్భం (Context / Usage Example – Optional)**", max_chars=200)
submitted = st.form_submit_button("✅ సామెతను జత చేయండి", use_container_width=True, type="primary")
if submitted:
if proverb and meaning:
save_proverb(proverb, meaning, context)
st.success("ధన్యవాదాలు! మీ సామెత జత చేయబడింది.")
st.balloons()
else:
st.error("దయచేసి సామెత మరియు భావం రెండూ నమోదు చేయండి.")
# --- Gallery Section ---
df = load_proverbs()
st.markdown("---")
st.subheader("🗂️ సామెతల గ్యాలరీ")
st.markdown(f"🔢 ఇప్పటివరకు మొత్తం **{len(df)}** సామెతలు జత చేయబడ్డాయి.")
if df.empty:
st.info("ఇప్పటి వరకు ఎలాంటి సామెతలు జత చేయలేదు. మీరే మొదటిది జత చేయండి!")
else:
for _, row in df.iterrows():
# Format the timestamp for display
timestamp_str = row['Timestamp'].strftime('%d %B %Y, %I:%M %p')
st.markdown(f"""
<div style='border: 1px solid #444; padding: 15px; border-radius: 10px; margin-bottom: 15px; background-color: #0e1117;'>
<h5>📝 {row['Proverb']}</h5>
<b>భావం:</b> {row['Meaning']}<br>
<i>సందర్భం:</i> {row['Context'] or "—"}<br>
<span style='color:#bbb;'>🏷️ శ్రేణి: {row['Category']}</span><br>
<span style='font-size: 0.8em; color: gray;'>🕒 {timestamp_str}</span>
</div>
""", unsafe_allow_html=True)
# --- Footer ---
st.markdown("---")
st.markdown("<center><small>© తెలుగు సామెతల ఖజానా – viswam.ai</small></center>", unsafe_allow_html=True)