File size: 1,359 Bytes
9b34fa8
 
 
 
 
 
 
 
 
 
94e4de7
9b34fa8
 
 
 
94e4de7
9b34fa8
 
 
 
 
 
 
94e4de7
 
 
 
9b34fa8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8350ecc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# AUTOGENERATED! DO NOT EDIT! File to edit: ../app.ipynb.

# %% auto 0
__all__ = ['device', 'model', 'CLASS_LABELS', 'image', 'label', 'examples', 'intf', 'classify_emotions']

# %% ../app.ipynb 2
import gradio as gr 
import torch
from torch.nn.functional import softmax
import numpy as np
from PIL import Image

# %% ../app.ipynb 3
device = "cuda" if torch.cuda.is_available() else "cpu"

model = torch.load('model.pth', map_location=torch.device('cpu')).to(device)
model.eval()

# %% ../app.ipynb 4
CLASS_LABELS  = ['Anger', 'Disgust', 'Fear', 'Happy', 'Neutral', 'Sadness', "Surprise"]

# %% ../app.ipynb 5
def classify_emotions(im):
    im = np.array(im) 
    im = np.array(Image.fromarray(im).convert('L')) / 255
    im = im[..., np.newaxis]
    im = np.concatenate((im, im, im), 2)
    im = torch.tensor(im.transpose(2, 0, 1), dtype=torch.float32)
    prediction = model.forward(im[np.newaxis, ...].to(device))
    return dict(zip(CLASS_LABELS, *softmax(prediction, dim=1).tolist()))
    

# %% ../app.ipynb 6
image = gr.inputs.Image((48, 48))
label = gr.outputs.Label()
examples = ['happy.png', 'fear.png', 'anger.png']

intf = gr.Interface(fn=classify_emotions, 
                    inputs=image, 
                    outputs=label, 
                    title='Emotion classification',
                    examples=examples)
intf.launch(inline=False)