Spaces:
Sleeping
Sleeping
Download app.py from oxedanda/pml_Assignment_4: direct link, hf CLI and curl.
- Browser
- Download file 2.38 kB
-
https://huggingface.co/spaces/oxedanda/pml_Assignment_4/resolve/main/app.py
- Command line
-
hf download hf://spaces/oxedanda/pml_Assignment_4/app.py
-
curl -L -o app.py https://huggingface.co/spaces/oxedanda/pml_Assignment_4/resolve/main/app.py
2.38 kB
| 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() |