VSDatta commited on
Commit
e49dd64
·
verified ·
1 Parent(s): 0414efc

Update src/app.py

Browse files
Files changed (1) hide show
  1. src/app.py +104 -96
src/app.py CHANGED
@@ -1,96 +1,104 @@
1
- import streamlit as st
2
- from datetime import datetime
3
- from ai_classifier import classify_proverb
4
- from pymongo import MongoClient
5
- import pandas as pd
6
-
7
- # MongoDB setup
8
- client = MongoClient(st.secrets["mongo"]["uri"])
9
- collection = client["proverbs_and_meanings"]["proverbs"]
10
-
11
- # Load proverbs from MongoDB
12
- def load_proverbs():
13
- data = list(collection.find({}, {'_id': 0})) # exclude _id
14
- return pd.DataFrame(data) if data else pd.DataFrame(columns=["Proverb", "Meaning", "Context", "Category", "Timestamp"])
15
-
16
- # Save new proverb to MongoDB
17
- def save_proverb(proverb, meaning, context):
18
- text_for_classification = proverb + " " + meaning
19
- category = classify_proverb(text_for_classification)
20
- new_entry = {
21
- "Proverb": proverb.strip(),
22
- "Meaning": meaning.strip(),
23
- "Context": context.strip(),
24
- "Category": category,
25
- "Timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
26
- }
27
- collection.insert_one(new_entry)
28
-
29
- # Streamlit Page Config
30
- st.set_page_config(
31
- page_title="తెలుగు సామెతల ఖజానా",
32
- page_icon="📜",
33
- layout="centered"
34
- )
35
-
36
- # Title & Intro
37
- st.title("📜 తెలుగు సామెతల ఖజానా")
38
- st.markdown("### మీకు తెలిసిన సామెతను పంచుకోండి ✍️")
39
- st.markdown("వెనుక తరాల నుంచి ముందుకు, మనం భద్రపరిద్దాం మన తెలుగు జ్ఞానం.")
40
- st.markdown("<hr style='border:1px solid #555'>", unsafe_allow_html=True)
41
-
42
- # Clear form trigger (safe approach)
43
- if "clear_form" not in st.session_state:
44
- st.session_state.clear_form = False
45
-
46
- if st.session_state.clear_form:
47
- st.session_state.clear_form = False
48
- st.experimental_rerun()
49
-
50
- # Form UI
51
- with st.form("proverb_form"):
52
- st.subheader("📥 కొత్త సామెతను జత చేయండి")
53
-
54
- col1, col2 = st.columns(2)
55
- with col1:
56
- proverb = st.text_area("**సామెత (Proverb)**", max_chars=100, height=100)
57
- with col2:
58
- meaning = st.text_area("**భావం (Meaning)**", max_chars=300, height=100)
59
-
60
- context = st.text_input("**సందర్భం (Context / Usage Example – Optional)**", max_chars=150)
61
-
62
- centered_button = st.columns([2, 3, 2])
63
- with centered_button[1]:
64
- submitted = st.form_submit_button(" సామెతను జత చేయండి")
65
-
66
- if submitted:
67
- if proverb and meaning:
68
- save_proverb(proverb, meaning, context)
69
- st.success("ధన్యవాదాలు! మీ సామెత జత చేయబడింది.")
70
- st.balloons()
71
- st.session_state.clear_form = True
72
- else:
73
- st.error("దయచేసి సామెత మరియు భావం రెండూ నమోదు చేయండి.")
74
-
75
- # Gallery Section
76
- df = load_proverbs()
77
-
78
- st.subheader("🗂️ సామెతల గ్యాలరీ")
79
- st.markdown(f"🔢 ఇప్పటివరకు మొత్తం **{len(df)}** సామెతలు జత చేయబడ్డాయి.")
80
-
81
- if df.empty:
82
- st.info("ఇప్పటి వరకు ఎలాంటి సామెతలు జత చేయలేదు.")
83
- else:
84
- for _, row in df.iterrows():
85
- st.markdown(f"""
86
- <div style='border: 1px solid #444; padding: 10px; border-radius: 10px; margin-bottom: 10px; background-color: #0e1117;'>
87
- <h5>📝 {row['Proverb']}</h5>
88
- <b>భావం:</b> {row['Meaning']}<br>
89
- <i>సందర్భం:</i> {row['Context'] or "—"}<br>
90
- <span style='color:#bbb;'>🏷️ శ్రేణి: {row['Category']}</span><br>
91
- <span style='font-size: 0.8em; color: gray;'>🕒 {row['Timestamp']}</span>
92
- </div>
93
- """, unsafe_allow_html=True)
94
-
95
- st.markdown("---")
96
- st.markdown("<center><small>© తెలుగు సామెతల ఖజానా – viswam.ai</small></center>", unsafe_allow_html=True)
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ from datetime import datetime
3
+ from ai_classifier import classify_proverb
4
+ from pymongo import MongoClient
5
+ import pandas as pd
6
+
7
+ # --- MongoDB Setup & Caching (Best Practice) ---
8
+
9
+ # Use @st.cache_resource to establish the database connection only once.
10
+ @st.cache_resource
11
+ def init_connection():
12
+ """Initializes a connection to the MongoDB database."""
13
+ return MongoClient(st.secrets["MONGO_URI"])
14
+
15
+ client = init_connection()
16
+ collection = client["proverbs_and_meanings"]["proverbs"]
17
+
18
+
19
+ # Use @st.cache_data to load data only when it changes.
20
+ @st.cache_data
21
+ def load_proverbs():
22
+ """Retrieves all proverbs, sorted by newest first."""
23
+ data = list(collection.find({}, {'_id': 0}).sort("Timestamp", -1))
24
+ return pd.DataFrame(data) if data else pd.DataFrame()
25
+
26
+
27
+ def save_proverb(proverb, meaning, context):
28
+ """Saves a new proverb to the database and clears the data cache."""
29
+ text_for_classification = proverb + " " + meaning
30
+ category = classify_proverb(text_for_classification)
31
+ new_entry = {
32
+ "Proverb": proverb.strip(),
33
+ "Meaning": meaning.strip(),
34
+ "Context": context.strip(),
35
+ "Category": category,
36
+ "Timestamp": datetime.now() # Store as a native datetime object
37
+ }
38
+ collection.insert_one(new_entry)
39
+ # Clear the cache so the gallery updates immediately
40
+ load_proverbs.clear()
41
+
42
+
43
+ # --- Streamlit Page Configuration ---
44
+ st.set_page_config(
45
+ page_title="తెలుగు సామెతల ఖజానా",
46
+ page_icon="📜",
47
+ layout="centered"
48
+ )
49
+
50
+
51
+ # --- Title & Introduction ---
52
+ st.title("📜 తెలుగు సామెతల ఖజానా")
53
+ st.markdown("### మీకు తెలిసిన సామెతను పంచుకోండి ✍️")
54
+ st.markdown("వెనుక తరాల నుంచి ముందుకు, మనం భద్రపరిద్దాం మన తెలుగు జ్ఞానం.")
55
+ st.markdown("<hr style='border:1px solid #555'>", unsafe_allow_html=True)
56
+
57
+
58
+ # --- Form UI (Simplified) ---
59
+ # The `clear_on_submit=True` parameter handles clearing the form automatically.
60
+ with st.form("proverb_form", clear_on_submit=True):
61
+ st.subheader("📥 కొత్త సామెతను జత చేయండి")
62
+
63
+ proverb = st.text_area("**సామెత (Proverb)**", height=100, max_chars=150)
64
+ meaning = st.text_area("**భావం (Meaning)**", height=100, max_chars=500)
65
+ context = st.text_input("**సందర్భం (Context / Usage Example – Optional)**", max_chars=200)
66
+
67
+ submitted = st.form_submit_button("✅ సామెతను జత చేయండి", use_container_width=True, type="primary")
68
+
69
+ if submitted:
70
+ if proverb and meaning:
71
+ save_proverb(proverb, meaning, context)
72
+ st.success("ధన్యవాదాలు! మీ సామెత జత చేయబడింది.")
73
+ st.balloons()
74
+ else:
75
+ st.error("దయచేసి సామెత మరియు భావం రెండూ నమోదు చేయండి.")
76
+
77
+
78
+ # --- Gallery Section ---
79
+ df = load_proverbs()
80
+
81
+ st.markdown("---")
82
+ st.subheader("🗂️ సామెతల గ్యాలరీ")
83
+ st.markdown(f"🔢 ఇప్పటివరకు మొత్తం **{len(df)}** సామెతలు జత చేయబడ్డాయి.")
84
+
85
+ if df.empty:
86
+ st.info("ఇప్పటి వరకు ఎలాంటి సామెతలు జత చేయలేదు. మీరే మొదటిది జత చేయండి!")
87
+ else:
88
+ for _, row in df.iterrows():
89
+ # Format the timestamp for display
90
+ timestamp_str = row['Timestamp'].strftime('%d %B %Y, %I:%M %p')
91
+ st.markdown(f"""
92
+ <div style='border: 1px solid #444; padding: 15px; border-radius: 10px; margin-bottom: 15px; background-color: #0e1117;'>
93
+ <h5>📝 {row['Proverb']}</h5>
94
+ <b>భావం:</b> {row['Meaning']}<br>
95
+ <i>సందర్భం:</i> {row['Context'] or ""}<br>
96
+ <span style='color:#bbb;'>🏷️ శ్రేణి: {row['Category']}</span><br>
97
+ <span style='font-size: 0.8em; color: gray;'>🕒 {timestamp_str}</span>
98
+ </div>
99
+ """, unsafe_allow_html=True)
100
+
101
+
102
+ # --- Footer ---
103
+ st.markdown("---")
104
+ st.markdown("<center><small>© తెలుగు సామెతల ఖజానా – viswam.ai</small></center>", unsafe_allow_html=True)