File size: 1,949 Bytes
cb5412b
 
 
 
 
 
 
 
 
1e9917c
 
 
 
cb5412b
 
 
 
1e9917c
 
 
cb5412b
1e9917c
cb5412b
1e9917c
 
cb5412b
1e9917c
cb5412b
 
 
 
 
1e9917c
 
 
 
 
 
 
 
 
 
cb5412b
1e9917c
 
cb5412b
1e9917c
 
 
 
 
 
 
 
 
 
cb5412b
1e9917c
 
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
57
58
59
import torch
import torchvision
from torchvision.models import efficientnet_v2_s, EfficientNet_V2_S_Weights

from torch import nn

from PIL import Image
from model import create_effnet_v2_model

import gradio as gr
import os
from timeit import default_timer as timer

class_names = ['Honda', 'Hyundai', 'Toyota']

effnet_v2, transforms = create_effnet_v2_model(num_classes=len(class_names), weights_path="efficient_net_s_carvision_3.pth")

def predict(image):

    start_time = timer()

    # image = Image.open(image_path)
    image = transforms(image).unsqueeze(0)
    # image = image.to(device)
    output = effnet_v2(image)
    
    effnet_v2.eval()
    with torch.inference_mode():
        probs = torch.softmax(output, dim=1)

    pred_labels_and_probs = {class_names[i]: float(probs[0, i]) for i in range(len(class_names))}

    pred_time = round(timer() - start_time, 5)
    return pred_labels_and_probs, pred_time


### 4. Gradio app ###

# Create title, description and article strings
title = "CarVision 🚗🚘🚙🏎️"
description = "An EfficientNetv2 model to classify cars as Honda, Hyundai or Toyota"
article = "Created by Akshay Ballal"

# Create examples list from "examples/" directory
example_list = [["examples/" + example] for example in os.listdir("examples")]

# Create the Gradio demo
demo = gr.Interface(fn=predict, # mapping function from input to output
                    inputs=gr.Image(type="pil"), # what are the inputs?
                    outputs=[gr.Label(num_top_classes=3, label="Predictions"), # what are the outputs?
                             gr.Number(label="Prediction time (s)")], # our fn has two outputs, therefore we have two outputs
                    # Create examples list from "examples/" directory
                    examples=example_list, 
                    title=title,
                    description=description,
                    article=article)

# Launch the demo!
demo.launch()