Spaces:
Sleeping
Sleeping
| import numpy as np | |
| from tensorflow.keras.preprocessing.image import img_to_array, load_img | |
| import gradio as gr | |
| import tensorflow as tf | |
| from PIL import Image | |
| # Load your pre-trained model | |
| model = tf.keras.models.load_model('./ResNet50_Transfer_Learning.keras') | |
| # Emotion labels dictionary | |
| emotion_labels = {'angry': 0, 'disgust': 1, 'fear': 2, 'happy': 3, 'neutral': 4, 'sad': 5, 'surprise': 6} | |
| index_to_emotion = {v: k for k, v in emotion_labels.items()} | |
| def prepare_image(img_pil): | |
| """Preprocess the PIL image to fit your model's input requirements.""" | |
| img = img_pil.resize((224, 224)) | |
| img_array = img_to_array(img) | |
| img_array = np.expand_dims(img_array, axis=0) # Convert single image to a batch. | |
| img_array /= 255.0 # Rescale pixel values to [0,1], as done during training | |
| return img_array | |
| # Define the prediction function | |
| def predict_emotion(image): | |
| processed_image = prepare_image(image) | |
| prediction = model.predict(processed_image) | |
| predicted_class = np.argmax(prediction, axis=1) | |
| predicted_emotion = index_to_emotion.get(predicted_class[0], "Unknown Emotion") | |
| return predicted_emotion | |
| # Define Gradio interface with a custom design | |
| interface = gr.Interface( | |
| fn=predict_emotion, # Your prediction function | |
| inputs=gr.Image(type="pil", label="Upload an Image"), # Input for uploading an image | |
| outputs=gr.Textbox(label="Detected Emotion"), # Output as text displaying the predicted emotion | |
| title="Emotion Detection", | |
| description="Upload an image and let the AI detect the emotion!", | |
| css=".output {font-size: 20px; font-weight: bold; text-align: center; color: #4CAF50;}", # Custom CSS for output styling | |
| allow_flagging="never" | |
| ).launch() | |