VSDatta's picture
Update app.py
9b3c226 verified
import streamlit as st
from datetime import datetime
from pymongo import MongoClient
import pandas as pd
from transformers import pipeline
# =============================================================================
# AI CLASSIFIER LOGIC
# =============================================================================
# Load the pipeline once using caching for efficiency
@st.cache_resource
def load_classifier():
"""Loads the zero-shot classification model."""
return pipeline(
"zero-shot-classification",
model="joeddav/xlm-roberta-large-xnli",
cache_dir="./hf_cache" # Prevents permission errors
)
classifier = load_classifier()
# Define the candidate labels
CATEGORIES = {
"Family": "కుటుంబం", "Friendship": "స్నేహం", "Morality": "నీతి",
"Hard Work": "శ్రమ", "Knowledge": "జ్ఞానం", "Devotion": "భక్తి",
"Culture": "సంస్కృతి", "Literature": "సాహిత్యం", "Humility": "వినయం",
"Patience": "సహనం", "Courage": "ధైర్యం", "Arrogance": "అహంకారం",
"Love": "ప్రేమ", "Greed": "దురాశ", "Wisdom": "ఆలోచన",
"Responsibility": "బాధ్యత", "Satire": "వ్యంగ్యం", "Politics": "రాజకీయం",
"Wealth": "ధనము", "Time": "సమయం"
}
def classify_proverb(text):
"""Classifies the proverb and returns the Telugu label."""
result = classifier(text, list(CATEGORIES.keys()))
top_label = result["labels"][0]
return CATEGORIES[top_label]
# =============================================================================
# DATABASE LOGIC
# =============================================================================
# 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):
"""Saves a new proverb to the database and clears the data cache."""
# This now calls the classify_proverb function defined above
category = classify_proverb(proverb + " " + meaning)
new_entry = {
"Proverb": proverb.strip(),
"Meaning": meaning.strip(),
"Category": category,
"Timestamp": datetime.now()
}
collection.insert_one(new_entry)
load_proverbs.clear()
# =============================================================================
# STREAMLIT UI & APP LOGIC
# =============================================================================
# --- Page Configuration ---
st.set_page_config(
page_title="తెలుగు సామెతల ఖజానా", page_icon="📜", layout="wide"
)
# --- Title & Introduction ---
st.title("📜 తెలుగు సామెతల ఖజానా")
st.markdown("### మీకు తెలిసిన సామెతను పంచుకోండి ✍️")
st.markdown("వెనుక తరాల నుంచి ముందుకు, మనం భద్రపరిద్దాం మన తెలుగు జ్ఞానం.")
st.markdown("<hr style='border:1px solid #555'>", unsafe_allow_html=True)
# --- Main Layout (Two Columns) ---
col1, col2 = st.columns([1, 2], gap="large")
# --- Column 1: Submission Form ---
with col1:
st.subheader("📥 కొత్త సామెతను జత చేయండి")
with st.form("proverb_form", clear_on_submit=True):
proverb = st.text_area("**సామెత (Proverb)**", height=100, max_chars=150)
meaning = st.text_area("**భావం (Meaning)**", height=100, max_chars=500)
submitted = st.form_submit_button("✅ సామెతను జత చేయండి", use_container_width=True, type="primary")
if submitted:
if proverb and meaning:
save_proverb(proverb, meaning)
st.success("ధన్యవాదాలు! మీ సామెత జత చేయబడింది.")
st.balloons()
else:
st.error("దయచేసి సామెత మరియు భావం రెండూ నమోదు చేయండి.")
# --- Column 2: Gallery Section ---
with col2:
st.subheader("🗂️ సామెతల గ్యాలరీ")
df = load_proverbs()
st.markdown(f"🔢 ఇప్పటివరకు మొత్తం **{len(df)}** సామెతలు జత చేయబడ్డాయి.")
if df.empty:
st.info("ఇప్పటి వరకు ఎలాంటి సామెతలు జత చేయలేదు. మీరే మొదటిది జత చేయండి!")
else:
for _, row in df.iterrows():
# This block safely handles both datetime objects and old string formats
timestamp_str = "N/A"
timestamp_val = row.get('Timestamp')
if isinstance(timestamp_val, datetime):
timestamp_str = timestamp_val.strftime('%d %B %Y, %I:%M %p')
elif timestamp_val:
try:
# Try to convert old string format to datetime
timestamp_obj = datetime.strptime(str(timestamp_val), '%Y-%m-%d %H:%M:%S')
timestamp_str = timestamp_obj.strftime('%d %B %Y, %I:%M %p')
except (ValueError, TypeError):
# If conversion fails, just show the original string
timestamp_str = str(timestamp_val)
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>
<span style='color:#bbb;'>🏷️ శ్రేణి: {row.get('Category', 'N/A')}</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)