akhaliq HF staff commited on
Commit
5f94ab7
1 Parent(s): ef1a5dd

Create app.py

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