Spaces:
Sleeping
Sleeping
Update Space
Browse files- app.py +34 -0
- requirements.txt +1 -0
app.py
CHANGED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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)}
|
requirements.txt
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
torch
|