Spaces:
Build error
Build error
Create Pictionary/app.py
Browse files- Pictionary/app.py +47 -0
Pictionary/app.py
ADDED
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from pathlib import Path
|
2 |
+
|
3 |
+
import gradio as gr
|
4 |
+
import torch
|
5 |
+
from huggingface_hub import hf_hub_download
|
6 |
+
from torch import nn
|
7 |
+
|
8 |
+
LABELS = Path(hf_hub_download('nateraw/quickdraw', 'class_names.txt')).read_text().splitlines()
|
9 |
+
|
10 |
+
model = nn.Sequential(
|
11 |
+
nn.Conv2d(1, 32, 3, padding='same'),
|
12 |
+
nn.ReLU(),
|
13 |
+
nn.MaxPool2d(2),
|
14 |
+
nn.Conv2d(32, 64, 3, padding='same'),
|
15 |
+
nn.ReLU(),
|
16 |
+
nn.MaxPool2d(2),
|
17 |
+
nn.Conv2d(64, 128, 3, padding='same'),
|
18 |
+
nn.ReLU(),
|
19 |
+
nn.MaxPool2d(2),
|
20 |
+
nn.Flatten(),
|
21 |
+
nn.Linear(1152, 256),
|
22 |
+
nn.ReLU(),
|
23 |
+
nn.Linear(256, len(LABELS)),
|
24 |
+
)
|
25 |
+
weights_file = hf_hub_download('nateraw/quickdraw', 'pytorch_model.bin')
|
26 |
+
state_dict = torch.load(weights_file, map_location='cpu')
|
27 |
+
model.load_state_dict(state_dict, strict=False)
|
28 |
+
model.eval()
|
29 |
+
|
30 |
+
|
31 |
+
def predict(im):
|
32 |
+
x = torch.tensor(im, dtype=torch.float32).unsqueeze(0).unsqueeze(0) / 255.0
|
33 |
+
|
34 |
+
with torch.no_grad():
|
35 |
+
out = model(x)
|
36 |
+
|
37 |
+
probabilities = torch.nn.functional.softmax(out[0], dim=0)
|
38 |
+
|
39 |
+
values, indices = torch.topk(probabilities, 5)
|
40 |
+
|
41 |
+
return {LABELS[i]: v.item() for i, v in zip(indices, values)}
|
42 |
+
|
43 |
+
|
44 |
+
interface = gr.Interface(predict, inputs='sketchpad', outputs='label', live=True)
|
45 |
+
|
46 |
+
if __name__ == '__main__':
|
47 |
+
interface.launch(debug=True)
|