SakibRumu commited on
Commit
3d079da
·
verified ·
1 Parent(s): 4c30efd

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +49 -0
app.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import torch
3
+ from torchvision import models, transforms
4
+ from PIL import Image
5
+ import io
6
+
7
+ # Load the pre-trained model
8
+ model = models.resnet50(pretrained=False)
9
+ model.fc = torch.nn.Linear(2048, 7) # Adjust for the number of emotion categories
10
+ model.load_state_dict(torch.load('model/emotion_model.pth'))
11
+ model.eval()
12
+
13
+ # Define image transforms
14
+ transform = transforms.Compose([
15
+ transforms.Resize((224, 224)),
16
+ transforms.ToTensor(),
17
+ transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
18
+ ])
19
+
20
+ # Emotion classes (adjust based on your dataset)
21
+ emotions = ['angry', 'disgust', 'fear', 'happy', 'sad', 'surprise', 'neutral']
22
+
23
+ # Define the prediction function
24
+ def predict_emotion(image):
25
+ img = Image.open(io.BytesIO(image))
26
+ img = transform(img).unsqueeze(0) # Add batch dimension
27
+
28
+ with torch.no_grad():
29
+ output = model(img)
30
+ probs = torch.nn.functional.softmax(output, dim=1)
31
+ confidence, predicted_class = probs.max(1)
32
+
33
+ emotion = emotions[predicted_class.item()]
34
+ percentage = confidence.item() * 100
35
+ return emotion, f"{percentage:.2f}%"
36
+
37
+ # Set up the Gradio interface
38
+ iface = gr.Interface(
39
+ fn=predict_emotion,
40
+ inputs=gr.inputs.Image(type="bytes"),
41
+ outputs=[gr.outputs.Textbox(label="Predicted Emotion"), gr.outputs.Textbox(label="Confidence")],
42
+ live=True,
43
+ title="Emotion Classification",
44
+ description="Upload an image to predict the emotion expressed in the image using a fine-tuned ResNet50 model."
45
+ )
46
+
47
+ # Launch the app
48
+ if __name__ == "__main__":
49
+ iface.launch()