File size: 1,682 Bytes
cd87932
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
45
46
47
48
49
50
51
52
53
54
55
56
import gradio as gr 
import numpy as np
import onnxruntime as ort
from PIL import Image 

session = ort.InferenceSession(
    "dog_emotion_classifier.onnx",
    providers=["CPUExecutionProvider"]
)


def normalize_image(image):
    
    mean = np.array([0.485, 0.456, 0.406])
    std = np.array([0.229, 0.224, 0.225])
    image[0] = (image[0] - mean[0]) / std[0]
    image[1] = (image[1] - mean[1]) / std[1]
    image[2] = (image[2] - mean[2]) / std[2]
    return image

def preprocess_image(image, is_link = False):
    
    image = image.resize((288, 288),Image.BICUBIC)
    image = np.array(image).astype(np.float32) 
    image = normalize_image(image)
    return image
def predict(image_path , is_link = False):
    image = preprocess_image(image_path , is_link)
 
    image = np.reshape(image , (1, 3, 288, 288))
    input_name = session.get_inputs()[0].name
    outputs = session.run([session.get_outputs()[0].name], {input_name: image})
    predictions = outputs[0]
    probs = np.exp(predictions) / np.sum(np.exp(predictions))
    probs = probs.flatten()
    probs = probs.tolist()
    to_plot  = {'angry':probs[0], 'happy':probs[1], 'relaxed':probs[2], 'sad':probs[3]}
    
    return to_plot


with gr.Blocks() as demo : 
    gr.Markdown("**Dog Emotion Classifier**")
    with gr.Row():
        with gr.Column():
            gr.Markdown("Upload an image of a dog to predict its emotion.")
            dog_image  = gr.Image(type="pil")
            button = gr.Button("Predict")
        
        with gr.Column():
            gr.Markdown("Results")
            text_out = gr.Label()
        value = button.click(predict, inputs=[dog_image], outputs=text_out)


demo.launch()