oxedanda commited on
Commit
fb2e3f6
·
verified ·
1 Parent(s): e0b4ddc

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +43 -9
app.py CHANGED
@@ -20,7 +20,7 @@ model.fc = nn.Linear(in_features=512, out_features=10)
20
  model.load_state_dict(torch.load("mnist_resnet18.pth", map_location=torch.device("cpu")))
21
  model.eval()
22
 
23
- def predict(img):
24
  x = data_transform(img).unsqueeze(0)
25
  with torch.no_grad():
26
  outputs = model(x).flatten()
@@ -28,14 +28,48 @@ def predict(img):
28
  confidences = {labels[i]: float(probs[i]) for i in range(len(labels))}
29
  return confidences
30
 
31
- demo = gr.Interface(
32
- fn=predict,
33
- inputs=gr.Image(type="pil"),
34
- outputs=gr.Label(num_top_classes=len(labels)),
35
- examples=[],
36
- title="MNIST Digit Classifier",
37
- description="Upload or draw a handwritten digit from 0 to 9."
38
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
 
40
  if __name__ == "__main__":
41
  demo.launch()
 
20
  model.load_state_dict(torch.load("mnist_resnet18.pth", map_location=torch.device("cpu")))
21
  model.eval()
22
 
23
+ def predict_pil(img):
24
  x = data_transform(img).unsqueeze(0)
25
  with torch.no_grad():
26
  outputs = model(x).flatten()
 
28
  confidences = {labels[i]: float(probs[i]) for i in range(len(labels))}
29
  return confidences
30
 
31
+ def predict_upload(img):
32
+ if img is None:
33
+ return None
34
+ return predict_pil(img)
35
+
36
+ def predict_draw(img):
37
+ if img is None:
38
+ return None
39
+ if isinstance(img, dict) and "composite" in img:
40
+ img = img["composite"]
41
+ return predict_pil(img)
42
+
43
+ with gr.Blocks() as demo:
44
+ gr.Markdown("# MNIST Digit Classifier")
45
+ gr.Markdown("Upload an image, use your webcam, or draw a digit from 0 to 9.")
46
+
47
+ with gr.Tab("Upload / Webcam"):
48
+ with gr.Row():
49
+ input_img = gr.Image(
50
+ type="pil",
51
+ sources=["upload", "webcam", "clipboard"],
52
+ label="Input image"
53
+ )
54
+ output_label = gr.Label(
55
+ num_top_classes=10,
56
+ label="Predicted probabilities"
57
+ )
58
+ submit_btn = gr.Button("Predict")
59
+ submit_btn.click(fn=predict_upload, inputs=input_img, outputs=output_label)
60
+
61
+ with gr.Tab("Draw digit"):
62
+ with gr.Row():
63
+ sketch = gr.Sketchpad(
64
+ type="pil",
65
+ label="Draw a digit here"
66
+ )
67
+ draw_output = gr.Label(
68
+ num_top_classes=10,
69
+ label="Predicted probabilities"
70
+ )
71
+ draw_btn = gr.Button("Predict drawing")
72
+ draw_btn.click(fn=predict_draw, inputs=sketch, outputs=draw_output)
73
 
74
  if __name__ == "__main__":
75
  demo.launch()