File size: 9,217 Bytes
77b49bd
ede0423
 
 
 
 
 
 
 
0e35e4f
ede0423
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0909872
ede0423
 
 
 
 
 
 
 
 
 
0909872
ede0423
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
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.")