ibrahim321123 commited on
Commit
0e35e4f
·
verified ·
1 Parent(s): 62b1535

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +234 -55
app.py CHANGED
@@ -1,67 +1,246 @@
1
  import streamlit as st
2
-
3
- # Set page config
 
 
 
 
 
 
 
 
 
4
  st.set_page_config(
5
  page_title="Shaafee - Helps You Heal",
6
  page_icon="🕋",
7
  layout="centered"
8
  )
9
 
10
- # App Title
11
- st.title("🕋 Shaafee")
12
- st.subheader("Helps You Heal")
13
-
14
- # Intro
15
- st.markdown("""
16
- Welcome to **Shaafee**, your AI-powered Islamic companion that helps you find comfort, guidance, and healing through the Quran and your faith.
17
- """)
18
-
19
- # Features Section
20
- st.header("✨ Features")
21
-
22
- # Feature 1
23
- st.markdown("""
24
- **📖 Quranic Verse for Your Feelings**
25
-
26
- Tell us how you feel — and Shaafee will find a Quranic ayah to comfort and guide you.
27
- """)
28
-
29
- # Feature 2
30
- st.markdown("""
31
- **🤳 Emotion Detection with Selfie**
32
 
33
- Upload a selfie, and Shaafee will recognize your emotion and suggest a suitable ayah to uplift your soul.
34
- """)
 
35
 
36
- # Feature 3
37
- st.markdown("""
38
- **❓ Ask the Quran**
39
 
40
- Curious about what the Quran says about any topic? Just ask, and Shaafee will guide you with relevant verses.
41
- """)
 
42
 
43
- # Feature 4
44
- st.markdown("""
45
- **🌙 Soul Healing Tracker**
46
-
47
- Track your spiritual healing journey with Shaafee’s personalized progress tools.
48
- """)
49
-
50
- # Feature 5
51
- st.markdown("""
52
- **🕌 Mosque Finder**
53
-
54
- Find mosques near you to connect with your community and strengthen your Imaan.
55
- """)
56
-
57
- # Call to Action
58
- st.header("🚀 Get Started")
59
- st.markdown("""
60
- Stay tuned! We are launching soon, Insha'Allah.
61
- Meanwhile, feel free to explore the features as we build this experience for you.
62
- """)
63
-
64
- # Footer
65
- st.markdown("---")
66
- st.markdown("Made with ❤️ for the Ummah")
67
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import streamlit as st
2
+ from openai import OpenAI
3
+ from deepface import DeepFace
4
+ from PIL import Image
5
+ import tempfile
6
+ import json
7
+ import random
8
+ import os
9
+ import datetime
10
+ from fuzzywuzzy import process
11
+
12
+ # ================== CONFIG ==================
13
  st.set_page_config(
14
  page_title="Shaafee - Helps You Heal",
15
  page_icon="🕋",
16
  layout="centered"
17
  )
18
 
19
+ # ================== OpenAI CLIENT ==================
20
+ client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
 
22
+ # ================== Load Local Ayahs JSON ==================
23
+ with open("ayahs.json", "r", encoding="utf-8") as f:
24
+ ayah_data = json.load(f)
25
 
26
+ # ================== Masjid Data ==================
27
+ # Put your full masjid_data here (as you shared)
 
28
 
29
+ masjid_data = {
30
+ # truncated for brevity — use your full dictionary here
31
+ }
32
 
33
+ # ================== TABS ==================
34
+ st.title("🕋 Shaafee")
35
+ st.subheader("Helps You Heal")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36
 
