Spaces:
Running
on
Zero
Running
on
Zero
Create mnist_digits.py
Browse files- mnist_digits.py +43 -0
mnist_digits.py
ADDED
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
import spaces
|
3 |
+
from transformers import AutoImageProcessor, SiglipForImageClassification
|
4 |
+
from transformers.image_utils import load_image
|
5 |
+
from PIL import Image
|
6 |
+
import torch
|
7 |
+
|
8 |
+
# Load model and processor
|
9 |
+
model_name = "prithivMLmods/Mnist-Digits-SigLIP2"
|
10 |
+
model = SiglipForImageClassification.from_pretrained(model_name)
|
11 |
+
processor = AutoImageProcessor.from_pretrained(model_name)
|
12 |
+
|
13 |
+
@spaces.GPU
|
14 |
+
def classify_digit(image):
|
15 |
+
"""Predicts the digit in the given handwritten digit image."""
|
16 |
+
image = Image.fromarray(image).convert("RGB")
|
17 |
+
inputs = processor(images=image, return_tensors="pt")
|
18 |
+
|
19 |
+
with torch.no_grad():
|
20 |
+
outputs = model(**inputs)
|
21 |
+
logits = outputs.logits
|
22 |
+
probs = torch.nn.functional.softmax(logits, dim=1).squeeze().tolist()
|
23 |
+
|
24 |
+
labels = {
|
25 |
+
"0": "0", "1": "1", "2": "2", "3": "3", "4": "4",
|
26 |
+
"5": "5", "6": "6", "7": "7", "8": "8", "9": "9"
|
27 |
+
}
|
28 |
+
predictions = {labels[str(i)]: round(probs[i], 3) for i in range(len(probs))}
|
29 |
+
|
30 |
+
return predictions
|
31 |
+
|
32 |
+
# Create Gradio interface
|
33 |
+
iface = gr.Interface(
|
34 |
+
fn=classify_digit,
|
35 |
+
inputs=gr.Image(type="numpy"),
|
36 |
+
outputs=gr.Label(label="Prediction Scores"),
|
37 |
+
title="MNIST Digit Classification 🔢",
|
38 |
+
description="Upload a handwritten digit image (0-9) to recognize it using MNIST-Digits-SigLIP2."
|
39 |
+
)
|
40 |
+
|
41 |
+
# Launch the app
|
42 |
+
if __name__ == "__main__":
|
43 |
+
iface.launch()
|