Spaces:
Sleeping

File size: 1,959 Bytes
79cbb9a
 
 
 
f0a9812
 
79cbb9a
f0a9812
79cbb9a
 
 
 
 
 
 
 
 
 
f0a9812
 
 
 
 
 
 
 
 
 
79cbb9a
 
f0a9812
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
79cbb9a
 
 
 
 
 
f0a9812
79cbb9a
f0a9812
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
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