Download app.py from Prayag80/rd: direct link, hf CLI and curl.
- Browser
- Download file 4.49 kB
-
https://huggingface.co/spaces/Prayag80/rd/resolve/main/app.py
- Command line
-
hf download hf://spaces/Prayag80/rd/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Prayag80/rd/resolve/main/app.py
4.49 kB
| import os | |
| import io | |
| import numpy as np | |
| import torch | |
| import torch.nn as nn | |
| import torchvision.models as models | |
| import cv2 | |
| from fastapi import FastAPI, UploadFile, File | |
| from fastapi.middleware.cors import CORSMiddleware | |
| from fastapi.responses import JSONResponse | |
| # Model configuration | |
| CLASS_NAMES = ['No_DR', 'Mild', 'Moderate', 'Severe', 'Proliferative_DR'] | |
| IMAGE_SIZE = 512 | |
| DEVICE = 'cpu' # Hugging Face Spaces use CPU | |
| # Model architecture (must match training) | |
| class MobileNet_V3_Large(nn.Module): | |
| def __init__(self, num_classes=5): | |
| super(MobileNet_V3_Large, self).__init__() | |
| self.model = models.mobilenet_v3_large(weights=None) | |
| self.model.classifier[-1] = nn.Linear( | |
| self.model.classifier[-1].in_features, | |
| num_classes, | |
| bias=True | |
| ) | |
| def forward(self, x): | |
| return self.model(x) | |
| # Setup FastAPI App | |
| app = FastAPI(title="DR Detection API", version="1.0.0") | |
| # Enable CORS for the frontend to call this endpoint | |
| app.add_middleware( | |
| CORSMiddleware, | |
| allow_origins=["*"], # Allows all origins | |
| allow_credentials=True, | |
| allow_methods=["*"], # Allows all methods | |
| allow_headers=["*"], # Allows all headers | |
| ) | |
| # Global model variable | |
| model = None | |
| async def load_model(): | |
| """Load the trained model once at startup.""" | |
| global model | |
| model_path = "best_val_loss.pt" | |
| print(f"Loading model from: {model_path}") | |
| model = MobileNet_V3_Large(num_classes=5) | |
| model.load_state_dict(torch.load(model_path, map_location=DEVICE, weights_only=False)) | |
| model.to(DEVICE) | |
| model.eval() | |
| print(f"Model loaded on {DEVICE}") | |
| def remove_black_borders(img, black_th=5): | |
| img_t = img.copy() | |
| img_t = cv2.cvtColor(img_t, cv2.COLOR_RGB2GRAY) | |
| # x axis | |
| centre_y = img_t.shape[1] // 2 | |
| black_list = img_t[:, centre_y] | |
| black_list = np.where(black_list >= black_th)[0] | |
| if len(black_list) > 1: | |
| first_non_black = black_list[0] | |
| reverse_first_non_black = black_list[-1] + 1 | |
| img = img[first_non_black:, :, :] | |
| img = img[:reverse_first_non_black - first_non_black, :, :] | |
| # y axis | |
| centre_x = img_t.shape[0] // 2 | |
| black_list = img_t[centre_x, :] | |
| black_list = np.where(black_list >= black_th)[0] | |
| if len(black_list) > 1: | |
| first_non_black_y = black_list[0] | |
| reverse_first_non_black_y = black_list[-1] + 1 | |
| img = img[:, first_non_black_y:, :] | |
| img = img[:, :reverse_first_non_black_y - first_non_black_y, :] | |
| return img | |
| def preprocess_image(image_bytes: bytes) -> np.ndarray: | |
| nparr = np.frombuffer(image_bytes, np.uint8) | |
| image = cv2.imdecode(nparr, cv2.IMREAD_COLOR) | |
| image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) | |
| image = remove_black_borders(image) | |
| height, width, _ = image.shape | |
| if height > width: | |
| pad = (height - width) // 2 | |
| image = cv2.copyMakeBorder(image, 0, 0, pad, pad, cv2.BORDER_CONSTANT) | |
| elif width > height: | |
| pad = (width - height) // 2 | |
| image = cv2.copyMakeBorder(image, pad, pad, 0, 0, cv2.BORDER_CONSTANT) | |
| image = cv2.resize(image, (IMAGE_SIZE, IMAGE_SIZE)) | |
| image = image / 255.0 | |
| image = np.transpose(image, (2, 0, 1)) | |
| return image | |
| async def predict(file: UploadFile = File(...)): | |
| try: | |
| contents = await file.read() | |
| image = preprocess_image(contents) | |
| tensor = torch.tensor(image, dtype=torch.float32).unsqueeze(0).to(DEVICE) | |
| with torch.no_grad(): | |
| output = model(tensor) | |
| probabilities = torch.softmax(output, dim=1).cpu().numpy()[0] | |
| predicted_class = int(np.argmax(probabilities)) | |
| predicted_label = CLASS_NAMES[predicted_class] | |
| confidence = float(probabilities[predicted_class]) | |
| class_probs = {} | |
| for i, name in enumerate(CLASS_NAMES): | |
| class_probs[name] = round(float(probabilities[i]), 4) | |
| return JSONResponse({ | |
| "success": True, | |
| "prediction": predicted_label, | |
| "confidence": round(confidence, 4), | |
| "class_probabilities": class_probs | |
| }) | |
| except Exception as e: | |
| return JSONResponse( | |
| {"success": False, "error": str(e)}, | |
| status_code=500 | |
| ) | |
| def read_root(): | |
| return {"message": "Welcome to the DR Predictor API. Please use POST /api/predict with an image file."} | |