File size: 1,371 Bytes
0f4688b
 
 
 
 
d97694e
0f4688b
 
 
 
ea90889
 
0f4688b
 
 
 
 
916a9e6
0f4688b
 
 
 
ea90889
 
 
 
5a71792
fabaf4d
5a71792
 
084ddd1
0f4688b
 
 
 
5af7084
 
0f4688b
 
d97694e
0f4688b
d97694e
0f4688b
09159ee
 
0f4688b
fabaf4d
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
import requests

import torch
import torchvision

import gradio as gr
import torch.nn.functional as F
import torchvision.transforms as T

# Get pre-trained model
weights = torchvision.models.ResNet18_Weights.IMAGENET1K_V1
model = torchvision.models.resnet18(weights=weights)

# Set model to evaluation mode
model.eval()

# Get ImageNet labels
r = requests.get("https://git.io/JJkYN")
labels = r.text.split("\n")

# Define prediction function
def predict(img):
    '''
    img: PIL image to be predicted
    confidences: python dictionary containing confidences
    '''
    # Transform image to pytorch tensor of shape [1, 3, 224, 224]
    # Put your image transforms here
    img = T.PILToTensor()(img).unsqueeze(0)
    img = T.Resize(size=(224, 224))(img)
    img = img / 255
    
    # Use model without gradients to reduce computation
    with torch.no_grad():
        # Get the tensor that contains the predictions
        out = model(img)
        prediction = F.softmax(out[0], dim=0)
        # Turn the above tensor into a dictionary with the humand-readable label and probability.
        confidences = {labels[i]: float(prediction[i]) for i in range(1000)}

    return confidences

gr.Interface(fn=predict,
             inputs=gr.Image(type="pil"),
             outputs=gr.Label(num_top_classes=10),
             theme="default",
            ).launch(share=False)