import streamlit as st
import tempfile
import os
import io
import base64
import requests
from PIL import Image
from Emotion_music_project.Graphical_Visualisation import Emotion_Analysis
from Emotion_music_project.camera import mood, activities, provide_url
# Page config
st.set_page_config(page_title="Emotion-Based Music Recommender", layout="wide")
# Header UI
st.markdown("""
🎶 Emotion-Based Music Recommender
Detect emotions from facial expressions and get mood-matching music instantly
""", unsafe_allow_html=True)
# Input method
st.sidebar.header("Choose Input Method")
option = st.sidebar.radio("", ["📁 Upload Image", "📸 Capture from Webcam", "🌐 Image URL"])
image = None
temp_path = os.path.join(tempfile.gettempdir(), "temp_image.jpg")
# Input logic
if option == "📁 Upload Image":
uploaded_file = st.sidebar.file_uploader("Upload an image", type=["jpg", "png", "jpeg"])
if uploaded_file:
image = Image.open(uploaded_file).convert("RGB")
image.save(temp_path)
elif option == "📸 Capture from Webcam":
img_file=st.sidebar.camera_input("Take a photo")
if img_file is not None:
try:
image=Image.open(img_file).convert("RGB")
image.save(temp_path)
except Exception as e:
st.error(f"Error processing captured image: {e}")
elif option == "🌐 Image URL":
url = st.sidebar.text_input("Paste image URL or base64 string:")
submit_url = st.sidebar.button("Submit URL")
if submit_url and url:
try:
url = url.strip()
if url.startswith("data:image"):
_, base64_data = url.split(",", 1)
image_bytes = base64.b64decode(base64_data)
image = Image.open(io.BytesIO(image_bytes)).convert("RGB")
elif url.lower().startswith(("http://", "https://")):
response = requests.get(url, stream=True)
if response.status_code == 200:
image = Image.open(response.raw).convert("RGB")
else:
st.error("Image fetch failed.")
else:
st.error("Invalid input format.")
if image:
image.save(temp_path)
except Exception as e:
st.error(f"Error loading image: {e}")
# Output section
if image:
try:
with st.spinner("🔍 Analyzing Emotion..."):
pie_base64, bar_base64, pred_summary, main_emotion = Emotion_Analysis(temp_path)
# Layout
st.markdown("---")
st.subheader("📈 Emotion Analysis Results")
col1, col2 = st.columns([1, 2])
with col1:
st.image(image, caption="Input Image", use_column_width=True)
with col2:
emotion_emojis = {
"happy": "😄", "sad": "😢", "angry": "😠", "surprise": "😲",
"neutral": "😐", "disgust": "🤢", "fear": "😨"
}
emoji = emotion_emojis.get(main_emotion, "🎭")
st.markdown(
f""
f"{emoji} {main_emotion}
",
unsafe_allow_html=True
)
st.snow()
st.write(pred_summary)
# Emotion charts
if pie_base64 and bar_base64:
st.subheader("📊 Emotion Distribution")
st.image(base64.b64decode(pie_base64))
st.image(base64.b64decode(bar_base64))
# Music Recommendation
with st.expander("🎵 View Music Recommendation"):
st.success(mood(main_emotion))
st.info(activities(main_emotion))
st.markdown(f"[▶️ Click here to listen]({provide_url(main_emotion)})", unsafe_allow_html=True)
except Exception as e:
st.error(f"Error during emotion analysis: {e}")
else:
st.info("Please upload or capture an image to start emotion detection.")
# Footer
st.markdown("""
Developed by Srikanth Gunti | MCA Final Project | Nizam College, Osmania University
""", unsafe_allow_html=True)