Download app.py from ma4389/Covid_CLassification_Using_Torch: direct link, hf CLI and curl.
- Browser
- Download file 1.73 kB
-
https://huggingface.co/spaces/ma4389/Covid_CLassification_Using_Torch/resolve/main/app.py
- Command line
-
hf download hf://spaces/ma4389/Covid_CLassification_Using_Torch/app.py
-
curl -L -o app.py https://huggingface.co/spaces/ma4389/Covid_CLassification_Using_Torch/resolve/main/app.py
1.73 kB
| import gradio as gr | |
| import torch | |
| import torchvision.transforms as transforms | |
| from PIL import Image | |
| import torchvision.models as models | |
| import torch.nn as nn | |
| # 🔹 Device setup | |
| device = torch.device("cuda" if torch.cuda.is_available() else "cpu") | |
| # 🔹 Load ResNet50 and modify for 2-class output | |
| model = models.resnet50(weights=models.ResNet50_Weights.DEFAULT) | |
| in_features = model.fc.in_features | |
| model.fc = nn.Sequential( | |
| nn.Linear(in_features, 512), | |
| nn.ReLU(), | |
| nn.Dropout(0.4), | |
| nn.Linear(512, 2) # 2 classes: NORMAL, PNEUMONIA | |
| ) | |
| # 🔹 Load the trained model | |
| model.load_state_dict(torch.load("best_model (2).pth", map_location=device)) | |
| model.to(device) | |
| model.eval() | |
| # 🔹 Preprocessing - exactly matching your val_transforms | |
| transform = transforms.Compose([ | |
| transforms.Lambda(lambda img: img.convert("RGB")), # 🧠Force RGB | |
| transforms.Resize((224, 224)), | |
| transforms.ToTensor(), | |
| transforms.Normalize(mean=[0.5]*3, std=[0.5]*3) | |
| ]) | |
| # 🔹 Class labels | |
| class_names = ["NORMAL", "PNEUMONIA"] | |
| # 🔹 Inference function | |
| def classify_image(img): | |
| img = transform(img).unsqueeze(0).to(device) | |
| with torch.no_grad(): | |
| outputs = model(img) | |
| probs = torch.nn.functional.softmax(outputs, dim=1) | |
| return {class_names[i]: float(probs[0][i]) for i in range(len(class_names))} | |
| # 🔹 Gradio Interface | |
| interface = gr.Interface( | |
| fn=classify_image, | |
| inputs=gr.Image(type="pil"), | |
| outputs=gr.Label(num_top_classes=2), | |
| title="🩺 Pneumonia Classifier", | |
| description="Upload a chest X-ray image. The model predicts whether it's NORMAL or shows signs of PNEUMONIA." | |
| ) | |
| # 🔹 Launch the app | |
| interface.launch() | |