Marwa-Khan commited on
Commit ·
1efb530
1
Parent(s): e0c43c7
added requirements and application file
Browse files- app.py +55 -0
- requirements.txt +4 -0
app.py
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import torch
|
| 3 |
+
import torch.nn.functional as F
|
| 4 |
+
from transformers import ViTImageProcessor, ViTForImageClassification
|
| 5 |
+
from PIL import Image
|
| 6 |
+
import numpy as np
|
| 7 |
+
|
| 8 |
+
MODEL_NAME = "mo-thecreator/vit-Facial-Expression-Recognition"
|
| 9 |
+
EMOTIONS = ["Angry", "Disgust", "Fear", "Happy", "Sad", "Surprise", "Neutral"]
|
| 10 |
+
|
| 11 |
+
# Load model and processor
|
| 12 |
+
processor = ViTImageProcessor.from_pretrained(MODEL_NAME)
|
| 13 |
+
model = ViTForImageClassification.from_pretrained(MODEL_NAME)
|
| 14 |
+
model.eval()
|
| 15 |
+
|
| 16 |
+
def analyze_emotion(image):
|
| 17 |
+
if image is None:
|
| 18 |
+
return "Upload an image", None
|
| 19 |
+
|
| 20 |
+
# Preprocess
|
| 21 |
+
if isinstance(image, np.ndarray):
|
| 22 |
+
image = Image.fromarray(image)
|
| 23 |
+
if image.mode != "RGB":
|
| 24 |
+
image = image.convert("RGB")
|
| 25 |
+
|
| 26 |
+
inputs = processor(images=image, return_tensors="pt")
|
| 27 |
+
with torch.no_grad():
|
| 28 |
+
outputs = model(**inputs)
|
| 29 |
+
probs = F.softmax(outputs.logits, dim=-1)[0].numpy()
|
| 30 |
+
|
| 31 |
+
# Get top emotion
|
| 32 |
+
top_idx = np.argmax(probs)
|
| 33 |
+
top_emotion = EMOTIONS[top_idx]
|
| 34 |
+
|
| 35 |
+
# Prepare bar chart
|
| 36 |
+
chart_data = {"emotion": EMOTIONS, "confidence": probs.tolist()}
|
| 37 |
+
|
| 38 |
+
result_text = f"Predicted Emotion: {top_emotion} ({probs[top_idx]*100:.1f}%)"
|
| 39 |
+
|
| 40 |
+
return result_text, chart_data
|
| 41 |
+
|
| 42 |
+
# Build Gradio interface
|
| 43 |
+
demo = gr.Interface(
|
| 44 |
+
fn=analyze_emotion,
|
| 45 |
+
inputs=gr.Image(type="pil", label="Upload Facial Image"),
|
| 46 |
+
outputs=[
|
| 47 |
+
gr.Textbox(label="Prediction"),
|
| 48 |
+
gr.BarPlot(x="emotion", y="confidence", y_lim=[0,1], label="Confidence")
|
| 49 |
+
],
|
| 50 |
+
title="Facial Expression Recognition (ViT)",
|
| 51 |
+
description="Upload a facial image and detect emotions (Angry, Disgust, Fear, Happy, Sad, Surprise, Neutral) using a Vision Transformer."
|
| 52 |
+
)
|
| 53 |
+
|
| 54 |
+
if __name__ == "__main__":
|
| 55 |
+
demo.launch(server_name="0.0.0.0", server_port=7860)
|
requirements.txt
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
gradio>=4.0.0
|
| 2 |
+
transformers>=4.36.0
|
| 3 |
+
torch>=2.0.0
|
| 4 |
+
pillow>=8.3.2
|