ibrahim321123 commited on
Commit
c44d482
ยท
verified ยท
1 Parent(s): dfbc32f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +133 -223
app.py CHANGED
@@ -1,236 +1,146 @@
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("Healing Souls Through Quran")
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.")
236
 
 
1
  import streamlit as st
2
  from openai import OpenAI
 
3
  from PIL import Image
4
+ from deepface import DeepFace
5
  import tempfile
6
  import json
 
7
  import datetime
8
+ from fuzzywuzzy import process
9
+ import os
10
 
11
+ # ======================
12
+ # CONFIG
13
+ # ======================
14
+ st.set_page_config(page_title="Shaafee - The App that Helps You Heal", layout="centered")
 
 
15
 
16
+ # Load OpenAI key from env
17
  OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
 
 
 
 
18
  client = OpenAI(api_key=OPENAI_API_KEY)
19
 
20
+ # Load masjid data
21
+ with open("masjid_data.json", "r", encoding="utf-8") as f:
22
+ masjid_data = json.load(f)
23
+
24
+ # Init session state
25
+ if "page" not in st.session_state:
26
+ st.session_state.page = "home"
27
+
28
+ # ======================
29
+ # LOAD CUSTOM CSS
30
+ # ======================
31
+ def local_css(file_name):
32
+ with open(file_name) as f:
33
+ st.markdown(f"<style>{f.read()}</style>", unsafe_allow_html=True)
34
+
35
+ local_css("style.css")
36
+
37
+ # ======================
38
+ # HOME PAGE
39
+ # ======================
40
+ if st.session_state.page == "home":
41
+ st.markdown("""
42
+ <div class="hero">
43
+ <h1>The App that helps you heal</h1>
44
+ <p>Guiding you through stress, sadness and anxiety with the wisdom of the Qurโ€™an</p>
45
+ <button onclick="window.location.href='?page=menu'">Browse App</button>
46
+ </div>
47
+ """, unsafe_allow_html=True)
48
+
49
+ if st.query_params.get("page") == "menu":
50
+ st.session_state.page = "menu"
51
+
52
+ # ======================
53
+ # MENU PAGE
54
+ # ======================
55
+ elif st.session_state.page == "menu":
56
+ st.markdown("""
57
+ <div class="menu">
58
+ <div class="card" onclick="window.location.href='?page=mood'">๐Ÿ“ธ Mood Detection</div>
59
+ <div class="card" onclick="window.location.href='?page=voice'">๐ŸŽ™๏ธ Voice Journal</div>
60
+ <div class="card" onclick="window.location.href='?page=search'">โ“ Qurโ€™an Search</div>
61
+ <div class="card" onclick="window.location.href='?page=tracker'">๐ŸŒฑ Progress Tracker</div>
62
+ <div class="card" onclick="window.location.href='?page=masjid'">๐Ÿ“ Masjid Finder</div>
63
+ </div>
64
+ """, unsafe_allow_html=True)
65
+
66
+ page = st.query_params.get("page")
67
+ if page:
68
+ st.session_state.page = page
69
+
70
+ # ======================
71
+ # MOOD DETECTION
72
+ # ======================
73
+ elif st.session_state.page == "mood":
74
+ st.title("๐Ÿ“ธ Mood Detection")
75
+ uploaded_file = st.file_uploader("Upload your selfie:", type=["jpg", "jpeg", "png"])
76
+ if uploaded_file:
77
+ img = Image.open(uploaded_file).convert("RGB")
78
+ st.image(img)
79
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".jpg") as tmp_file:
80
+ img.save(tmp_file.name)
81
+ image_path = tmp_file.name
82
+
83
+ result = DeepFace.analyze(img_path=image_path, actions=["emotion"], enforce_detection=False)
84
+ emotion = result["dominant_emotion"]
85
+ st.success(f"Detected Emotion: {emotion}")
86
+
87
+ if st.button("Get Ayah"):
88
+ prompt = f"Suggest a Quranic Ayah for someone feeling {emotion}."
89
+ response = client.chat.completions.create(
90
+ model="gpt-4o-mini",
91
+ messages=[{"role": "user", "content": prompt}]
92
+ )
93
+ st.write(response.choices[0].message.content)
94
+
95
+ # ======================
96
+ # VOICE JOURNAL
97
+ # ======================
98
+ elif st.session_state.page == "voice":
99
+ st.title("๐ŸŽ™๏ธ Voice Journal")
100
+ st.info("Coming soon InshaAllah!")
101
+
102
+ # ======================
103
+ # QURAN SEARCH
104
+ # ======================
105
+ elif st.session_state.page == "search":
106
+ st.title("โ“ Qurโ€™an Search")
107
+ topic = st.text_input("What does the Qurโ€™an say about...")
108
+ if st.button("Get Ayah"):
109
+ prompt = f"Provide a Quranic Ayah for: {topic}."
110
+ response = client.chat.completions.create(
111
+ model="gpt-4o-mini",
112
+ messages=[{"role": "user", "content": prompt}]
113
  )
114
+ st.write(response.choices[0].message.content)
115
+
116
+ # ======================
117
+ # TRACKER
118
+ # ======================
119
+ elif st.session_state.page == "tracker":
120
+ st.title("๐ŸŒฑ Healing Tracker")
121
+ goal = st.text_input("Your Goal")
122
+ days = st.slider("Days:", 1, 30, 7)
123
+ if "progress" not in st.session_state:
124
+ st.session_state.progress = [False] * days
125
+ for i in range(days):
126
+ done = st.checkbox(f"Day {i+1}", value=st.session_state.progress[i], key=f"day{i}")
127
+ st.session_state.progress[i] = done
128
+ percent = int(sum(st.session_state.progress) / days * 100)
129
+ st.progress(percent)
130
+
131
+ # ======================
132
+ # MASJID FINDER
133
+ # ======================
134
+ elif st.session_state.page == "masjid":
135
+ st.title("๐Ÿ“ Masjid Finder")
136
+ city = st.selectbox("City", list(masjid_data.keys()))
137
+ area = st.text_input("Area")
138
+ if st.button("Find"):
139
+ match, score = process.extractOne(area.lower(), masjid_data[city].keys())
140
+ if score >= 70:
141
+ st.write(f"Masajid near {match.title()}:")
142
+ for masjid in masjid_data[city][match]:
143
+ st.write(f"- {masjid}")
144
+ else:
145
+ st.warning("No match found.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
146