ibrahim321123 commited on
Commit
ede0423
·
verified ·
1 Parent(s): 1c9b749

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +233 -66
app.py CHANGED
@@ -1,68 +1,235 @@
1
  import streamlit as st
 
 
 
 
 
 
 
 
2
 
3
- if "page" not in st.session_state:
4
- st.session_state.page = "home"
5
-
6
- def add_bg_from_url(image_url):
7
- st.markdown(
8
- f"""
9
- <style>
10
- .stApp {{
11
- background: url("{image_url}") no-repeat center center fixed;
12
- background-size: cover;
13
- }}
14
- </style>
15
- """,
16
- unsafe_allow_html=True
17
- )
18
-
19
- if st.session_state.page == "home":
20
- add_bg_from_url("https://huggingface.co/spaces/ibrahim321123/Shaafee/resolve/main/ShaafeeUi.png")
21
-
22
- # Position the native Streamlit button with custom CSS
23
- st.markdown(
24
- """
25
- <style>
26
- div.stButton > button {
27
- position: fixed;
28
- right: 50px;
29
- bottom: 50px;
30
- background-color: #FFA500;
31
- color: white;
32
- border: none;
33
- padding: 15px 30px;
34
- font-size: 18px;
35
- border-radius: 8px;
36
- cursor: pointer;
37
- z-index: 9999;
38
- }
39
- </style>
40
- """,
41
- unsafe_allow_html=True
42
- )
43
-
44
- if st.button("🚀 Browse Shaafee"):
45
- st.session_state.page = "browse"
46
-
47
- # If query params present → also switch
48
- if st.query_params:
49
- st.session_state.page = "browse"
50
-
51
- elif st.session_state.page == "browse":
52
- add_bg_from_url("https://huggingface.co/spaces/ibrahim321123/Shaafee/resolve/main/Shaafee2.png")
53
-
54
- st.title("✨ Shaafee - Explore Modules")
55
-
56
- col1, col2 = st.columns(2)
57
- with col1:
58
- if st.button("📖 Qur'anic Journaling"):
59
- st.switch_page("pages/1_Quran_Journaling.py")
60
- if st.button("📷 Emotion Recognition"):
61
- st.switch_page("pages/2_Emotion_Recognition.py")
62
- if st.button("💬 Ask the Qur'an"):
63
- st.switch_page("pages/3_Ask_Quran.py")
64
- with col2:
65
- if st.button("🌿 Healing Tracker"):
66
- st.switch_page("pages/4_Healing_Tracker.py")
67
- if st.button("🕌 Masjid Finder"):
68
- st.switch_page("pages/5_Masjid_Finder.py")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import streamlit as st
2
+ from openai import OpenAI
3
+ from deepface import DeepFace
4
+ from PIL import Image
5
+ from fuzzywuzzy import process
6
+ import tempfile
7
+ import json
8
+ import os
9
+ import datetime
10
 
