Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from pathlib import Path
|
2 |
+
|
3 |
+
import torch
|
4 |
+
import gradio as gr
|
5 |
+
from torch import nn
|
6 |
+
from PIL import Image
|
7 |
+
import numpy as np
|
8 |
+
|
9 |
+
LABELS = Path('class_names.txt').read_text().splitlines()
|
10 |
+
|
11 |
+
model = nn.Sequential(
|
12 |
+
nn.Conv2d(1, 32, 3, padding='same'),
|
13 |
+
nn.ReLU(),
|
14 |
+
nn.MaxPool2d(2),
|
15 |
+
nn.Conv2d(32, 64, 3, padding='same'),
|
16 |
+
nn.ReLU(),
|
17 |
+
nn.MaxPool2d(2),
|
18 |
+
nn.Conv2d(64, 128, 3, padding='same'),
|
19 |
+
nn.ReLU(),
|
20 |
+
nn.MaxPool2d(2),
|
21 |
+
nn.Flatten(),
|
22 |
+
nn.Linear(1152, 256),
|
23 |
+
nn.ReLU(),
|
24 |
+
nn.Linear(256, len(LABELS)),
|
25 |
+
)
|
26 |
+
state_dict = torch.load('pytorch_model.bin', map_location='cpu')
|
27 |
+
model.load_state_dict(state_dict, strict=False)
|
28 |
+
model.eval()
|
29 |
+
|
30 |
+
def predict(im_dict):
|
31 |
+
im_raw = im_dict['composite'][:,:,3]
|
32 |
+
img = Image.fromarray(im_raw)
|
33 |
+
img_small = img.resize([24,28],resample=0)
|
34 |
+
im = np.array(np.uint8(img_small))
|
35 |
+
im = np.transpose(im,(1,0))
|
36 |
+
x = torch.tensor(im, dtype=torch.float32).unsqueeze(0).unsqueeze(0) / 255.
|
37 |
+
|
38 |
+
with torch.no_grad():
|
39 |
+
out = model(x)
|
40 |
+
|
41 |
+
probabilities = torch.nn.functional.softmax(out[0], dim=0)
|
42 |
+
|
43 |
+
values, indices = torch.topk(probabilities, 5)
|
44 |
+
|
45 |
+
return {LABELS[i]: v.item() for i, v in zip(indices, values)}
|
46 |
+
|
47 |
+
interface = gr.Interface(
|
48 |
+
predict,
|
49 |
+
inputs="sketchpad",
|
50 |
+
outputs='label',
|
51 |
+
title="Sketch Recognition",
|
52 |
+
description="Who wants to play Pictionary? Draw a common object like a shovel or a laptop, and the algorithm will guess in real time!",
|
53 |
+
article = "<p style='text-align: center'>Sketch Recognition | Demo Model</p>",
|
54 |
+
live=True)
|
55 |
+
interface.launch(debug=True)
|