Spaces:
Sleeping
Sleeping
Create 2_Emotion_Recognition.py
Browse files
pages/2_Emotion_Recognition.py
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
from PIL import Image
|
| 3 |
+
import tempfile
|
| 4 |
+
from deepface import DeepFace
|
| 5 |
+
from openai import OpenAI
|
| 6 |
+
|
| 7 |
+
# Initialize OpenAI
|
| 8 |
+
client = OpenAI(api_key=st.secrets["OPENAI_API_KEY"])
|
| 9 |
+
|
| 10 |
+
st.title("📸 Shaafee - Emotion Recognition")
|
| 11 |
+
|
| 12 |
+
st.write(
|
| 13 |
+
"Upload your selfie — I’ll detect your emotion and suggest a Qur'anic Ayah for you."
|
| 14 |
+
)
|
| 15 |
+
|
| 16 |
+
# Upload file
|
| 17 |
+
uploaded_file = st.file_uploader("Choose a selfie image...", type=["jpg", "jpeg", "png"])
|
| 18 |
+
|
| 19 |
+
if uploaded_file is not None:
|
| 20 |
+
img = Image.open(uploaded_file).convert("RGB")
|
| 21 |
+
st.image(img, caption="Your Uploaded Selfie", use_container_width=True)
|
| 22 |
+
|
| 23 |
+
# Save temporarily
|
| 24 |
+
with tempfile.NamedTemporaryFile(delete=False, suffix=".jpg") as tmp_file:
|
| 25 |
+
img.save(tmp_file.name)
|
| 26 |
+
image_path = tmp_file.name
|
| 27 |
+
|
| 28 |
+
# Analyze with DeepFace
|
| 29 |
+
with st.spinner("Analyzing your emotion..."):
|
| 30 |
+
result = DeepFace.analyze(img_path=image_path, actions=["emotion"], enforce_detection=False)
|
| 31 |
+
|
| 32 |
+
dominant_emotion = result[0]["dominant_emotion"] if isinstance(result, list) else result["dominant_emotion"]
|
| 33 |
+
dominant_emotion = dominant_emotion.lower()
|
| 34 |
+
|
| 35 |
+
st.success(f"😊 Detected Emotion: *{dominant_emotion.capitalize()}*")
|
| 36 |
+
|
| 37 |
+
# Ask OpenAI for Ayah for this emotion
|
| 38 |
+
prompt = f"""
|
| 39 |
+
Suggest a Qur'anic Ayah in Arabic for someone feeling '{dominant_emotion}'.
|
| 40 |
+
Include:
|
| 41 |
+
1) The Ayah in Arabic
|
| 42 |
+
2) Its English translation
|
| 43 |
+
3) A short, simple tafsir.
|
| 44 |
+
Be gentle and authentic.
|
| 45 |
+
"""
|
| 46 |
+
|
| 47 |
+
try:
|
| 48 |
+
response = client.chat.completions.create(
|
| 49 |
+
model="gpt-4o-mini",
|
| 50 |
+
messages=[{"role": "user", "content": prompt}]
|
| 51 |
+
)
|
| 52 |
+
|
| 53 |
+
output = response.choices[0].message.content
|
| 54 |
+
|
| 55 |
+
st.subheader("🕋 Qur'anic Guidance")
|
| 56 |
+
st.write(output)
|
| 57 |
+
|
| 58 |
+
except Exception as e:
|
| 59 |
+
st.error(f"❌ API Error: {e}")
|