File size: 1,603 Bytes
46274ff
bb9fde7
c096457
21ef691
46274ff
c096457
 
 
 
 
 
 
 
21ef691
 
 
 
af88cea
21ef691
1effd41
c096457
 
1effd41
 
 
c096457
21ef691
 
 
1effd41
21ef691
 
1effd41
21ef691
 
 
 
 
1effd41
21ef691
1effd41
21ef691
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import streamlit as st
import numpy as np
from PIL import Image
from transformers import pipeline

# Set the page config
st.set_page_config(page_title="Emotion Recognition App", layout="centered")

st.title("Emotion Recognition App")

# Upload an image
uploaded_file = st.file_uploader("Upload an image", type=["jpg", "jpeg", "png"])

# Allocate the Hugging Face pipeline
@st.cache_resource  # Cache the model to avoid reloading it
def load_model():
    return pipeline("image-classification", model="Xenova/facial_emotions_image_detection")

emotion_classifier = load_model()

# Process the uploaded image
if uploaded_file is not None:
    # Check file size to prevent loading large images
    if uploaded_file.size > 10 * 1024 * 1024:  # 10 MB limit
        st.error("File too large. Please upload an image smaller than 10 MB.")
    else:
        # Open and preprocess the image
        image = Image.open(uploaded_file).convert("RGB")
        image_resized = image.resize((224, 224))  # Resize to match model input size

        # Convert image to numpy array and predict emotion
        predictions = emotion_classifier(image_resized)

        # Extract the top prediction
        if predictions:
            top_prediction = predictions[0]  # Assuming the model returns a list of predictions
            emotion = top_prediction["label"]
            confidence = top_prediction["score"]

            st.image(image, caption=f"Detected Emotion: {emotion} (Confidence: {confidence:.2f})", use_column_width=True)
        else:
            st.warning("Unable to determine emotion. Try another image.")