import os import json import joblib _MODEL_CACHE = {} def load_store_model(store_id: str, base_dir: str = "models"): """Load and cache best model + metadata for a given store_id. Looks under {base_dir}/store_{store_id}/ Returns (model, metadata) or raises FileNotFoundError. """ key = (base_dir, str(store_id)) if key in _MODEL_CACHE: return _MODEL_CACHE[key] store_dir = os.path.join(base_dir, f"store_{store_id}") meta_path = os.path.join(store_dir, "metadata.json") if not os.path.exists(meta_path): raise FileNotFoundError(f"metadata.json not found for store {store_id} in {store_dir}") with open(meta_path, "r") as f: metadata = json.load(f) model_name = metadata.get("model") if not model_name: raise FileNotFoundError(f"'model' not defined in metadata.json for store {store_id}") model_path = os.path.join(store_dir, f"{model_name}.joblib") if not os.path.exists(model_path): raise FileNotFoundError(f"Model file missing: {model_path}") model = joblib.load(model_path) _MODEL_CACHE[key] = (model, metadata) return model, metadata