Spaces:
Runtime error
Runtime error
| 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() | |