from __future__ import annotations import os from functools import lru_cache from pathlib import Path from huggingface_hub import hf_hub_download os.environ.setdefault("YOLO_CONFIG_DIR", "/tmp/Ultralytics") FASTSAM_REPO = "Uminosachi/FastSAM" FASTSAM_FILENAME = "FastSAM-s.pt" @lru_cache(maxsize=1) def load_fastsam_cpu(): """Carica una sola istanza FastSAM e la mantiene esplicitamente su CPU.""" from ultralytics import FastSAM local_weight = Path(FASTSAM_FILENAME) if local_weight.exists(): weight_path = local_weight else: weight_path = Path(hf_hub_download(repo_id=FASTSAM_REPO, filename=FASTSAM_FILENAME)) model = FastSAM(str(weight_path)) try: model.model.to("cpu") except Exception: pass return model