import gradio as gr import os import cv2 import numpy as np import imutils from keras.preprocessing.image import img_to_array from keras.models import load_model # Load the pre-trained models and define parameters detection_model_path = 'haarcascade_files/haarcascade_frontalface_default.xml' emotion_model_path = 'model4_0.83/model4_entire_model.h5' face_detection = cv2.CascadeClassifier(detection_model_path) emotion_classifier = load_model(emotion_model_path, compile=False) EMOTIONS = ['neutral', 'happiness', 'surprise', 'sadness', 'anger', 'disgust', 'fear', 'contempt', 'unknown'] # face_detector_mtcnn = MTCNN() classifier = load_model(emotion_model_path) def predict_emotion(image): # Convert the image to grayscale gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # Detect faces in the grayscale image faces = face_detection.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30), flags=cv2.CASCADE_SCALE_IMAGE) confidences = {} for (x, y, w, h) in faces: # Extract the region of interest (ROI) roi_gray = gray[y:y+h, x:x+w] roi_gray = cv2.resize(roi_gray, (48, 48), interpolation=cv2.INTER_AREA) # Preprocess the ROI for prediction img = roi_gray.astype('float') / 255.0 img = img_to_array(img) img = np.expand_dims(img, axis=0) # Make a prediction for the emotion prediction = emotion_classifier.predict(img)[0] confidences = {EMOTIONS[i]: float(prediction[i]) for i in range(len(EMOTIONS))} return confidences demo = gr.Interface( fn = predict_emotion, inputs = gr.Image(type="numpy"), outputs = gr.Label(num_top_classes=9), #flagging_options=["blurry", "incorrect", "other"], examples = [ os.path.join(os.path.dirname(__file__), "images/chandler.jpeg"), os.path.join(os.path.dirname(__file__), "images/janice.jpeg"), os.path.join(os.path.dirname(__file__), "images/joey.jpeg"), os.path.join(os.path.dirname(__file__), "images/phoebe.jpeg"), os.path.join(os.path.dirname(__file__), "images/rachel_monica.jpeg"), os.path.join(os.path.dirname(__file__), "images/ross.jpeg"), os.path.join(os.path.dirname(__file__), "images/gunther.jpeg") ], title = "Whatchu feeling?", theme = "shivi/calm_seafoam" ) if __name__ == "__main__": demo.launch()