File size: 1,995 Bytes
81a6137
 
 
 
 
d1d4583
 
81a6137
d1d4583
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81a6137
d1d4583
81a6137
d1d4583
d1888a8
d1d4583
 
 
 
 
81a6137
d1d4583
81a6137
d1d4583
 
 
 
 
 
81a6137
d1d4583
 
81a6137
a0962d2
81a6137
d1d4583
 
81a6137
 
 
 
d1d4583
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
import gradio as gr
import torch
from torchvision import transforms
from PIL import Image

# Load the model using PyTorch
model_path = "https://huggingface.co/immartian/improved_digits_recognition/resolve/main/pytorch_model.bin"

# Define your ImageClassifier model architecture (same as used during training)
class ImageClassifier(torch.nn.Module):
    def __init__(self):
        super().__init__()
        self.model = torch.nn.Sequential(
            torch.nn.Conv2d(1, 32, (3, 3)),
            torch.nn.ReLU(),
            torch.nn.Conv2d(32, 64, (3, 3)),
            torch.nn.ReLU(),
            torch.nn.Conv2d(64, 64, (3, 3)),
            torch.nn.ReLU(),
            torch.nn.AdaptiveAvgPool2d((1, 1)),
            torch.nn.Flatten(),
            torch.nn.Linear(64, 10)
        )
    
    def forward(self, x):
        return self.model(x)

# Instantiate the model and load weights
model = ImageClassifier()
model.load_state_dict(torch.hub.load_state_dict_from_url(model_path))
model.eval()

# Gradio preprocessing and prediction pipeline
def predict_digit(image):
    # Preprocess the image: resize to 28x28, convert to grayscale, and normalize
    image = Image.fromarray(image).convert('L')  # Convert to grayscale
    transform = transforms.Compose([
        transforms.Resize((28, 28)),
        transforms.ToTensor(),
        transforms.Normalize((0.5,), (0.5,))
    ])
    
    img_tensor = transform(image).unsqueeze(0)  # Add batch dimension

    # Pass through the model
    with torch.no_grad():
        output = model(img_tensor)
        predicted_label = torch.argmax(output, dim=1).item()
    
    return f"Predicted Label: {predicted_label}"

# Create Gradio Interface
interface = gr.Interface(
    fn=predict_digit,
    inputs=gr.Sketchpad(),  # Sketchpad for users to draw
    outputs="text",
    title="Digit Recognizer",
    description="Draw a digit (0-9) and the model will predict the number!"
)

# Launch the app
if __name__ == "__main__":
    interface.launch()