Spaces:
Sleeping

deploy_ml / model.py
helviz
v2
f0a9812
Raw History Blame Contribute Delete
1.96 kB
import torch
import torchvision.transforms as transforms
from PIL import Image
import timm
import gdown
import os
# Define class labels
CLASS_LABELS = [
"No DR signs",
"Mild (or early) NPDR",
"Moderate NPDR",
"Severe NPDR",
"Very Severe NPDR",
"PDR",
"Advanced PDR"
]
# Define Model Paths
MODEL_PATH = "model.pth"
GDRIVE_FILE_ID = "1RNhOLcAuVUru4kpnnyFvWeL1Fu0HIOom"
# Ensure model is available (Download if missing)
if not os.path.exists(MODEL_PATH):
print("Downloading model from Google Drive...")
gdown.download(f"https://drive.google.com/uc?id={GDRIVE_FILE_ID}", MODEL_PATH, quiet=False)
# Set Device (GPU if available, otherwise CPU)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# Load Model
def load_model():
try:
model = timm.create_model('swin_tiny_patch4_window7_224', pretrained=False, num_classes=len(CLASS_LABELS))
model.load_state_dict(torch.load(MODEL_PATH, map_location=device))
model.to(device)
model.eval()
print("Model loaded successfully.")
return model
except Exception as e:
print(f"Error loading model: {e}")
exit(1)
model = load_model()
# Image Preprocessing
transform = transforms.Compose([
transforms.Resize((224, 224)),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
])
# Prediction Function
def predict(image_path):
try:
image = Image.open(image_path).convert("RGB")
image = transform(image).unsqueeze(0).to(device)
with torch.no_grad():
output = model(image)
probabilities = torch.nn.functional.softmax(output[0], dim=0)
predicted_class = torch.argmax(probabilities).item()
return CLASS_LABELS[predicted_class], probabilities.cpu().numpy().tolist()
except Exception as e:
print(f"Error during prediction: {e}")
return None, None