Kalam_Comfort / app.py
ashhal's picture
Update app.py
3dde9fc verified
raw
history blame
5.77 kB
import streamlit as st
import os
import json
import random
import requests
from datetime import datetime
from dotenv import load_dotenv
st.set_page_config(page_title="Kalam Comfort", page_icon="📚")
load_dotenv()
# ---------- File Setup ----------
default_moods = {
"anxious": ["13:28", "2:286", "10:62"],
"sad": ["94:5", "93:6", "65:7"],
"hopeless": ["39:53", "12:87", "3:139"],
"grateful": ["14:7", "31:12"],
"lonely": ["2:186", "9:40"],
"angry": ["3:134", "41:34"],
"lost": ["93:7", "6:122"],
"tired": ["94:6", "3:200"],
"afraid": ["8:46", "33:3"]
}
if not os.path.exists("moods.json"):
with open("moods.json", "w") as f:
json.dump(default_moods, f, indent=4)
with open("moods.json", "r") as f:
moods = json.load(f)
if not os.path.exists("reflections.json"):
with open("reflections.json", "w") as f:
json.dump({}, f)
with open("reflections.json", "r") as f:
reflections = json.load(f)
if not os.path.exists(".env"):
st.warning("⚠️ Optional: .env file not found. It's not required unless using secrets.")
# ---------- UI ----------
st.title("📚 Kalam Comfort")
st.subheader("Find Quranic comfort by emotion 💖")
selected_mood = st.selectbox("How are you feeling today?", list(moods.keys()), index=0)
if st.button("🔁 Show another verse"):
st.rerun()
if selected_mood:
verse_list = moods[selected_mood]
verse_ref = random.choice(verse_list)
surah_num, ayah_num = verse_ref.split(":")
# 1. Quran Arabic, English, Urdu
quran_api = f"https://api.alquran.cloud/v1/ayah/{surah_num}:{ayah_num}/editions/quran-simple,en.asad,ur.jalandhry"
response = requests.get(quran_api)
if response.status_code == 200:
data = response.json()['data']
arabic = data[0]['text']
english = data[1]['text']
urdu = data[2]['text']
surah_info = f"{data[0]['surah']['englishName']} ({data[0]['surah']['name']})"
st.markdown("### 🌙 Quranic Verse")
st.markdown(f"**Surah:** {surah_info} — Ayah {ayah_num}")
st.markdown(f"<div style='font-size:24px; direction: rtl'>{arabic}</div>", unsafe_allow_html=True)
st.markdown(f"**📖 English:** *{english}*")
st.markdown(f"**📖 Urdu:** {urdu}")
else:
st.error("❌ Failed to fetch Quranic text.")
st.stop()
# 2. Tafsir (Urdu)
tafsir_api = f"https://api.quranenc.com/v1/translation/tafsir?language=ur&verse_id={surah_num}:{ayah_num}"
tafsir_text = "Tafsir not available."
try:
tafsir_response = requests.get(tafsir_api)
if tafsir_response.status_code == 200:
tafsir_text = tafsir_response.json().get("result", {}).get("tafsir", "Tafsir not found.")
except Exception as e:
tafsir_text = "Could not fetch tafsir."
st.markdown("### 📘 Tafsir (Urdu)")
st.info(tafsir_text)
# 3. Dua (Mood-based, bilingual)
dua_map = {
"anxious": "اللهم اجعل قلبي مطمئنًا بذكرك\n**O Allah, make my heart tranquil with Your remembrance.**\n**یا اللہ! میرے دل کو اپنے ذکر سے اطمینان دے۔**",
"sad": "اللهم اجبر قلبي جبرا يتعجب له أهل السماوات والأرض\n**O Allah, mend my heart in a way that amazes the heavens and earth.**\n**یا اللہ! میرے دل کو ایسا سہارا دے جو زمین و آسمان کو حیران کر دے۔**",
"hopeless": "رب لا تذرني فردا وأنت خير الوارثين\n**My Lord, do not leave me alone — You are the Best Inheritor.**\n**یا رب! مجھے تنہا نہ چھوڑ، تو بہترین وارث ہے۔**",
"grateful": "اللهم اجعلني لك شَكُورًا\n**O Allah, make me deeply grateful to You.**\n**یا اللہ! مجھے شکر گزار بنا دے۔**",
"lonely": "اللهم كن معي حين لا يكون أحد بجانبي\n**O Allah, be with me when no one else is.**\n**یا اللہ! جب کوئی ساتھ نہ ہو، تو میرے ساتھ ہو۔**",
"angry": "اللهم ارزقني الحلم عند الغضب\n**O Allah, grant me forbearance when I’m angry.**\n**یا اللہ! غصے میں مجھے برداشت عطا فرما۔**",
"lost": "اللهم دلّني على صراطك المستقيم\n**O Allah, guide me to Your straight path.**\n**یا اللہ! مجھے اپنے سیدھے راستے پر چلا۔**",
"tired": "اللهم جدد طاقتي، وارزقني راحة البال\n**O Allah, renew my energy and grant me peace of mind.**\n**یا اللہ! میری طاقت کو تازہ کر اور مجھے ذہنی سکون عطا فرما۔**",
"afraid": "ربِّ أعني ولا تعن عليّ\n**My Lord, support me and not against me.**\n**میرے رب! میری مدد فرما، میرے خلاف نہ ہو۔**"
}
st.markdown("### 🤲 Dua (English + Urdu)")
st.markdown(dua_map.get(selected_mood, "May Allah ease your situation."))
# 4. Reflections
st.markdown("### 📝 Your Reflection")
reflection_input = st.text_area("Write your thoughts:", placeholder="How does this verse speak to you today?")
if st.button("💾 Save Reflection"):
reflections[selected_mood] = {
"text": reflection_input,
"timestamp": datetime.now().strftime("%Y-%m-%d %H:%M")
}
with open("reflections.json", "w") as f:
json.dump(reflections, f, indent=4)
st.success("Reflection saved.")
if selected_mood in reflections:
last = reflections[selected_mood]
st.markdown("#### 📜 Last Saved Reflection:")
st.markdown(f"**{last['timestamp']}** — {last['text']}")