37
+ tabs = st.tabs([
38
+ "🏠 Home",
39
+ "📖 Qur'anic Journaling",
40
+ "🤳 Emotion Detection",
41
+ "❓ Ask the Qur’an",
42
+ "🌙 Healing Tracker",
43
+ "🕌 Masjid Finder"
44
+ ])
45
+
46
+ # ================== HOME ==================
47
+ with tabs[0]:
48
+ st.markdown("""
49
+ Welcome to **Shaafee**, your AI-powered Islamic companion for comfort, guidance, and healing through the Qur’an and your faith.
50
+ """)
51
+
52
+ st.header("✨ Features")
53
+ st.markdown("""
54
+ **📖 Quranic Journaling** — Describe how you feel, and get a Quranic ayah for comfort.
55
+
56
+ **🤳 Emotion Detection** — Upload a selfie to detect your emotion and receive an ayah.
57
+
58
+ **❓ Ask the Qur’an** — Ask any question and see what the Qur’an says.
59
+
60
+ **🌙 Healing Tracker** — Track your spiritual goals and healing progress.
61
+
62
+ **🕌 Masjid Finder** — Find nearby mosques in your city.
63
+ """)
64
+
65
+ st.header("🚀 Get Started")
66
+ st.markdown("""
67
+ Stay tuned! We are launching soon, Insha'Allah.
68
+ """)
69
+
70
+ st.markdown("---")
71
+ st.markdown("Made with ❤️ for the Ummah")
72
+
73
+ # ================== QURANIC JOURNALING ==================
74
+ with tabs[1]:
75
+ st.header("📖 Qur'anic Journaling")
76
+
77
+ emotion = st.text_input("How are you feeling right now?")
78
+
79
+ if st.button("Get Qur'anic Guidance", key="journaling"):
80
+ if emotion.strip():
81
+ prompt = f"""
82
+ Suggest one Qur'anic Ayah in Arabic that helps someone feeling {emotion}.
83
+ Provide:
84
+ 1) The Ayah in Arabic
85
+ 2) Its English translation
86
+ 3) A short, easy-to-understand tafsir.
87
+ """
88
+
89
+ response = client.chat.completions.create(
90
+ model="gpt-4o-mini",
91
+ messages=[{"role": "user", "content": prompt}]
92
+ )
93
+
94
+ output = response.choices[0].message.content
95
+
96
+ st.subheader("Qur'anic Guidance")
97
+ st.write(output)
98
+ else:
99
+ st.warning("Please enter how you feel.")
100
+
101
+ # ================== EMOTION DETECTION ==================
102
+ with tabs[2]:
103
+ st.header("🤳 Emotion Detection & Quranic Ayah")
104
+
105
+ uploaded_file = st.file_uploader(
106
+ "Upload your selfie...", type=["jpg", "jpeg", "png"]
107
+ )
108
+
109
+ if uploaded_file is not None:
110
+ img = Image.open(uploaded_file).convert("RGB")
111
+ st.image(img, caption="Uploaded Selfie", use_container_width=True)
112
+
113
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".jpg") as tmp_file:
114
+ img.save(tmp_file.name)
115
+ image_path = tmp_file.name
116
+
117
+ with st.spinner("Analyzing emotion..."):
118
+ result = DeepFace.analyze(
119
+ img_path=image_path,
120
+ actions=["emotion"],
121
+ enforce_detection=False
122
+ )
123
+
124
+ if isinstance(result, list):
125
+ dominant_emotion = result[0]["dominant_emotion"].lower()
126
+ else:
127
+ dominant_emotion = result["dominant_emotion"].lower()
128
+
129
+ st.success(f"Detected Emotion: *{dominant_emotion.capitalize()}*")
130
+
131
+ ayahs_for_emotion = ayah_data.get(dominant_emotion)
132
+
133
+ if ayahs_for_emotion:
134
+ selected_ayah = random.choice(ayahs_for_emotion)
135
+ st.header("📖 Suggested Quranic Ayah")
136
+ st.markdown(f"*Ayah (Arabic):* {selected_ayah['ayah_arabic']}")
137
+ st.markdown(f"*Surah & Ayah:* {selected_ayah['surah_ayah']}")
138
+ st.markdown(f"*Translation:* {selected_ayah['translation']}")
139
+ st.markdown(f"*Tafsir:* {selected_ayah['tafsir']}")
140
+ else:
141
+ st.warning(
142
+ f"❌ No Ayahs found for *{dominant_emotion}*. "
143
+ f"Please add more to ayahs.json!"
144
+ )
145
+
146
+ st.info("💡 Uses only local, verified Ayahs for accuracy.")
147
+
148
+ # ================== ASK THE QURAN ==================
149
+ with tabs[3]:
150
+ st.header("❓ Ask the Qur’an")
151
+
152
+ topic = st.text_input(
153
+ "Ask your question:",
154
+ placeholder="What does the Qur’an say about ____?"
155
+ )
156
+
157
+ if st.button("Get Qur’anic Guidance", key="ask_quran"):
158
+ if topic.strip():
159
+ prompt = f"""
160
+ Provide a Qur'anic ayah in Arabic related to: {topic}.
161
+ Also provide:
162
+ 1) The English translation
163
+ 2) A short tafsir/explanation that is easy to understand.
164
+ Keep it concise.
165
+ """
166
+
167
+ try:
168
+ response = client.chat.completions.create(
169
+ model="gpt-4o-mini",
170
+ messages=[{"role": "user", "content": prompt}]
171
+ )
172
+ output = response.choices[0].message.content
173
+
174
+ st.subheader("Qur’anic Guidance")
175
+ st.write(output)
176
+
177
+ except Exception as e:
178
+ st.error(f"Error: {e}")
179
+ else:
180
+ st.warning("Please type your question.")
181
+
182
+ # ================== HEALING TRACKER ==================
183
+ with tabs[4]:
184
+ st.header("🌙 Soul Healing Tracker")
185
+
186
+ emotion = st.selectbox(
187
+ "Which emotion or challenge are you working on?",
188
+ ["Anxiety", "Sadness", "Anger", "Hopelessness", "Loneliness"]
189
+ )
190
+
191
+ goal = st.text_input(
192
+ "Set your healing goal (e.g., Recite Surah Duha every morning for 7 days):"
193
+ )
194
+
195
+ days = st.slider("How many days do you want to track?", 1, 30, 7)
196
+
197
+ if "progress" not in st.session_state:
198
+ st.session_state.progress = [False] * days
199
+
200
+ st.subheader("Daily Check-In")
201
+ for i in range(days):
202
+ done = st.checkbox(
203
+ f"Day {i+1} completed?", value=st.session_state.progress[i], key=f"day{i}"
204
+ )
205
+ st.session_state.progress[i] = done
206
+
207
+ completed = sum(st.session_state.progress)
208
+ percent = int((completed / days) * 100)
209
+
210
+ st.progress(percent)
211
+ st.write(f"✅ You’ve completed {completed} out of {days} days. ({percent}% done)")
212
+
213
+ if percent == 100:
214
+ st.success("MashaAllah! You’ve achieved your goal. Keep going!")
215
+ elif percent >= 50:
216
+ st.info("Great work! You’re more than halfway there.")
217
+ elif percent > 0:
218
+ st.write("Good start! Keep it consistent.")
219
+
220
+ # ================== MASJID FINDER ==================
221
+ with tabs[5]:
222
+ st.header("🕌 Find a Masjid Near You")
223
+
224
+ city = st.selectbox(
225
+ "Select your city:",
226
+ ["lahore", "islamabad", "karachi"]
227
+ )
228
+
229
+ locality = st.text_input(
230
+ "Enter your area/locality:",
231
+ placeholder="e.g., Model Town, G-6, DHA"
232
+ )
233
+
234
+ if st.button("Find Masajid"):
235
+ locations = masjid_data.get(city, {})
236
+ if not locations:
237
+ st.warning("❌ No masjid data for this city.")
238
+ else:
239
+ best_match, score = process.extractOne(locality.strip().lower(), locations.keys())
240
+
241
+ if score >= 70:
242
+ st.success(f"📍 Masajid near '{best_match.title()}':")
243
+ for name in locations[best_match]:
244
+ st.write(f"- {name}")
245
+ else:
246
+ st.warning("⚠ No close match found. Try again with a different area.")