""" Backend modelu rekomendacji — SVDGCL. Aktywacja: USE_REAL_BACKEND=1 (domyslnie wlaczone — mock tylko gdy ALLOW_MOCK_BACKEND=1) Zmienne srodowiskowe: MODEL_BASE_DIR — katalog glowny projektu (override) MODEL_CONFIG_PATH — sciezka do config.yaml (override) MODEL_CHECKPOINT_PATH — bezposrednia sciezka do best_model.pt MODEL_CHECKPOINT_DIR — katalog z best_model.pt MODEL_DEVICE — "cuda" | "cpu" (domyslnie: auto) """ from __future__ import annotations import importlib.util import os import tempfile from pathlib import Path from typing import Any, Dict, List, Optional import torch import yaml from game_dataset import F95Dataset from svdgcl_model import SVDGCL from utils import find_checkpoint, scipy_to_torch_sparse EXPERT_CANDIDATE_POOL_SIZE = 30 # ─── HF data downloader ─────────────────────────────────────────────────────── def _hf_pull_data_files(config: Dict[str, Any]) -> Optional[str]: """ Pobiera pliki danych z prywatnego repo HF (HF_DATA_REPO_ID) do tymczasowego katalogu i zwraca jego ścieżkę (staje się nowym base_dir datasetu). Pobierane pliki (wg config['paths']): data_F95/games.json data_F95/reviews.json data_F95/likes.json (opcjonalny — brak nie przerywa) Zwraca None gdy HF_DATA_REPO_ID nie jest ustawione LUB gdy pobieranie nie jest potrzebne (pliki już istnieją w lokalnym base_dir). """ repo_id = os.getenv("HF_DATA_REPO_ID", "").strip() if not repo_id: return None token = os.getenv("HF_TOKEN", "").strip() or None paths_cfg = config.get("paths", {}) current_base = str(paths_cfg.get("base_dir", "")).strip() # Sprawdź czy pliki są już dostępne lokalnie games_rel = str(paths_cfg.get("games", "data_F95/games.json")).strip() reviews_rel = str(paths_cfg.get("reviews", "data_F95/reviews.json")).strip() if (os.path.exists(os.path.join(current_base, games_rel)) and os.path.exists(os.path.join(current_base, reviews_rel))): print(f"[INFO] Pliki danych dostępne lokalnie w: {current_base}") return None # Pobierz z HF do katalogu tymczasowego try: from huggingface_hub import hf_hub_download as _dl except ImportError: raise RuntimeError("huggingface_hub nie jest zainstalowane — pip install huggingface_hub") tmp_dir = tempfile.mkdtemp(prefix="hf_data_") print(f"[INFO] Pobieram pliki datasetu z HF repo '{repo_id}' → {tmp_dir}") # Lista plików do pobrania: (ścieżka_w_repo, rel_dest, wymagany) # Folder docelowy to sub_dir wewnątrz tmp_dir zachowujący strukturę data_F95/* data_folder = "data_F95" # nazwa folderu jak w repo files_to_pull = [ (f"{data_folder}/games.json", f"{data_folder}/games.json", True), (f"{data_folder}/reviews.json", f"{data_folder}/reviews.json", True), (f"{data_folder}/likes.json", f"{data_folder}/likes.json", False), ] for repo_path, rel_dest, required in files_to_pull: dest = Path(tmp_dir) / rel_dest dest.parent.mkdir(parents=True, exist_ok=True) try: local = _dl( repo_id=repo_id, filename=repo_path, repo_type="dataset", token=token, local_dir=tmp_dir, ) # hf_hub_download z local_dir zapisuje plik we właściwej podmapie if not dest.exists() and Path(local).exists(): import shutil shutil.copy2(local, dest) print(f"[INFO] ✓ {repo_path}") except Exception as exc: if required: raise FileNotFoundError( f"Nie udało się pobrać wymaganego pliku '{repo_path}' " f"z repo '{repo_id}': {exc}" ) else: print(f"[INFO] ✗ {repo_path} (opcjonalny — pominięto: {exc})") return tmp_dir def _load_recommendation_tester_class(base_dir: str): """ Laduje klase RecommendationTester z test_recommend.py. Kolejnosc prob: 1) normalny import: from test_recommend import RecommendationTester 2) import oparty na pliku — szuka test_recommend*.py w base_dir """ errors: List[str] = [] try: from test_recommend import RecommendationTester # type: ignore return RecommendationTester except Exception as exc: errors.append(f"import test_recommend: {exc}") for path in sorted(Path(base_dir).glob("test_recommend*.py")): try: module_name = f"_dynamic_{path.stem.replace(' ', '_')}" spec = importlib.util.spec_from_file_location(module_name, str(path)) if spec is None or spec.loader is None: raise ImportError(f"Cannot create spec for {path.name}") module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) cls = getattr(module, "RecommendationTester", None) if cls is not None: print(f"[INFO] Loaded RecommendationTester from {path.name}") return cls except Exception as exc: errors.append(f"{path.name}: {exc}") raise ModuleNotFoundError( "Could not load RecommendationTester. " "Ensure test_recommend.py is present in the repository. " f"Details: {' | '.join(errors)}" ) class RealRecommenderBackend: """Pelny backend SVDGCL podlaczony do test_recommend.RecommendationTester.""" def __init__(self) -> None: self.base_dir = os.path.dirname(os.path.abspath(__file__)) self.config = self._load_config() self.device = os.getenv("MODEL_DEVICE", "cuda" if torch.cuda.is_available() else "cpu") self.dataset = self._load_dataset() self.model = self._load_model() ignored_tags = set( str(t).lower() for t in self.config.get("model", {}).get("ignored_tags", []) ) tester_cls = _load_recommendation_tester_class(self.base_dir) self.tester = tester_cls( self.model, self.dataset, device=self.device, ignored_tags=ignored_tags, dataset_type="f95", ) # ────────────────────────────────────────────────────────────────────── # Config # ────────────────────────────────────────────────────────────────────── def _load_config(self) -> Dict[str, Any]: config_env = os.getenv("MODEL_CONFIG_PATH", "config.yaml").strip() config_path = config_env if os.path.isabs(config_env) else os.path.join(self.base_dir, config_env) if not os.path.exists(config_path): raise FileNotFoundError(f"Brak config: {config_path}") with open(config_path, "r", encoding="utf-8") as f: config = yaml.safe_load(f) or {} paths = config.setdefault("paths", {}) # Resolve base_dir (env override > config > runtime dir) env_bd = os.getenv("MODEL_BASE_DIR", "").strip() cfg_bd = str(paths.get("base_dir", "")).strip() if env_bd: resolved = env_bd if os.path.isabs(env_bd) else os.path.join(self.base_dir, env_bd) resolved = os.path.abspath(resolved) print(f"[INFO] MODEL_BASE_DIR: {resolved}") elif cfg_bd and os.path.exists(cfg_bd): resolved = cfg_bd else: resolved = self.base_dir if cfg_bd and cfg_bd != resolved: print(f"[WARN] base_dir not found, using runtime dir: {cfg_bd} -> {resolved}") paths["base_dir"] = resolved # Fallback dla sciezek plikow danych for key, default_rel in ( ("games", "data/games.json"), ("reviews", "data/reviews_all.json"), ): raw = str(paths.get(key, default_rel)).strip() or default_rel if os.path.isabs(raw): if os.path.exists(raw): paths[key] = raw continue # Probuj fallback w resolved base_dir for rel in (default_rel, os.path.join("data", os.path.basename(raw))): abs_try = os.path.join(resolved, rel) if os.path.exists(abs_try): print(f"[WARN] paths.{key} not found, fallback: {rel}") paths[key] = rel break else: paths[key] = raw else: if not os.path.exists(os.path.join(resolved, raw)): fallback = os.path.join(resolved, default_rel) if os.path.exists(fallback): print(f"[WARN] Missing {raw}, fallback: {default_rel}") paths[key] = default_rel return config # ────────────────────────────────────────────────────────────────────── # Dataset # ────────────────────────────────────────────────────────────────────── def _load_dataset(self) -> F95Dataset: # Pobierz dane z HF jeśli nie ma ich lokalnie hf_base = _hf_pull_data_files(self.config) if hf_base is not None: # Zaktualizuj base_dir i ścieżki relatywne do pobranego katalogu tymczasowego self.config["paths"]["base_dir"] = hf_base # Upewnij się że ścieżki relatywne wskazują na data_F95/* for key, default in (("games", "data_F95/games.json"), ("reviews", "data_F95/reviews.json"), ("likes", "data_F95/likes.json")): current = str(self.config["paths"].get(key, default)).strip() # Jeżeli ścieżka była absolutna i plik nie istnieje w nowej lokalizacji, # zamień na domyślną relatywną if os.path.isabs(current) and not os.path.exists(current): self.config["paths"][key] = default print(f"[INFO] paths.{key} → {default} (HF tmp dir)") print(f"[INFO] Dataset base_dir → {hf_base}") dataset = F95Dataset(config=self.config) seed = int(self.config.get("training", {}).get("seed", 42)) dataset.split_data(seed=seed) dataset.adj_matrix = scipy_to_torch_sparse(dataset.adj_matrix) return dataset # ────────────────────────────────────────────────────────────────────── # Checkpoint # ────────────────────────────────────────────────────────────────────── def _resolve_checkpoint_path(self) -> str: # 1) bezposrednia sciezka explicit = os.getenv("MODEL_CHECKPOINT_PATH", "").strip() if explicit: if not os.path.exists(explicit): raise FileNotFoundError(f"MODEL_CHECKPOINT_PATH nie istnieje: {explicit}") return explicit # 2) katalog z best_model.pt ckpt_dir = os.getenv("MODEL_CHECKPOINT_DIR", "").strip() if ckpt_dir: candidate = os.path.join(ckpt_dir, "best_model.pt") if os.path.exists(candidate): return candidate # 3) z config cfg_ckpt_dir = self.config.get("paths", {}).get("checkpoint_dir", "models") if not os.path.isabs(cfg_ckpt_dir): cfg_ckpt_dir = os.path.join(self.base_dir, cfg_ckpt_dir) candidate = os.path.join(cfg_ckpt_dir, "best_model.pt") if os.path.exists(candidate): return candidate # 4) auto-find auto = find_checkpoint(self.base_dir, ["models", "models_f95"]) if auto: return os.path.join(auto, "best_model.pt") raise FileNotFoundError( "Nie znaleziono best_model.pt. " "Ustaw MODEL_CHECKPOINT_PATH lub MODEL_CHECKPOINT_DIR." ) # ────────────────────────────────────────────────────────────────────── # Model — SVDGCL # ────────────────────────────────────────────────────────────────────── def _load_model(self) -> SVDGCL: checkpoint_path = self._resolve_checkpoint_path() print(f"[INFO] Loading checkpoint: {checkpoint_path}") checkpoint = torch.load(checkpoint_path, map_location=self.device, weights_only=False) state_dict = checkpoint.get("model_state_dict", checkpoint) # Merguj config z checkpointu z aktualnym config (checkpoint ma priorytet dla arch) ckpt_model_cfg = checkpoint.get("config", {}).get("model", {}) base_model_cfg = self.config.get("model", {}) mcfg = {**base_model_cfg, **ckpt_model_cfg} model = SVDGCL( n_users = self.dataset.n_users, n_items = self.dataset.n_games, embed_dim = int(mcfg.get("embed_dim", 64)), n_layers = int(mcfg.get("n_layers", 2)), epsilon_noise = float(mcfg.get("epsilon_noise", mcfg.get("epsilon", 0.2))), beta = float(mcfg.get("beta", 0.1)), lambda_cl = float(mcfg.get("lambda_cl", 0.2)), tau = float(mcfg.get("tau", 0.1)), contrast_layer= int(mcfg.get("contrast_layer", 1)), device = self.device, use_tsvd_init = False, # init tylko przy treningu, nie przy inference ) try: model.load_state_dict(state_dict, strict=True) except RuntimeError as e: print(f"[INFO] strict=False load: {e}") missing, unexpected = model.load_state_dict(state_dict, strict=False) if missing: print(f"[WARN] Missing keys: {missing}") if unexpected: print(f"[WARN] Unexpected keys: {unexpected}") model.eval() print(f"[INFO] Model loaded — {self.dataset.n_users:,} users, " f"{self.dataset.n_games:,} items, device={self.device}") return model # ────────────────────────────────────────────────────────────────────── # Filtry meta # ────────────────────────────────────────────────────────────────────── @staticmethod def _norm(value: Any) -> str: return str(value or "").strip().lower() def _matches_meta_filters( self, internal_idx: int, category: str | None, art_style: str | None, protagonist: str | None, ) -> bool: info = self.dataset.get_game_info(internal_idx) or {} if category and self._norm(info.get("category")) != self._norm(category): return False if art_style and self._norm(info.get("art_style")) != self._norm(art_style): return False if protagonist and self._norm(info.get("protagonist")) != self._norm(protagonist): return False return True # ────────────────────────────────────────────────────────────────────── # Rekomendacje # ────────────────────────────────────────────────────────────────────── def get_recommendations(self, request: Dict[str, Any]) -> List[Dict[str, Any]]: """ Wejscie (request): liked_games: list[str] category: str | None art_style: str | None protagonist: str | None include_tags: list[str] exclude_tags: list[str] top_k: int Kazda rekomendacja zawiera: title, author, tags, hybrid_score, raw_model_score, rating_bayesian, explanation, _f95_id, _internal_idx """ liked_games = [str(x).strip() for x in request.get("liked_games", []) if str(x).strip()] include_tags = [str(x).strip() for x in request.get("include_tags", []) if str(x).strip()] exclude_tags = [str(x).strip() for x in request.get("exclude_tags", []) if str(x).strip()] category = request.get("category") art_style = request.get("art_style") protagonist = request.get("protagonist") top_k = int(request.get("top_k", 15)) tag_weight = float(request.get("tag_weight", 0.35 if include_tags else 0.0)) if not liked_games: return [] _, recs = self.tester.get_recommendations( liked_games_queries = liked_games, emphasis_tags = include_tags if include_tags else None, tag_weight = tag_weight, exclude_tags = exclude_tags if exclude_tags else None, candidate_pool_size = EXPERT_CANDIDATE_POOL_SIZE, add_score_noise = False, ) final: List[Dict[str, Any]] = [] for r in recs: internal_idx = int(r.get("internal_idx", -1)) if internal_idx < 0: continue if not self._matches_meta_filters(internal_idx, category, art_style, protagonist): continue info = self.dataset.get_game_info(internal_idx) or {} game_tags = [str(t) for t in info.get("tags", [])] f95_id = str(info.get("f95_id", r.get("game_id", ""))) final.append({ "title": info.get("title", r.get("title", "Unknown")), "author": info.get("author", "Unknown"), "tags": ", ".join(game_tags), "hybrid_score": float(r.get("hybrid_score", 0.0)), "raw_model_score": float(r.get("raw_model_score", 0.0)), "rating_bayesian": float(r.get("rating_bayesian", 0.0)), "explanation": str(r.get("explanation", "")), "f95_id": f95_id, "_internal_idx": internal_idx, }) if len(final) >= top_k: break return final