11
+ # ===== Streamlit App Config =====
12
+ st.set_page_config(
13
+ page_title="Shaafee - Helps You Heal",
14
+ page_icon="🕌",
15
+ layout="centered",
16
+ )
17
+
18
+ # ===== Initialize OpenAI =====
19
+ OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
20
+ if not OPENAI_API_KEY:
21
+ st.error("❌ OPENAI_API_KEY not found! Please add it to your environment variables.")
22
+ st.stop()
23
+
24
+ client = OpenAI(api_key=OPENAI_API_KEY)
25
+
26
+ # ===== Session State =====
27
+ if "show_features" not in st.session_state:
28
+ st.session_state.show_features = False
29
+
30
+ # ===== Tabs =====
31
+ tabs = st.tabs([
32
+ "🏠 Home",
33
+ "📖 Qur'anic Journaling",
34
+ "📸 Emotion Detector",
35
+ "❓ Ask Qur’an",
36
+ "🌱 Healing Tracker",
37
+ "📍 Masjid Finder"
38
+ ])
39
+
40
+ # ============================================================
41
+ # 🏠 HOME TAB
42
+ # ============================================================
43
+ with tabs[0]:
44
+ st.title("🕌 Shaafee")
45
+ st.subheader("_Helps You Heal_")
46
+
47
+ st.image("https://i.imgur.com/QBtHT9U.png", width=150) # Optional logo
48
+
49
+ st.write("""
50
+ **Shaafee** is your AI-powered Islamic companion to help you heal spiritually:
51
+ - 📖 Get Qur’anic Ayah suggestions for how you feel
52
+ - 📸 Upload a selfie — detect your emotion & get an Ayah
53
+ - Ask what the Qur’an says about any topic
54
+ - 🌱 Track your spiritual healing journey
55
+ - 📍 Find Masajid near you
56
+ """)
57
+
58
+ st.info("✨ _May Allah grant you shifa & guidance._")
59
+
60
+ if st.button("Start Using Shaafee"):
61
+ st.session_state.show_features = True
62
+
63
+ # ============================================================
64
+ # OTHER TABS: Show only if show_features = True
65
+ # ============================================================
66
+
67
+ if st.session_state.show_features:
68
+
69
+ # ============================================================
70
+ # 📖 TAB 1: Qur’anic Journaling
71
+ # ============================================================
72
+ with tabs[1]:
73
+ st.header("📖 Qur'anic Journaling")
74
+ emotion = st.text_input("How are you feeling right now?")
75
+
76
+ if st.button("Get Qur’anic Guidance", key="journaling"):
77
+ if emotion.strip():
78
+ prompt = f"""
79
+ Suggest one Qur'anic Ayah in Arabic that helps someone feeling {emotion}.
80
+ Provide:
81
+ 1) The Ayah in Arabic.
82
+ 2) Its English translation.
83
+ 3) A short, easy-to-understand tafsir.
84
+ """
85
+ try:
86
+ response = client.chat.completions.create(
87
+ model="gpt-4o-mini",
88
+ messages=[{"role": "user", "content": prompt}]
89
+ )
90
+ st.subheader("📖 Suggested Qur'anic Ayah")
91
+ st.write(response.choices[0].message.content)
92
+
93
+ except Exception as e:
94
+ st.error(f"❌ Error: {e}")
95
+ else:
96
+ st.warning("Please enter how you feel.")
97
+
98
+ # ============================================================
99
+ # 📸 TAB 2: Selfie Emotion → Qur’an
100
+ # ============================================================
101
+ with tabs[2]:
102
+ st.header("📸 Emotion Recognition & Qur'anic Ayah (AI)")
103
+ uploaded_file = st.file_uploader(
104
+ "Upload your selfie:", type=["jpg", "jpeg", "png"], key="selfie"
105
+ )
106
+
107
+ if uploaded_file is not None:
108
+ img = Image.open(uploaded_file).convert("RGB")
109
+ st.image(img, caption="Uploaded Selfie", use_container_width=True)
110
+
111
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".jpg") as tmp_file:
112
+ img.save(tmp_file.name)
113
+ image_path = tmp_file.name
114
+
115
+ with st.spinner("🔍 Analyzing emotion..."):
116
+ try:
117
+ result = DeepFace.analyze(
118
+ img_path=image_path, actions=["emotion"], enforce_detection=False
119
+ )
120
+ if isinstance(result, list):
121
+ dominant_emotion = result[0]["dominant_emotion"].lower()
122
+ else:
123
+ dominant_emotion = result["dominant_emotion"].lower()
124
+
125
+ st.success(f"✅ Detected Emotion: *{dominant_emotion.capitalize()}*")
126
+
127
+ if st.button("Get Qur’anic Guidance", key="selfie_ayah"):
128
+ prompt = f"""
129
+ Suggest one Qur'anic Ayah in Arabic that helps someone feeling {dominant_emotion}.
130
+ Provide:
131
+ 1) The Ayah in Arabic.
132
+ 2) Its English translation.
133
+ 3) A short, easy-to-understand tafsir.
134
+ """
135
+ response = client.chat.completions.create(
136
+ model="gpt-4o-mini",
137
+ messages=[{"role": "user", "content": prompt}]
138
+ )
139
+ st.subheader("📖 Suggested Qur'anic Ayah")
140
+ st.write(response.choices[0].message.content)
141
+
142
+ except Exception as e:
143
+ st.error(f"❌ Error: {e}")
144
+
145
+ # ============================================================
146
+ # ❓ TAB 3: Ask the Qur’an
147
+ # ============================================================
148
+ with tabs[3]:
149
+ st.header("❓ Ask the Qur’an")
150
+ topic = st.text_input("Ask your question:", placeholder="What does the Qur’an say about ____?")
151
+
152
+ if st.button("Get Qur’anic Guidance", key="askquran"):
153
+ if topic.strip():
154
+ prompt = f"""
155
+ Provide a Qur'anic Ayah in Arabic related to: {topic}.
156
+ Also provide:
157
+ 1) The English translation.
158
+ 2) A short tafsir/explanation.
159
+ Keep it clear and authentic.
160
+ """
161
+ try:
162
+ response = client.chat.completions.create(
163
+ model="gpt-4o-mini",
164
+ messages=[{"role": "user", "content": prompt}]
165
+ )
166
+ st.subheader("📖 Qur’anic Answer")
167
+ st.write(response.choices[0].message.content)
168
+ except Exception as e:
169
+ st.error(f"❌ Error: {e}")
170
+ else:
171
+ st.warning("Please type your question.")
172
+
173
+ # ============================================================
174
+ # 🌱 TAB 4: Soul Healing Tracker
175
+ # ============================================================
176
+ with tabs[4]:
177
+ st.header("🌱 Healing Tracker")
178
+ emotion = st.selectbox(
179
+ "Which emotion/challenge are you working on?",
180
+ ["Anxiety", "Sadness", "Anger", "Hopelessness", "Loneliness"]
181
+ )
182
+
183
+ goal = st.text_input("Set your spiritual goal (e.g., Recite Surah Duha every morning for 7 days):")
184
+
185
+ days = st.slider("How many days do you want to track?", 1, 30, 7)
186
+
187
+ if "progress" not in st.session_state:
188
+ st.session_state.progress = [False] * days
189
+
190
+ st.subheader("Daily Check-In")
191
+ for i in range(days):
192
+ done = st.checkbox(f"Day {i+1} completed?", value=st.session_state.progress[i], key=f"day{i}")
193
+ st.session_state.progress[i] = done
194
+
195
+ completed = sum(st.session_state.progress)
196
+ percent = int((completed / days) * 100)
197
+ st.progress(percent)
198
+ st.write(f"✅ You’ve completed {completed} of {days} days. ({percent}%)")
199
+
200
+ if percent == 100:
201
+ st.success("MashaAllah! You’ve achieved your goal. Keep going!")
202
+ elif percent >= 50:
203
+ st.info("Great work! You’re more than halfway there.")
204
+ elif percent > 0:
205
+ st.write("Good start! Keep it consistent.")
206
+
207
+ # ============================================================
208
+ # 📍 TAB 5: Masjid Finder
209
+ # ============================================================
210
+ with tabs[5]:
211
+ st.header("📍 Find Nearby Masajid")
212
+
213
+ try:
214
+ with open("masjid_data.json", "r", encoding="utf-8") as f:
215
+ masjid_data = json.load(f)
216
+ except Exception as e:
217
+ st.error(f"Could not load masjid data: {e}")
218
+ st.stop()
219
+
220
+ city = st.selectbox("Select your city:", list(masjid_data.keys()))
221
+ area_input = st.text_input("Enter your area name (e.g., 'Model Town')")
222
+
223
+ if st.button("Find Masajid"):
224
+ if area_input.strip():
225
+ areas = masjid_data[city]
226
+ best_match, score = process.extractOne(area_input.lower(), areas.keys())
227
+
228
+ if score >= 70:
229
+ st.success(f"📍 Masajid near *{best_match.title()}* in *{city.title()}*:")
230
+ for name in areas[best_match]:
231
+ st.markdown(f"- {name}")
232
+ else:
233
+ st.warning("⚠️ No close match found. Try different spelling.")
234
+ else:
235
+ st.info("Please enter an area name.")