import streamlit as st from openai import OpenAI from deepface import DeepFace from PIL import Image from fuzzywuzzy import process import tempfile import json import os import datetime # ===== Streamlit App Config ===== st.set_page_config( page_title="Shaafee - Helps You Heal", page_icon="🕌", layout="centered", ) # ===== Initialize OpenAI ===== OPENAI_API_KEY = os.getenv("OPENAI_API_KEY") if not OPENAI_API_KEY: st.error("❌ OPENAI_API_KEY not found! Please add it to your environment variables.") st.stop() client = OpenAI(api_key=OPENAI_API_KEY) # ===== Session State ===== if "show_features" not in st.session_state: st.session_state.show_features = False # ===== Tabs ===== tabs = st.tabs([ "🏠 Home", "📖 Qur'anic Journaling", "📸 Emotion Detector", "❓ Ask Qur’an", "🌱 Healing Tracker", "📍 Masjid Finder" ]) # ============================================================ # 🏠 HOME TAB # ============================================================ with tabs[0]: st.title("🕌 Shaafee") st.subheader("_Helps You Heal_") #st.image("https://i.imgur.com/QBtHT9U.png", width=150) # Optional logo st.write(""" **Shaafee** is your AI-powered Islamic companion to help you heal spiritually: - 📖 Get Qur’anic Ayah suggestions for how you feel - 📸 Upload a selfie — detect your emotion & get an Ayah - ❓ Ask what the Qur’an says about any topic - 🌱 Track your spiritual healing journey - 📍 Find Masajid near you """) st.info("Healing Souls Through Quran") if st.button("Start Using Shaafee"): st.session_state.show_features = True # ============================================================ # OTHER TABS: Show only if show_features = True # ============================================================ if st.session_state.show_features: # ============================================================ # 📖 TAB 1: Qur’anic Journaling # ============================================================ with tabs[1]: st.header("📖 Qur'anic Journaling") emotion = st.text_input("How are you feeling right now?") if st.button("Get Qur’anic Guidance", key="journaling"): if emotion.strip(): prompt = f""" Suggest one Qur'anic Ayah in Arabic that helps someone feeling {emotion}. Provide: 1) The Ayah in Arabic. 2) Its English translation. 3) A short, easy-to-understand tafsir. """ try: response = client.chat.completions.create( model="gpt-4o-mini", messages=[{"role": "user", "content": prompt}] ) st.subheader("📖 Suggested Qur'anic Ayah") st.write(response.choices[0].message.content) except Exception as e: st.error(f"❌ Error: {e}") else: st.warning("Please enter how you feel.") # ============================================================ # 📸 TAB 2: Selfie Emotion → Qur’an # ============================================================ with tabs[2]: st.header("📸 Emotion Recognition & Qur'anic Ayah (AI)") uploaded_file = st.file_uploader( "Upload your selfie:", type=["jpg", "jpeg", "png"], key="selfie" ) if uploaded_file is not None: img = Image.open(uploaded_file).convert("RGB") st.image(img, caption="Uploaded Selfie", use_container_width=True) with tempfile.NamedTemporaryFile(delete=False, suffix=".jpg") as tmp_file: img.save(tmp_file.name) image_path = tmp_file.name with st.spinner("🔍 Analyzing emotion..."): try: result = DeepFace.analyze( img_path=image_path, actions=["emotion"], enforce_detection=False ) if isinstance(result, list): dominant_emotion = result[0]["dominant_emotion"].lower() else: dominant_emotion = result["dominant_emotion"].lower() st.success(f"✅ Detected Emotion: *{dominant_emotion.capitalize()}*") if st.button("Get Qur’anic Guidance", key="selfie_ayah"): prompt = f""" Suggest one Qur'anic Ayah in Arabic that helps someone feeling {dominant_emotion}. Provide: 1) The Ayah in Arabic. 2) Its English translation. 3) A short, easy-to-understand tafsir. """ response = client.chat.completions.create( model="gpt-4o-mini", messages=[{"role": "user", "content": prompt}] ) st.subheader("📖 Suggested Qur'anic Ayah") st.write(response.choices[0].message.content) except Exception as e: st.error(f"❌ Error: {e}") # ============================================================ # ❓ TAB 3: Ask the Qur’an # ============================================================ with tabs[3]: st.header("❓ Ask the Qur’an") topic = st.text_input("Ask your question:", placeholder="What does the Qur’an say about ____?") if st.button("Get Qur’anic Guidance", key="askquran"): if topic.strip(): prompt = f""" Provide a Qur'anic Ayah in Arabic related to: {topic}. Also provide: 1) The English translation. 2) A short tafsir/explanation. Keep it clear and authentic. """ try: response = client.chat.completions.create( model="gpt-4o-mini", messages=[{"role": "user", "content": prompt}] ) st.subheader("📖 Qur’anic Answer") st.write(response.choices[0].message.content) except Exception as e: st.error(f"❌ Error: {e}") else: st.warning("Please type your question.") # ============================================================ # 🌱 TAB 4: Soul Healing Tracker # ============================================================ with tabs[4]: st.header("🌱 Healing Tracker") emotion = st.selectbox( "Which emotion/challenge are you working on?", ["Anxiety", "Sadness", "Anger", "Hopelessness", "Loneliness"] ) goal = st.text_input("Set your spiritual goal (e.g., Recite Surah Duha every morning for 7 days):") days = st.slider("How many days do you want to track?", 1, 30, 7) if "progress" not in st.session_state: st.session_state.progress = [False] * days st.subheader("Daily Check-In") for i in range(days): done = st.checkbox(f"Day {i+1} completed?", value=st.session_state.progress[i], key=f"day{i}") st.session_state.progress[i] = done completed = sum(st.session_state.progress) percent = int((completed / days) * 100) st.progress(percent) st.write(f"✅ You’ve completed {completed} of {days} days. ({percent}%)") if percent == 100: st.success("MashaAllah! You’ve achieved your goal. Keep going!") elif percent >= 50: st.info("Great work! You’re more than halfway there.") elif percent > 0: st.write("Good start! Keep it consistent.") # ============================================================ # 📍 TAB 5: Masjid Finder # ============================================================ with tabs[5]: st.header("📍 Find Nearby Masajid") try: with open("masjid_data.json", "r", encoding="utf-8") as f: masjid_data = json.load(f) except Exception as e: st.error(f"Could not load masjid data: {e}") st.stop() city = st.selectbox("Select your city:", list(masjid_data.keys())) area_input = st.text_input("Enter your area name (e.g., 'Model Town')") if st.button("Find Masajid"): if area_input.strip(): areas = masjid_data[city] best_match, score = process.extractOne(area_input.lower(), areas.keys()) if score >= 70: st.success(f"📍 Masajid near *{best_match.title()}* in *{city.title()}*:") for name in areas[best_match]: st.markdown(f"- {name}") else: st.warning("⚠️ No close match found. Try different spelling.") else: st.info("Please enter an area name.")