Srikanth0804's picture
Update app.py
9f1c1c4 verified
Raw History Blame Contribute Delete
4.91 kB
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("""
<style>
.subheader {
font-size: 22px;
font-weight: 600;
margin-top: 20px;
color: #2d3436;
}
.emotion-badge {
background-color: #ffeaa7;
color: #2d3436;
padding: 8px 16px;
border-radius: 25px;
display: inline-block;
font-weight: 600;
}
</style>
<div style="background: linear-gradient(to right, #4b6c7f, #182848); padding: 25px 10px; border-radius: 12px; text-align: center; margin-bottom: 25px;">
<h1 style="color: white; font-size: 38px; margin-bottom: 5px;">🎢 Emotion-Based Music Recommender</h1>
<p style="color: #dcdde1; font-size: 18px;">Detect emotions from facial expressions and get mood-matching music instantly</p>
</div>
""", 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"<div class='subheader'>🧠 Detected Emotion:</div>"
f"<div class='emotion-badge'>{emoji} {main_emotion}</div>",
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("""
<hr>
<div style='text-align:center; color: gray; font-size: 14px;'>
Developed by <b>Srikanth Gunti</b> | MCA Final Project | Nizam College, Osmania University
</div>
""", unsafe_allow_html=True)