Spaces:
Sleeping
Sleeping
File size: 2,379 Bytes
3bff406 fb2e3f6 3bff406 fb2e3f6 3bff406 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 | import gradio as gr
import torch
from torch import nn
from torchvision import transforms
from torchvision.models import resnet18, ResNet18_Weights
from PIL import Image
labels = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
data_transform = transforms.Compose([
transforms.Resize((224, 224)),
transforms.Grayscale(num_output_channels=3),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225])
])
model = resnet18(weights=ResNet18_Weights.DEFAULT)
model.fc = nn.Linear(in_features=512, out_features=10)
model.load_state_dict(torch.load("mnist_resnet18.pth", map_location=torch.device("cpu")))
model.eval()
def predict_pil(img):
x = data_transform(img).unsqueeze(0)
with torch.no_grad():
outputs = model(x).flatten()
probs = torch.nn.functional.softmax(outputs, dim=0)
confidences = {labels[i]: float(probs[i]) for i in range(len(labels))}
return confidences
def predict_upload(img):
if img is None:
return None
return predict_pil(img)
def predict_draw(img):
if img is None:
return None
if isinstance(img, dict) and "composite" in img:
img = img["composite"]
return predict_pil(img)
with gr.Blocks() as demo:
gr.Markdown("# MNIST Digit Classifier")
gr.Markdown("Upload an image, use your webcam, or draw a digit from 0 to 9.")
with gr.Tab("Upload / Webcam"):
with gr.Row():
input_img = gr.Image(
type="pil",
sources=["upload", "webcam", "clipboard"],
label="Input image"
)
output_label = gr.Label(
num_top_classes=10,
label="Predicted probabilities"
)
submit_btn = gr.Button("Predict")
submit_btn.click(fn=predict_upload, inputs=input_img, outputs=output_label)
with gr.Tab("Draw digit"):
with gr.Row():
sketch = gr.Sketchpad(
type="pil",
label="Draw a digit here"
)
draw_output = gr.Label(
num_top_classes=10,
label="Predicted probabilities"
)
draw_btn = gr.Button("Predict drawing")
draw_btn.click(fn=predict_draw, inputs=sketch, outputs=draw_output)
if __name__ == "__main__":
demo.launch() |