Spaces:
Sleeping
Sleeping
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 | |
# 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.") | |