File size: 1,331 Bytes
d4f7659
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import torch
from torchvision import models
from safetensors.torch import load_file
from huggingface_hub import hf_hub_download
import joblib

# ---------------- GLOBAL MODELS ---------------- #
cnn_model = None
kmeans_model = None
scaler = None


class DenseNet121_CheXpert(torch.nn.Module):
    def __init__(self, num_labels=14):
        super().__init__()
        self.densenet = models.densenet121(weights=None)
        num_features = self.densenet.classifier.in_features
        self.densenet.classifier = torch.nn.Linear(num_features, num_labels)

    def forward(self, x):
        return self.densenet(x)


# ---------------- LOAD FUNCTION ---------------- #

def load_all_models():
    global cnn_model, kmeans_model, scaler

    print("Downloading DenseNet...")

    local_path = hf_hub_download(
        repo_id="itsomk/chexpert-densenet121",
        filename="pytorch_model.safetensors"
    )

    print("Loading CNN...")
    state = load_file(local_path)

    cnn_model = DenseNet121_CheXpert()
    cnn_model.load_state_dict(state, strict=False)
    cnn_model.eval()

    print("Loading KMeans + Scaler...")

    kmeans_model = joblib.load("models/risk_model.pkl")
    scaler = joblib.load("models/risk_scaler.pkl")

    print("ALL MODELS READY 🚀")


# ---------------- AUTO LOAD (IMPORTANT FIX) ---------------- #