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