from dataclasses import dataclass from functools import lru_cache from pathlib import Path from threading import RLock from typing import Any, Iterable, Mapping import joblib import numpy as np import pandas as pd from app.config import Settings, get_settings from app.services.feature_contract import ( FeatureContractError, load_feature_contract, validate_feature_row, ) REQUIRED_BUNDLE_KEYS = { "model", "preprocessor", "feature_columns", "numeric_features", "categorical_features", } class ModelLoadError(RuntimeError): """Raised when the saved model bundle is missing or incompatible.""" class ModelInputError(ValueError): """Raised when an inference row cannot be converted safely.""" @dataclass(frozen=True, slots=True) class ModelMetadata: feature_count: int pipeline_version: str | None target: str | None class ModelService: """Loads and serves the saved preprocessing + XGBoost bundle.""" def __init__(self, settings: Settings) -> None: self._settings = settings self._lock = RLock() self._loaded = False self._model: Any = None self._preprocessor: Any = None self._feature_columns: list[str] = [] self._numeric_features: list[str] = [] self._categorical_features: list[str] = [] self._schema: dict[str, Any] = {} @property def loaded(self) -> bool: return self._loaded @property def metadata(self) -> ModelMetadata: if not self._loaded: raise ModelLoadError("Model has not been loaded") return ModelMetadata( feature_count=len(self._feature_columns), pipeline_version=self._schema.get("pipeline_version"), target=self._schema.get("target"), ) def load(self) -> None: """Load once and fail if the bundle/schema contract does not match.""" with self._lock: if self._loaded: return model_path = self._settings.model_path schema_path = self._settings.model_schema_path self._assert_file(model_path, "model") self._assert_file(schema_path, "model schema") try: schema, saved_features = load_feature_contract(schema_path) bundle = joblib.load(model_path) except Exception as exc: raise ModelLoadError(f"Unable to load model artifacts: {exc}") from exc if not isinstance(bundle, dict): raise ModelLoadError("Model bundle must be a dictionary") missing_keys = REQUIRED_BUNDLE_KEYS.difference(bundle) if missing_keys: raise ModelLoadError( f"Model bundle is missing keys: {sorted(missing_keys)}" ) bundle_features = list(bundle["feature_columns"]) schema_features = list(saved_features) if bundle_features != schema_features: raise ModelLoadError( "Feature order mismatch between .pkl bundle and schema JSON" ) numeric_features = list(bundle["numeric_features"]) categorical_features = list(bundle["categorical_features"]) typed_features = numeric_features + categorical_features if set(typed_features) != set(bundle_features): raise ModelLoadError( "Numeric/categorical feature lists do not cover model features" ) preprocessor_features = list( getattr(bundle["preprocessor"], "feature_names_in_", []) ) if preprocessor_features != schema_features: raise ModelLoadError( "Saved preprocessor feature order differs from schema JSON" ) model = bundle["model"] preprocessor = bundle["preprocessor"] if not callable(getattr(model, "predict_proba", None)): raise ModelLoadError("Saved model has no predict_proba method") if not callable(getattr(preprocessor, "transform", None)): raise ModelLoadError("Saved preprocessor has no transform method") self._model = model self._preprocessor = preprocessor self._feature_columns = bundle_features self._numeric_features = numeric_features self._categorical_features = categorical_features self._schema = schema self._loaded = True def predict(self, rows: Iterable[Mapping[str, Any]]) -> np.ndarray: """Return the raw positive-class probability for every input row.""" if not self._loaded: self.load() row_list = [dict(row) for row in rows] if not row_list: raise ModelInputError("At least one feature row is required") try: for row in row_list: validate_feature_row(row, self._feature_columns) except FeatureContractError as exc: raise ModelInputError(str(exc)) from exc frame = self._prepare_frame(row_list) try: with self._lock: processed = self._preprocessor.transform(frame) probabilities = self._model.predict_proba(processed) except Exception as exc: raise ModelInputError(f"Model inference failed: {exc}") from exc classes = list(getattr(self._model, "classes_", [])) if 1 not in classes: raise ModelLoadError("Saved classifier does not contain positive class 1") positive_index = classes.index(1) result = np.asarray(probabilities[:, positive_index], dtype=float) if result.shape != (len(row_list),) or not np.isfinite(result).all(): raise ModelInputError("Model returned invalid probabilities") return result def _prepare_frame(self, rows: list[dict[str, Any]]) -> pd.DataFrame: frame = pd.DataFrame(rows) unknown = sorted(set(frame.columns).difference(self._feature_columns)) if unknown: raise ModelInputError(f"Unexpected model features: {unknown}") if "Driver" not in frame.columns or frame["Driver"].isna().any(): raise ModelInputError("Every row must contain Driver") frame = frame[self._feature_columns].copy() for column in self._numeric_features: frame[column] = pd.to_numeric(frame[column], errors="coerce") for column in self._categorical_features: frame[column] = frame[column].map( lambda value: np.nan if value is None or pd.isna(value) else str(value).strip().upper() ) return frame.replace([np.inf, -np.inf], np.nan) @staticmethod def _assert_file(path: Path, label: str) -> None: if not path.is_file(): raise ModelLoadError(f"{label.capitalize()} file not found: {path}") @lru_cache(maxsize=1) def get_model_service() -> ModelService: return ModelService(get_settings())