Spaces:
Running
Running
Download app.py from 2003Rohansinha/chexnet-api: direct link, hf CLI and curl.
- Browser
- Download file 2.51 kB
-
https://huggingface.co/spaces/2003Rohansinha/chexnet-api/resolve/main/app.py
- Command line
-
hf download hf://spaces/2003Rohansinha/chexnet-api/app.py
-
curl -L -o app.py https://huggingface.co/spaces/2003Rohansinha/chexnet-api/resolve/main/app.py
2.51 kB
| from flask import Flask, request, jsonify | |
| from flask_cors import CORS | |
| import torch | |
| import torch.nn as nn | |
| import torchvision.models as models | |
| import torchvision.transforms as T | |
| from PIL import Image | |
| import io | |
| app = Flask(__name__) | |
| CORS(app) | |
| CLASSES = [ | |
| 'Atelectasis','Consolidation','Infiltration','Pneumothorax', | |
| 'Edema','Emphysema','Fibrosis','Effusion','Pneumonia', | |
| 'Pleural_Thickening','Cardiomegaly','Nodule','Mass','Hernia' | |
| ] | |
| class CheXNet(nn.Module): | |
| def __init__(self, num_classes=14): | |
| super().__init__() | |
| self.net = models.densenet121(pretrained=False) | |
| in_feats = self.net.classifier.in_features | |
| self.net.classifier = nn.Sequential( | |
| nn.Linear(in_feats, 512), | |
| nn.BatchNorm1d(512), | |
| nn.ReLU(inplace=True), | |
| nn.Dropout(0.3), | |
| nn.Linear(512, num_classes) | |
| ) | |
| def forward(self, x): | |
| return self.net(x) | |
| print("Loading model...") | |
| model = CheXNet(num_classes=14) | |
| state = torch.load('best_chexnet_v2.pth', | |
| map_location='cpu', | |
| weights_only=False) | |
| # Fix DataParallel 'module.' prefix | |
| state_dict = state['model_state_dict'] | |
| new_state_dict = {} | |
| for k, v in state_dict.items(): | |
| new_key = k.replace('module.', '') # remove the 'module.' prefix | |
| new_state_dict[new_key] = v | |
| model.load_state_dict(new_state_dict) | |
| model.eval() | |
| print("Model ready!") | |
| model.eval() | |
| print("Model ready!") | |
| transform = T.Compose([ | |
| T.Resize((224, 224)), | |
| T.ToTensor(), | |
| T.Normalize([0.485, 0.456, 0.406], | |
| [0.229, 0.224, 0.225]) | |
| ]) | |
| def health(): | |
| return jsonify({'status': 'CheXNet API running'}) | |
| def predict(): | |
| if 'file' not in request.files: | |
| return jsonify({'error': 'No file uploaded'}), 400 | |
| try: | |
| file = request.files['file'] | |
| image = Image.open(io.BytesIO(file.read())).convert('RGB') | |
| tensor = transform(image).unsqueeze(0) | |
| with torch.no_grad(): | |
| probs = torch.sigmoid(model(tensor)).squeeze().tolist() | |
| results = [ | |
| {'disease': c, 'probability': round(p, 4)} | |
| for c, p in zip(CLASSES, probs) | |
| ] | |
| results.sort(key=lambda x: -x['probability']) | |
| return jsonify({'predictions': results, 'status': 'success'}) | |
| except Exception as e: | |
| return jsonify({'error': str(e)}), 500 | |
| if __name__ == '__main__': | |
| app.run(host='0.0.0.0', port=7860) |