masto commited on
Commit
28b6880
1 Parent(s): 63180ca

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +50 -0
app.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ #import streamlit as st
3
+ from torchvision import transforms
4
+ import torch
5
+ import json
6
+ from torch import nn
7
+ from torchvision import models
8
+ from PIL import Image
9
+ from torch.nn import functional as F
10
+
11
+ # load idx_to_class.json into dictionary
12
+ with open('class_to_idx.json', 'r') as f:
13
+ class_to_idx = json.load(f)
14
+
15
+ idx_to_class = {v: k for k, v in class_to_idx.items()}
16
+
17
+ device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
18
+
19
+ # model
20
+ model = models.resnet18(pretrained=True)
21
+ num_ftrs = model.fc.in_features
22
+ model.fc = nn.Linear(num_ftrs, len(idx_to_class))
23
+ model.load_state_dict(torch.load('gardenbirds.pth', map_location=torch.device('cpu')))
24
+ model.eval()
25
+
26
+ data_transforms = {
27
+ 'val': transforms.Compose([
28
+ transforms.Resize(256),
29
+ transforms.CenterCrop(224),
30
+ transforms.ToTensor(),
31
+ transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
32
+ ]),
33
+ }
34
+
35
+ def predict(inp):
36
+ # transform pil image to tensor
37
+ inp = data_transforms['val'](inp).unsqueeze(0)
38
+ with torch.no_grad():
39
+ prediction = torch.nn.functional.softmax(model(inp)[0], dim=0)
40
+ #print(prediction)
41
+ confidences = {idx_to_class[i]: float(prediction[i]) for i in range(26)}
42
+ return confidences
43
+
44
+ interface = gr.Interface(fn=predict,
45
+ inputs=gr.Image(type="pil"),
46
+ outputs=gr.Label(num_top_classes=3),
47
+ title="What garden bird is this?",
48
+ examples=["gardenbirds/Parus major/345c506a-6ed5-4f9c-a7d3-4d0cb4af88fc.jpg"])
49
+
50
+ interface.launch(share=True)