akhaliq HF staff commited on
Commit
2dac6df
1 Parent(s): 7600912

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +60 -0
app.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from PIL import Image
3
+ from torchvision import transforms
4
+ import gradio as gr
5
+ import os
6
+
7
+ os.system("wget https://raw.githubusercontent.com/pytorch/hub/master/imagenet_classes.txt")
8
+
9
+ # get list of models
10
+ torch.hub.list('zhanghang1989/ResNeSt', force_reload=True)
11
+ # load pretrained models, using ResNeSt-50 as an example
12
+ model = torch.hub.load('zhanghang1989/ResNeSt', 'resnest50', pretrained=True)
13
+ model.eval()
14
+ # Download an example image from the pytorch website
15
+ torch.hub.download_url_to_file("https://github.com/pytorch/hub/raw/master/images/dog.jpg", "dog.jpg")
16
+ # sample execution (requires torchvision)
17
+
18
+
19
+
20
+ def inference(input_image):
21
+ preprocess = transforms.Compose([
22
+ transforms.Resize(256),
23
+ transforms.CenterCrop(224),
24
+ transforms.ToTensor(),
25
+ transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
26
+ ])
27
+ input_tensor = preprocess(input_image)
28
+ input_batch = input_tensor.unsqueeze(0) # create a mini-batch as expected by the model
29
+
30
+ # move the input and model to GPU for speed if available
31
+ if torch.cuda.is_available():
32
+ input_batch = input_batch.to('cuda')
33
+ model.to('cuda')
34
+
35
+ with torch.no_grad():
36
+ output = model(input_batch)
37
+ # The output has unnormalized scores. To get probabilities, you can run a softmax on it.
38
+ probabilities = torch.nn.functional.softmax(output[0], dim=0)
39
+
40
+ # Read the categories
41
+ with open("imagenet_classes.txt", "r") as f:
42
+ categories = [s.strip() for s in f.readlines()]
43
+ # Show top categories per image
44
+ top5_prob, top5_catid = torch.topk(probabilities, 5)
45
+ result = {}
46
+ for i in range(top5_prob.size(0)):
47
+ result[categories[top5_catid[i]]] = top5_prob[i].item()
48
+ return result
49
+
50
+ inputs = gr.inputs.Image(type='pil')
51
+ outputs = gr.outputs.Label(type="confidences",num_top_classes=5)
52
+
53
+ title = "RESNEST"
54
+ description = "Gradio demo for RESNEST, A new ResNet variant. To use it, simply upload your image, or click one of the examples to load them. Read more at the links below."
55
+ article = "<p style='text-align: center'><a href='https://arxiv.org/abs/2004.08955'>ResNeSt: Split-Attention Networks</a> | <a href='https://github.com/zhanghang1989/ResNeSt'>Github Repo</a></p>"
56
+
57
+ examples = [
58
+ ['dog.jpg']
59
+ ]
60
+ gr.Interface(inference, inputs, outputs, title=title, description=description, article=article, examples=examples, analytics_enabled=False).launch()