Spaces:
Runtime error
Runtime error
| import torch | |
| from torchvision import models, transforms | |
| from PIL import Image | |
| import gradio as gr | |
| # Updated class names with 'plaque' in front of 'calculus' and 'gingivitis' | |
| class_names = [ | |
| "plaque_calculus", | |
| "caries", | |
| "plaque_gingivitis", | |
| "hypodontia", | |
| "mouth_ulcer", | |
| "tooth_discoloration" | |
| ] | |
| model = models.resnet50(weights=None) | |
| model.fc = torch.nn.Linear(model.fc.in_features, len(class_names)) | |
| model.load_state_dict(torch.load('tooth_model.pth', map_location=torch.device('cpu'))) | |
| model.eval() | |
| preprocess = transforms.Compose([ | |
| transforms.Resize((224, 224)), | |
| transforms.ToTensor(), | |
| transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]), | |
| ]) | |
| def predict_image(image): | |
| processed_image = preprocess(image).unsqueeze(0) | |
| with torch.no_grad(): | |
| outputs = model(processed_image) | |
| probabilities = torch.nn.functional.softmax(outputs, dim=1) | |
| top_probs, top_indices = torch.topk(probabilities, 2) | |
| top_classes = [class_names[idx] for idx in top_indices[0]] | |
| # Create a result dictionary with class names and probabilities | |
| result = {top_classes[i]: top_probs[0][i].item() for i in range(2)} | |
| return result | |
| iface = gr.Interface( | |
| fn=predict_image, | |
| inputs=gr.Image(type="pil"), | |
| outputs="label", | |
| title="Medical Image Classification", | |
| description="Upload an image to predict its class with probabilities of top 2 predictions." | |
| ) | |
| iface.launch() | |