PeterYoung777
commited on
Commit
•
e2c3f43
1
Parent(s):
71b93be
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import json
|
3 |
+
|
4 |
+
import torch
|
5 |
+
from PIL import Image
|
6 |
+
from torchvision import transforms
|
7 |
+
import matplotlib.pyplot as plt
|
8 |
+
|
9 |
+
from model import efficientnetv2_m as create_model
|
10 |
+
|
11 |
+
|
12 |
+
|
13 |
+
def predict(img):
|
14 |
+
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
|
15 |
+
|
16 |
+
img_size = {"s": [300, 384], # train_size, val_size
|
17 |
+
"m": [384, 480],
|
18 |
+
"l": [384, 480]}
|
19 |
+
num_model = "s"
|
20 |
+
|
21 |
+
data_transform = transforms.Compose(
|
22 |
+
[transforms.Resize(img_size[num_model][1]),
|
23 |
+
transforms.CenterCrop(img_size[num_model][1]),
|
24 |
+
transforms.ToTensor(),
|
25 |
+
transforms.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5])])
|
26 |
+
img = data_transform(img)
|
27 |
+
# expand batch dimension
|
28 |
+
img = torch.unsqueeze(img, dim=0)
|
29 |
+
json_path = './class_indices.json'
|
30 |
+
json_file = open(json_path, "r")
|
31 |
+
class_indict = json.load(json_file)
|
32 |
+
model = create_model(num_classes=5).to(device)
|
33 |
+
model_weight_path = "./weights/model-20.pth"
|
34 |
+
model.load_state_dict(torch.load(model_weight_path, map_location=device))
|
35 |
+
model.eval()
|
36 |
+
with torch.no_grad():
|
37 |
+
# predict class
|
38 |
+
output = torch.squeeze(model(img.to(device))).cpu()
|
39 |
+
predict = torch.softmax(output, dim=0)
|
40 |
+
predict_cla = torch.argmax(predict).numpy()
|
41 |
+
print_res = "class: {} prob: {:.3}".format(class_indict[str(predict_cla)],
|
42 |
+
predict[predict_cla].numpy())
|
43 |
+
return print_res
|
44 |
+
|
45 |
+
import gradio as gr
|
46 |
+
|
47 |
+
gr.Interface(fn=predict,
|
48 |
+
inputs=gr.inputs.Image(type="pil"),
|
49 |
+
outputs=gr.outputs.Label(num_top_classes=5),
|
50 |
+
theme="default").launch()
|