from transformers import pipeline import cv2 import numpy as np from PIL import Image import gradio as gr # Load the Hugging Face pipeline pipe = pipeline("image-classification", model="dima806/facial_emotions_image_detection") # Load face detection model (Haar Cascade) face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_default.xml") # Emoji mapping for emotions emoji_mapping = { "disappointment": "😞", "sadness": "😢", "annoyance": "😠", "neutral": "😐", "disapproval": "👎", "realization": "😮", "nervousness": "😬", "approval": "👍", "joy": "😄", "anger": "😡", "embarrassment": "😳", "caring": "🤗", "remorse": "😔", "disgust": "🤢", "grief": "😥", "confusion": "😕", "relief": "😌", "desire": "😍", "admiration": "😌", "optimism": "😊", "fear": "😨", "love": "❤️", "excitement": "🎉", "curiosity": "🤔", "amusement": "😄", "surprise": "😲", "gratitude": "🙏", "pride": "🦁" } def preprocess_face(face_rgb): """ Preprocess the face for the pipeline. """ try: # Resize and normalize the face to match pipeline requirements face_resized = cv2.resize(face_rgb, (224, 224)) face_normalized = face_resized / 255.0 # Normalize pixel values (0-1) face_pil = Image.fromarray((face_normalized * 255).astype(np.uint8)) return face_pil except Exception: return None def classify_mood_from_frame(frame): """ Detect faces in the frame, classify emotion for each face, and annotate the frame. """ try: # Convert frame to grayscale for face detection gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) faces = face_cascade.detectMultiScale(gray, scaleFactor=1.3, minNeighbors=5) for (x, y, w, h) in faces: # Extract and preprocess the face face_rgb = frame[y:y + h, x:x + w] # Extract RGB region face_pil = preprocess_face(face_rgb) if face_pil is None: continue # Skip if preprocessing failed # Predict emotion using the Hugging Face pipeline result = pipe(face_pil) emotion_label = result[0]['label'] emotion_score = result[0]['score'] # Get the corresponding emoji emotion_emoji = emoji_mapping.get(emotion_label.lower(), "❓") # Draw rectangle and emotion label on the frame cv2.rectangle(frame, (x, y), (x + w, y + h), (255, 0, 0), 2) cv2.putText(frame, f"{emotion_label} {emotion_emoji} ({emotion_score:.2f})", (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (255, 255, 255), 2) # Convert frame to RGB for Gradio display return cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) except Exception: return None def process_webcam(frame): """ Main function to classify emotions from a webcam frame. """ if frame is None: return None # Return if no frame is provided # Classify the mood from the given frame annotated_frame = classify_mood_from_frame(frame) return annotated_frame # Gradio interface for real-time webcam inference # Gradio interface for real-time webcam inference def interface_webcam(): return gr.Interface( fn=process_webcam, inputs=gr.Video(format="webcam", streaming=True), # Fixed for Gradio's webcam input outputs=gr.Video(format="mp4"), # Explicitly specify output format live=True, # Enable live streaming title="Real-Time Mood Classifier 🎭", description="Use your webcam to detect emotions in real time with facial emotion detection." ) # Gradio interface for image-based inference def process_image(image): """ Classify emotion for an uploaded image. """ frame = np.array(image) return classify_mood_from_frame(frame) def interface_image(): return gr.Interface( fn=process_image, inputs=gr.Image(type="pil", label="Upload Image"), outputs=gr.Image(type="numpy", label="Emotion-Detected Image"), title="Image-Based Mood Classifier 😊", description="Upload an image to detect emotions on faces." ) # Tabbed interface for both webcam and image modes def main(): gr.TabbedInterface( [interface_webcam(), interface_image()], tab_names=["Webcam", "Image"], title="Emotion Detection Toolkit" ).launch() if __name__ == "__main__": main()