File size: 1,538 Bytes
fa9b186
 
c0c0bc8
 
 
fa9b186
86a21c2
fa9b186
 
 
 
 
 
 
 
2827bbc
 
 
fa9b186
2827bbc
fa9b186
c0c0bc8
 
1276556
 
 
 
c0c0bc8
 
 
030f87e
c0c0bc8
 
2827bbc
030f87e
 
86a21c2
c0c0bc8
 
 
 
 
 
 
 
 
 
 
66ffdb0
c0c0bc8
 
 
 
 
 
f27cf49
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
import torch
import torch.nn as nn
import torchvision.transforms as transforms
import gradio as gr
from PIL import Image

# Define the neural network model
class Net(nn.Module):
    def __init__(self):
        super(Net, self).__init__()
        self.fc1 = nn.Linear(28 * 28, 128)
        self.fc2 = nn.Linear(128, 64)
        self.fc3 = nn.Linear(64, 10)

    def forward(self, x):
        x = x.view(-1, 28 * 28)  # Flatten the input
        x = torch.relu(self.fc1(x))
        x = torch.relu(self.fc2(x))
        x = self.fc3(x)
        return torch.log_softmax(x, dim=1)

# Load the trained model
model = Net()
try:
    model.load_state_dict(torch.load('mnist_model.pth', map_location=torch.device('cpu')))
except Exception as e:
    print(f"Error loading model: {e}")
model.eval()

# Define the transform to preprocess the input image
transform = transforms.Compose([
    transforms.Grayscale(num_output_channels=1),
    transforms.Resize((28, 28)),
    transforms.ToTensor(),
    transforms.Normalize((0.5,), (0.5,))
])

# Define the prediction function
def predict(image):
    image = transform(image).unsqueeze(0)  # Add batch dimension
    with torch.no_grad():
        output = model(image)
        prediction = torch.argmax(output, dim=1).item()
    return prediction

# Create the Gradio interface
iface = gr.Interface(
    fn=predict, 
    inputs=gr.Image(shape=(28, 28), image_mode='L', invert_colors=False), 
    outputs="label",
    live=True
)

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