import os import timm import torch import torchvision.transforms as transforms import requests import logging # Get logger from app.py or configure if run standalone logger = logging.getLogger(__name__) # Class labels CLASS_LABELS = [ "No DR signs", "Mild (or early) NPDR", "Moderate NPDR", "Severe NPDR", "Very Severe NPDR", "PDR", "Advanced PDR", ] # Model setup MODEL_URL = "https://huggingface.co/helviz/swin_model/resolve/main/model.pth" MODEL_LOCAL_PATH = "/app/models/model.pth" # Use /app/models, a writable directory device = torch.device("cuda" if torch.cuda.is_available() else "cpu") # Function to download the model from Hugging Face def download_model(url, local_path): logger.info(f"Checking for model at {local_path}") # Ensure the directory exists try: os.makedirs(os.path.dirname(local_path), exist_ok=True) logger.debug(f"Ensured directory exists: {os.path.dirname(local_path)}") except Exception as e: logger.error(f"Failed to create model directory: {str(e)}") raise if not os.path.exists(local_path): logger.info(f"Downloading model from {url}") try: response = requests.get(url, stream=True, timeout=30) response.raise_for_status() # Check for HTTP errors with open(local_path, "wb") as f: f.write(response.content) logger.info(f"Model downloaded to {local_path}") except Exception as e: logger.error(f"Failed to download model: {str(e)}") raise else: logger.info(f"Model already exists at {local_path}") # Function to load the model def load_model(): logger.info("Loading model") # Download the model if not already present try: download_model(MODEL_URL, MODEL_LOCAL_PATH) except Exception as e: logger.error(f"Model download failed: {str(e)}") raise # Create the model architecture try: model = timm.create_model("swin_tiny_patch4_window7_224", pretrained=False, num_classes=len(CLASS_LABELS)) logger.debug("Model architecture created") except Exception as e: logger.error(f"Failed to create model architecture: {str(e)}") raise # Load the state dict from the downloaded file try: state_dict = torch.load(MODEL_LOCAL_PATH, map_location=device) model.load_state_dict(state_dict) logger.debug("Model state dictionary loaded") except Exception as e: logger.error(f"Failed to load model state: {str(e)}") raise # Move model to the appropriate device and set to evaluation mode try: model.to(device) model.eval() logger.info(f"Model loaded successfully on {device}") except Exception as e: logger.error(f"Failed to move model to device: {str(e)}") raise return model # Load the model model = load_model()