DheivaCodes's picture
Update app.py
89547ec verified
Raw History Blame Contribute Delete
3.25 kB
import gradio as gr
from deepface import DeepFace
from fer import FER
import numpy as np
import cv2
import torch
from transformers import pipeline
# Text emotion model
text_emotion = pipeline(
"text-classification",
model="j-hartmann/emotion-english-distilroberta-base",
return_all_scores=True
)
# FER model with MTCNN face detector
fer_detector = FER(mtcnn=True)
# -------- Image Emotion Detection --------
def detect_emotion_image(image):
if image is None:
return None, "No image provided."
# Convert image to RGB
img_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
try:
# Try DeepFace
results = DeepFace.analyze(img_rgb, actions=['emotion'], enforce_detection=False)
dominant = results[0]['dominant_emotion']
confidence = results[0]['emotion'][dominant]
return image, f"Emotion (DeepFace): {dominant.capitalize()} ({confidence:.1f}%)"
except Exception as e:
try:
# Fallback to FER
emotions = fer_detector.detect_emotions(img_rgb)
if not emotions:
return image, "No face detected."
# Draw bounding boxes and show top emotion
for face in emotions:
(x, y, w, h) = face["box"]
top_emotion = max(face["emotions"], key=face["emotions"].get)
confidence = face["emotions"][top_emotion]
cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)
cv2.putText(image, f"{top_emotion} ({confidence*100:.1f}%)", (x, y - 10),
cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 0), 2)
return image, f"Emotion (FER): {top_emotion.capitalize()} ({confidence*100:.1f}%)"
except Exception as fe:
return image, f"FER error: {str(fe)}"
# -------- Text Emotion Detection --------
def detect_emotion_text(text):
if not text.strip():
return "Please enter some text."
try:
results = text_emotion(text)[0]
top = max(results, key=lambda x: x['score'])
emotion = top['label']
confidence = top['score']
return f"Emotion from text: {emotion} ({confidence*100:.1f}%)"
except Exception as e:
return f"Error: {str(e)}"
# -------- Gradio UI --------
with gr.Blocks() as demo:
gr.Markdown("## 🧠 Zenify+ AI Emotion Tracker\nDetect emotions from images or text.")
with gr.Tab("📸 Image Emotion Detection"):
img_input = gr.Image(type="numpy", label="Upload an image")
img_result_image = gr.Image(label="Processed Image with Detections")
img_output_text = gr.Textbox(label="Detected Emotion")
img_button = gr.Button("Analyze Image")
img_button.click(fn=detect_emotion_image,
inputs=img_input,
outputs=[img_result_image, img_output_text])
with gr.Tab("💬 Text Emotion Detection"):
text_input = gr.Textbox(label="Enter a sentence")
text_output = gr.Textbox(label="Detected Emotion")
text_button = gr.Button("Analyze Text")
text_button.click(fn=detect_emotion_text,
inputs=text_input,
outputs=text_output)
demo.launch()