| | import os |
| | os.environ["KERAS_BACKEND"] = "jax" |
| |
|
| | import gradio as gr |
| | import keras |
| | import numpy as np |
| | import cv2 |
| | from PIL import Image |
| | import io |
| | from huggingface_hub import hf_hub_download |
| |
|
| | |
| | model = None |
| | desired_emotions = ['happy', 'sad', 'neutral'] |
| | original_emotion_labels = ['angry', 'disgust', 'fear', 'happy', 'sad', 'surprise', 'neutral'] |
| | desired_indices = [original_emotion_labels.index(emotion) for emotion in desired_emotions] |
| |
|
| | |
| | def load_emotion_model(): |
| | global model |
| | try: |
| | print("π Downloading model from HuggingFace Hub...") |
| | model_path = hf_hub_download(repo_id="Shees7/facial_model", filename="emotion_model.keras") |
| | print("β
Model file downloaded at:", model_path) |
| | model = keras.saving.load_model(model_path) |
| | print("β
Model loaded successfully.") |
| | except Exception as e: |
| | print("β Failed to load model:", str(e)) |
| |
|
| | |
| | load_emotion_model() |
| |
|
| | |
| | def preprocess_face(image): |
| | try: |
| | np_img = np.array(image.convert('RGB')) |
| | face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml') |
| | gray = cv2.cvtColor(np_img, cv2.COLOR_RGB2GRAY) |
| | faces = face_cascade.detectMultiScale(gray, 1.1, 4) |
| |
|
| | if len(faces) == 0: |
| | return None |
| |
|
| | x, y, w, h = faces[0] |
| | face = np_img[y:y+h, x:x+w] |
| | face_resized = cv2.resize(face, (224, 224)) |
| | face_normalized = face_resized / 255.0 |
| | face_expanded = np.expand_dims(face_normalized, axis=0) |
| | return face_expanded |
| | except Exception as e: |
| | print("β Error during preprocessing:", str(e)) |
| | return None |
| |
|
| | |
| | def predict_emotion(image): |
| | if model is None: |
| | return "Model not loaded." |
| |
|
| | processed_face = preprocess_face(image) |
| | if processed_face is None: |
| | return "neutral" |
| |
|
| | predictions = model.predict(processed_face)[0] |
| | filtered_predictions = [predictions[i] for i in desired_indices] |
| | predicted_index = np.argmax(filtered_predictions) |
| | predicted_emotion = desired_emotions[predicted_index] |
| | return predicted_emotion |
| |
|
| | |
| | iface = gr.Interface( |
| | fn=predict_emotion, |
| | inputs=gr.Image(type="pil"), |
| | outputs=gr.Text(label="Predicted Emotion"), |
| | title="Facial Emotion Recognition", |
| | description="Upload an image with a visible face. The model predicts one of: happy, sad, or neutral." |
| | ) |
| |
|
| | |
| | if __name__ == "__main__": |
| | iface.launch() |
| |
|