File size: 3,122 Bytes
8cff4cb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
70
71
72
73
74
# models/loader.py
"""
Loads and warms up both ML models at startup.
Imported once by app.py β€” models are module-level singletons.
"""

import time
import numpy as np
import torch
from torchvision import transforms, models as tv_models
from ultralytics import YOLO

from config.settings import MODEL_PATH, SKIN_TYPE_MODEL_PATH

# ── Device ─────────────────────────────────────────────────────────────────────
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
print(f"[loader] Using device: {device}")

# ── YOLO ───────────────────────────────────────────────────────────────────────
print("[loader] Loading YOLO model…")
yolo_model = YOLO(MODEL_PATH)

# ── Skin-type ResNet-50 ────────────────────────────────────────────────────────
print("[loader] Loading skin-type model…")
skin_type_model = tv_models.resnet50(weights=None)
num_ftrs = skin_type_model.fc.in_features
skin_type_model.fc = torch.nn.Linear(num_ftrs, 3)

try:
    checkpoint  = torch.load(SKIN_TYPE_MODEL_PATH, map_location=device)
    model_dict  = skin_type_model.state_dict()
    pretrained  = {}
    for k, v in checkpoint.items():
        if k in model_dict and v.shape == model_dict[k].shape:
            pretrained[k] = v
        elif k == 'fc.weight' and model_dict['fc.weight'].shape[1] == v.shape[1]:
            pretrained['fc.weight'] = v[:3, :]
        elif k == 'fc.bias' and len(v) >= 3:
            pretrained['fc.bias'] = v[:3]
    skin_type_model.load_state_dict(pretrained, strict=False)
    print("[loader] Skin-type model loaded βœ“")
except Exception as exc:
    print(f"[loader] WARNING β€” skin-type model load error: {exc}")

skin_type_model = skin_type_model.to(device)
skin_type_model.eval()

# ── Image transform ────────────────────────────────────────────────────────────
skin_transform = transforms.Compose([
    transforms.ToPILImage(),
    transforms.Resize((224, 224)),
    transforms.ToTensor(),
    transforms.Normalize(mean=[0.485, 0.456, 0.406],
                         std=[0.229, 0.224, 0.225]),
])


def warm_up():
    """Run a dummy forward pass on both models to eliminate first-request latency."""
    print("[loader] Warming up models…")
    dummy = np.zeros((224, 224, 3), dtype=np.uint8)

    t = time.time()
    yolo_model(dummy, conf=0.15, iou=0.2)
    print(f"[loader] YOLO warm-up: {time.time()-t:.2f}s")

    t = time.time()
    tensor = skin_transform(dummy).unsqueeze(0).to(device)
    with torch.no_grad():
        skin_type_model(tensor)
    print(f"[loader] Skin-type warm-up: {time.time()-t:.2f}s")

    print("[loader] Models ready βœ“")