#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Adult Game AI Recommender — Gradio UI. Environment variables (configure in HF Spaces → Settings → Variables & Secrets): --- Model backend --- USE_REAL_BACKEND=1 enable real SVDGCL model (default: 1) ALLOW_MOCK_BACKEND=1 allow mock fallback when real backend fails (debug only) MODEL_DEVICE=cpu 'cpu' or 'cuda' MODEL_CONFIG_PATH=config.yaml MODEL_CHECKPOINT_PATH=models/best_model.pt (direct path to checkpoint) MODEL_CHECKPOINT_DIR=models (or just the dir) MODEL_BASE_DIR=. force dataset base directory --- HuggingFace — JEDEN repo na wszystko --- HF_DATA_REPO_ID HF dataset repo, e.g. malelolpiotr/f95Dataset Oczekiwana struktura repozytorium: data_F95/games.json data_F95/banners/part_1/{f95_id}.png (podzielone przez hfwyslanie.py) data_F95/banners/part_2/{f95_id}.jpg (7500 plików na folder) data_F95/banners/... (part_N/) feedback/feedback.json (tu ląduje feedback) Bannery są ładowane przez indeks budowany raz przy starcie (skan listy plików w repo → dict f95_id → path_in_repo). Puste → tylko pliki lokalne. HF_TOKEN HuggingFace token (Read + Write) — jeden do wszystkiego HF_FEEDBACK_FILE ścieżka pliku feedbacku w repo (domyślnie: feedback/feedback.json) Local fallback paths (used when HF is not configured or download fails): data_F95/games.json data_F95/banners/{f95_id}.{ext} (lub part_X/{f95_id}.{ext} jeśli lokalnie też podzielone) """ from __future__ import annotations import base64 import difflib import hashlib import json import os import random import traceback import uuid from dataclasses import dataclass from datetime import datetime, timezone from io import BytesIO from pathlib import Path from typing import Any, Dict, List, Optional, Protocol, Tuple import gradio as gr from huggingface_hub import HfApi, hf_hub_download # ============================================================================= # Konfiguracja # ============================================================================= CATEGORIES: List[str] = [ "Visual Novel", "RPGM", "Ren'Py", "Unity", "Others", "HTML", "Unreal Engine", "Wolf RPG", "Flash", "Collection", "QSP", "Java", "Unknown", "ADRIFT", ] TAGS: List[str] = sorted([ "animated", "exhibitionism", "female domination", "footjob", "groping", "group sex", "masturbation", "multiple endings", "sandbox", "teasing", "voyeurism", "adventure", "character creation", "combat", "dystopian setting", "horror", "japanese game", "lactation", "platformer", "pregnancy", "rpg", "shooter", "side-scroller", "tentacles", "transformation", "corruption", "male domination", "prostitution", "cheating", "netorare", "milf", "mobile game", "point & click", "sex toys", "voiced", "futa/trans", "internal view", "monster girl", "simulator", "spanking", "swinging", "graphic violence", "multiple penetration", "humiliation", "humor", "interracial", "management", "text based", "virgin", "bukkake", "kinetic novel", "stripping", "ahegao", "turn based combat", "fantasy", "strategy", "urination", "bdsm", "lesbian", "harem", "paranormal", "parody", "romance", "superpowers", "cosplay", "furry", "puzzle", "sci-fi", "possession", "dating sim", "religion", "dilf", "pov", "sissification", "gay", "trap", "trainer", "no sexual content", "scat", "virtual reality", ]) ART_STYLES: List[str] = ["2dcg", "3dcg", "real_porn", "ai_cg"] PROTAGONISTS: List[str] = ["male", "female", "futa", "multiple"] # Katalog bannerow — relatywny do lokalizacji app.py BASE_DIR = Path(__file__).resolve().parent BANNERS_DIRS = [ BASE_DIR / "data_F95" / "banners", BASE_DIR / "data_f95" / "banners", BASE_DIR / "f95" / "banners" / "banners", ] # ─── HuggingFace Data source ──────────────────────────────────────────────── # JEDEN repo na wszystko: dane gier + bannery + feedback. # Ustaw HF_DATA_REPO_ID w Settings → Variables & Secrets na HF Spaces. HF_DATA_REPO_ID: str = os.getenv("HF_DATA_REPO_ID", "").strip() # np. "malelolpiotr/f95Dataset" # Rzeczywista struktura repo (po upload przez hfwyslanie.py): # data_F95/games.json # data_F95/banners/part_1/{f95_id}.png ← pliki podzielone po 7500 # data_F95/banners/part_2/{f95_id}.jpg # data_F95/banners/part_N/... # feedback/feedback.json ← zapisywany automatycznie przy feedbacku # # HF_TOKEN — jeden token (Read + Write) do wszystkiego. # UWAGA: Jeśli repozytorium danych jest PRYWATNE, ustaw HF_TOKEN jako Secret # w ustawieniach HF Space. Token z dostępem Read wystarczy do odczytu bannerów i games.json. def _hf_download_file( path_in_repo: str, repo_id: str = "", *, repo_type: str = "dataset", silent: bool = True, ) -> Optional[Path]: """ Pobiera pojedynczy plik z HuggingFace Hub (z lokalnym cache'em). Zwraca Path do lokalnej kopii lub None przy błędzie/braku konfiguracji. """ rid = (repo_id or HF_DATA_REPO_ID).strip() if not rid: return None token = os.getenv("HF_TOKEN", "").strip() or None try: local_path = hf_hub_download( repo_id=rid, filename=path_in_repo, repo_type=repo_type, token=token, ) return Path(local_path) except Exception as exc: if not silent: print(f"[HF] Could not download {rid}/{path_in_repo}: {exc}") return None # ─── HF Banner Index ───────────────────────────────────────────────────────── # Indeks jest budowany RAZ przy pierwszym żądaniu bannera. # Mapuje: f95_id (string) → pełna ścieżka w repo (np. "data_F95/banners/part_3/12345.png") # Pozwala znaleźć banner bez znajomości numeru parta. _HF_BANNER_INDEX: Dict[str, str] = {} _HF_BANNER_INDEX_READY: bool = False def _build_hf_banner_index() -> None: """ Skanuje listę plików w HF repo (jednorazowo) i buduje słownik f95_id → path_in_repo dla wszystkich bannerów. Obsługuje strukturę płaską (banners/{id}.ext) i podzieloną na części (banners/part_N/{id}.ext). """ global _HF_BANNER_INDEX, _HF_BANNER_INDEX_READY if _HF_BANNER_INDEX_READY: return _HF_BANNER_INDEX_READY = True # ustaw przed próbą — nie ponawiaj przy błędzie if not HF_DATA_REPO_ID: return token = os.getenv("HF_TOKEN", "").strip() or None try: from huggingface_hub import HfApi as _HfApi _api = _HfApi() all_files = list(_api.list_repo_files( repo_id=HF_DATA_REPO_ID, repo_type="dataset", token=token, )) banner_exts = set(_BANNER_EXT_MIME.keys()) count = 0 for path_str in all_files: p = Path(path_str) if p.suffix.lower() not in banner_exts: continue parts_list = p.parts # np. ('data_F95', 'banners', 'part_1', '12345.png') if len(parts_list) < 3: continue # Akceptuj data_F95/banners/... i data_f95/banners/... (case-insensitive) if parts_list[0].lower() != "data_f95": continue if parts_list[1].lower() != "banners": continue stem = p.stem # f95_id bez rozszerzenia if stem not in _HF_BANNER_INDEX: # pierwszy znaleziony wygrywa _HF_BANNER_INDEX[stem] = path_str count += 1 print(f"[HF] Banner index built: {count} plików zindeksowanych " f"(łącznie {len(_HF_BANNER_INDEX)} unikalnych ID)") except Exception as exc: print(f"[HF] Nie udało się zbudować indeksu bannerów: {exc}") # ============================================================================= # Helpers # ============================================================================= def _safe_float(value: Any, default: float = 0.0) -> float: try: return float(value) except (TypeError, ValueError): return default def _safe_int(value: Any, default: int = 0) -> int: try: return int(float(value)) except (TypeError, ValueError): return default def _normalize_text(value: Any) -> str: return str(value or "").strip().lower() _BANNER_EXT_MIME: Dict[str, str] = { ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".webp": "image/webp", ".gif": "image/gif", } def _banner_bytes_to_b64(data: bytes, ext: str) -> Optional[str]: mime = _BANNER_EXT_MIME.get(ext) if not mime: return None return f"data:{mime};base64,{base64.b64encode(data).decode()}" def _load_banner_b64(f95_id: str) -> Optional[str]: """ Wczytuje baner gry jako base64 string (do osadzenia w HTML). Kolejność prób: 1) Lokalne katalogi (BANNERS_DIRS) — bezpośrednio AND w podfolderach part_*/ 2) HuggingFace — przez indeks _HF_BANNER_INDEX (budowany raz przy starcie) który uwzględnia podział na data_F95/banners/part_1/, part_2/, ... Zwraca None jesli nie znaleziono. """ if not f95_id: return None safe_id = str(f95_id).strip() exts = list(_BANNER_EXT_MIME.keys()) # 1) Lokalne — najpierw bezpośrednio w banner_dir, potem w podfolderach part_*/ for banner_dir in BANNERS_DIRS: if not banner_dir.exists(): continue # a) plik bezpośrednio for ext in exts: path = banner_dir / f"{safe_id}{ext}" if path.exists(): try: return _banner_bytes_to_b64(path.read_bytes(), ext) except Exception: return None # b) w podfolderach part_* (lokalny odpowiednik struktury HF) for part_dir in sorted(banner_dir.iterdir()): if not part_dir.is_dir() or not part_dir.name.startswith("part_"): continue for ext in exts: path = part_dir / f"{safe_id}{ext}" if path.exists(): try: return _banner_bytes_to_b64(path.read_bytes(), ext) except Exception: return None # 2) HuggingFace — użyj indeksu (data_F95/banners/part_N/{id}.ext) if HF_DATA_REPO_ID: # Zbuduj indeks przy pierwszym żądaniu (jednorazowy skan listy plików w repo) if not _HF_BANNER_INDEX_READY: _build_hf_banner_index() repo_path = _HF_BANNER_INDEX.get(safe_id) if repo_path: hf_file = _hf_download_file(repo_path) if hf_file and hf_file.exists(): ext = Path(repo_path).suffix.lower() try: return _banner_bytes_to_b64(hf_file.read_bytes(), ext) except Exception: pass # Ostatni fallback: stara płaska ścieżka (na wypadek gdyby indeks był pusty) for prefix in ("data_F95", "data_f95"): for ext in exts: hf_path = _hf_download_file(f"{prefix}/banners/{safe_id}{ext}") if hf_path and hf_path.exists(): try: return _banner_bytes_to_b64(hf_path.read_bytes(), ext) except Exception: pass return None # ============================================================================= # Katalog gier (autouzupelnianie tytułow) # ============================================================================= def _load_games_catalog() -> List[Dict[str, Any]]: """ Wczytuje katalog gier. Kolejność prób: 1) HuggingFace: {HF_DATA_REPO_ID}/data_f95/games.json 2) Lokalnie: data_F95/games.json / data_f95/games.json """ raw: Any = None # 1) HuggingFace — próbuj data_F95 (upload przez hfwyslanie.py) i data_f95 (fallback) if HF_DATA_REPO_ID: hf_path = _hf_download_file("data_F95/games.json", silent=False) if hf_path is None: hf_path = _hf_download_file("data_f95/games.json", silent=False) if hf_path and hf_path.exists(): try: with hf_path.open("r", encoding="utf-8") as f: raw = json.load(f) print(f"[INFO] games.json loaded from HF: {HF_DATA_REPO_ID}") except Exception as exc: print(f"[WARN] HF games.json parse error: {exc}") raw = None # 2) Lokalne fallbacki if raw is None: for rel in ("data_F95/games.json", "data_f95/games.json"): catalog_path = BASE_DIR / rel if catalog_path.exists(): try: with catalog_path.open("r", encoding="utf-8") as f: raw = json.load(f) print(f"[INFO] games.json loaded locally: {catalog_path}") break except Exception: pass if raw is None: print("[WARN] games.json not found (HF nor local)") return [] if not isinstance(raw, list): return [] catalog: List[Dict[str, Any]] = [] for item in raw: if not isinstance(item, dict): continue tags = item.get("tags", []) if not isinstance(tags, list): tags = [] catalog.append({ "title": item.get("title", "Unknown"), "author": item.get("author", "Unknown"), "category": item.get("category", "Unknown"), "status": item.get("status", "Unknown"), "art_style": item.get("art_style", "Unknown"), "protagonist": item.get("protagonist", "Unknown"), "game_dimension": item.get("game_dimension", "Unknown"), "rating_bayesian": _safe_float(item.get("rating_bayesian")), "engagement_score": _safe_float(item.get("engagement_score")), "n_reviews": _safe_int(item.get("n_reviews"), default=0), "log_n_reviews": _safe_float(item.get("log_n_reviews")), "f95_id": str(item.get("f95_id", item.get("id", ""))), "tags": [str(t) for t in tags], }) return catalog GLOBAL_CATALOG = _load_games_catalog() GLOBAL_TITLES = [str(g.get("title", "")).strip() for g in GLOBAL_CATALOG if str(g.get("title", "")).strip()] GLOBAL_TITLE_LOWER_TO_ORIG = {t.lower(): t for t in GLOBAL_TITLES} def suggest_similar_titles(query: str, limit: int = 5) -> List[str]: q = _normalize_text(query) if not q: return [] starts = [t for t in MODEL_TITLES if t.lower().startswith(q)] contains = [t for t in MODEL_TITLES if q in t.lower() and t not in starts] direct = (starts + contains)[:limit] # Fuzzy tylko gdy zero bezpośrednich dopasowań if direct: return direct fuzzy_lower = difflib.get_close_matches(q, list(MODEL_TITLE_LOWER_TO_ORIG.keys()), n=limit, cutoff=0.55) return [MODEL_TITLE_LOWER_TO_ORIG[x] for x in fuzzy_lower][:limit] def find_unknown_queries(queries: List[str]) -> Dict[str, List[str]]: unknown: Dict[str, List[str]] = {} for q in queries: qn = _normalize_text(q) if not qn: continue if not any(qn in t.lower() for t in MODEL_TITLES): unknown[q] = suggest_similar_titles(q, limit=4) return unknown # ============================================================================= # Backend protocol # ============================================================================= class RecommenderBackend(Protocol): def get_recommendations(self, request: Dict[str, Any]) -> List[Dict[str, Any]]: ... # ============================================================================= # Mock backend (tylko debug — ALLOW_MOCK_BACKEND=1) # ============================================================================= @dataclass class MockRecommenderBackend: """Mock uzywajacy prawdziwych tytulow z data/games.json.""" seed: int = 42 def __post_init__(self) -> None: self._rng = random.Random(self.seed) self._catalog = GLOBAL_CATALOG def _matches_hard_filters( self, game: Dict[str, Any], category: Optional[str], art_style: Optional[str], protagonist: Optional[str], ) -> bool: if category and _normalize_text(game.get("category")) != _normalize_text(category): return False if art_style and _normalize_text(game.get("art_style")) != _normalize_text(art_style): return False if protagonist and _normalize_text(game.get("protagonist")) != _normalize_text(protagonist): return False return True def _matches_tag_filters( self, game: Dict[str, Any], include_tags: List[str], exclude_tags: List[str], ) -> bool: tags = {_normalize_text(t) for t in game.get("tags", [])} if exclude_tags and any(_normalize_text(t) in tags for t in exclude_tags): return False if include_tags and not any(_normalize_text(t) in tags for t in include_tags): return False return True def get_recommendations(self, request: Dict[str, Any]) -> List[Dict[str, Any]]: top_k = int(request.get("top_k", 10)) liked_games = request.get("liked_games", []) include_tags = request.get("include_tags", []) exclude_tags = request.get("exclude_tags", []) category = request.get("category") art_style = request.get("art_style") protagonist = request.get("protagonist") if not self._catalog: return [] liked_lower = {_normalize_text(x) for x in liked_games} candidates = [ g for g in self._catalog if not any(seed in _normalize_text(g.get("title")) for seed in liked_lower) and self._matches_hard_filters(g, category, art_style, protagonist) and self._matches_tag_filters(g, include_tags, exclude_tags) ] or [ g for g in self._catalog if self._matches_hard_filters(g, category, art_style, protagonist) ] or self._catalog[:] self._rng.shuffle(candidates) recs: List[Dict[str, Any]] = [] for game in candidates[:top_k]: hybrid = round(self._rng.uniform(0.55, 0.95), 4) recs.append({ "title": game.get("title", "Unknown"), "author": game.get("author", "Unknown"), "tags": ", ".join(str(t) for t in game.get("tags", [])), "hybrid_score": hybrid, "raw_model_score": hybrid, "rating_bayesian": _safe_float(game.get("rating_bayesian")), "explanation": "Mock recommendation", "_f95_id": game.get("f95_id", ""), "_internal_idx": -1, }) return recs # ============================================================================= # Backend loading # ============================================================================= def load_backend() -> Tuple[RecommenderBackend, str]: allow_mock = os.getenv("ALLOW_MOCK_BACKEND", "0").strip() == "1" try: from model_backend import RealRecommenderBackend # type: ignore print("[INFO] Using RealRecommenderBackend (SVDGCL)") return RealRecommenderBackend(), "real" except Exception as exc: if allow_mock: print(f"[WARN] Real backend failed, fallback to mock: {exc}") return MockRecommenderBackend(), "mock" raise RuntimeError( f"Real backend initialization failed: {exc}\n" "Set ALLOW_MOCK_BACKEND=1 for temporary UI debugging." ) try: BACKEND, BACKEND_KIND = load_backend() BACKEND_ERROR: Optional[str] = None except Exception as exc: BACKEND = None BACKEND_KIND = "error" BACKEND_ERROR = str(exc) print(f"[ERROR] {BACKEND_ERROR}") def _build_model_titles() -> Tuple[List[str], Dict[str, str]]: """ Zbiera tytuły gier które faktycznie zna model (są w datasecie). Próbuje kilka podejść w kolejności, fallback do GLOBAL_CATALOG. """ if BACKEND is None: return GLOBAL_TITLES, _TITLE_TO_AUTHOR_CATALOG dataset = getattr(BACKEND, "dataset", None) if dataset is None: return GLOBAL_TITLES, _TITLE_TO_AUTHOR_CATALOG titles: List[str] = [] # Próba 1: dataset.game_title_to_idx (dict tytuł → idx) title_map = getattr(dataset, "game_title_to_idx", None) if isinstance(title_map, dict) and title_map: titles = [str(t).strip() for t in title_map.keys() if str(t).strip()] # Próba 2: dataset.idx_to_title lub dataset.id_to_title if not titles: for attr in ("idx_to_title", "id_to_title", "game_idx_to_title"): m = getattr(dataset, attr, None) if isinstance(m, dict) and m: titles = [str(v).strip() for v in m.values() if str(v).strip()] break # Próba 3: iteruj get_game_info po wszystkich itemach if not titles: n = getattr(dataset, "n_games", 0) if n > 0: for i in range(n): try: info = dataset.get_game_info(i) if info and info.get("title"): titles.append(str(info["title"]).strip()) except Exception: pass if not titles: print("[WARN] Could not extract model titles — falling back to catalog") return GLOBAL_TITLES, _TITLE_TO_AUTHOR_CATALOG titles = sorted(set(t for t in titles if t)) # Zbuduj mapę tytuł → autor na podstawie GLOBAL_CATALOG (tam są metadane) t2a = {t: _TITLE_TO_AUTHOR_CATALOG.get(t, "") for t in titles} print(f"[INFO] Model titles for autocomplete: {len(titles):,} (vs catalog: {len(GLOBAL_TITLES):,})") return titles, t2a # Oddziel stałą katalogu od stałej modelu _TITLE_TO_AUTHOR_CATALOG: Dict[str, str] = { g["title"]: g.get("author", "") for g in GLOBAL_CATALOG if g.get("title") } LOW_REVIEWS_THRESHOLD = 10 _TITLE_TO_N_REVIEWS: Dict[str, int] = { str(g.get("title", "")).strip(): _safe_int(g.get("n_reviews", 0), default=0) for g in GLOBAL_CATALOG if str(g.get("title", "")).strip() } # ============================================================================= # Feedback # ============================================================================= LOCAL_FEEDBACK_PATH = Path("feedback_local.jsonl") def now_iso() -> str: return datetime.now(timezone.utc).isoformat() def write_local_feedback(record: Dict[str, Any]) -> None: LOCAL_FEEDBACK_PATH.parent.mkdir(parents=True, exist_ok=True) with LOCAL_FEEDBACK_PATH.open("a", encoding="utf-8") as f: f.write(json.dumps(record, ensure_ascii=False, indent=2)) f.write("\n" + ("-" * 80) + "\n") def _build_feedback_record(label: str, comment: str, state: Dict[str, Any]) -> Dict[str, Any]: req = state.get("request", {}) or {} resp = state.get("response", []) or [] return { "feedback_id": uuid.uuid4().hex, "timestamp": now_iso(), "label": label, "comment": (comment or "").strip(), "request": {"liked_games": [str(x).strip() for x in req.get("liked_games", []) if str(x).strip()]}, "response": [{"title": str(r.get("title", "")), "author": str(r.get("author", ""))} for r in resp], } def write_hf_feedback(record: Dict[str, Any]) -> Tuple[bool, str]: """ Dopisuje rekord feedbacku do feedback/feedback.json w HF_DATA_REPO_ID. Ten sam repo co dane (data_f95/). Plik jest pobierany, uzupełniany i ponownie uploadowany (operacja read-modify-write). """ token = os.getenv("HF_TOKEN", "").strip() repo_id = HF_DATA_REPO_ID # JEDEN repo na wszystko feedback_file = os.getenv("HF_FEEDBACK_FILE", "feedback/feedback.json").strip() \ or "feedback/feedback.json" if not token: return False, "disabled: missing HF_TOKEN" if not repo_id: return False, "disabled: missing HF_DATA_REPO_ID" try: api = HfApi(token=token) # Repo musi istnieć — jeśli nie, utwórz (prywatny dataset) api.create_repo(repo_id=repo_id, repo_type="dataset", private=True, exist_ok=True) # Pobierz istniejący plik feedbacku (może nie istnieć przy pierwszym zapisie) existing: List[Dict[str, Any]] = [] try: p = hf_hub_download( repo_id=repo_id, filename=feedback_file, repo_type="dataset", token=token, force_download=True, # zawsze świeża wersja — nie stary cache ) with open(p, "r", encoding="utf-8") as f: loaded = json.load(f) if isinstance(loaded, list): existing = loaded except Exception: pass # plik nie istnieje jeszcze — zaczniemy od pustej listy existing.append(record) payload = json.dumps(existing, ensure_ascii=False, indent=2).encode("utf-8") api.upload_file( path_or_fileobj=BytesIO(payload), path_in_repo=feedback_file, repo_id=repo_id, repo_type="dataset", commit_message=f"feedback: {record.get('feedback_id', '')[:8]}", ) return True, f"saved:{repo_id}/{feedback_file} (total: {len(existing)})" except Exception as exc: return False, f"error:{exc}" def get_user_context(request: Optional[gr.Request]) -> Dict[str, Any]: if request is None: return {"session_hash": None, "anon_user_fingerprint": None, "source": "no-request"} headers = getattr(request, "headers", {}) or {} user_agent = str(headers.get("user-agent", "")) xff = str(headers.get("x-forwarded-for", "")).strip() source_ip = xff.split(",")[0].strip() if xff else getattr(getattr(request, "client", None), "host", "") fingerprint = hashlib.sha256(f"{source_ip}|{user_agent}".encode()).hexdigest()[:16] if (source_ip or user_agent) else None return {"session_hash": getattr(request, "session_hash", None), "anon_user_fingerprint": fingerprint, "source": "gradio-request"} # ============================================================================= # HTML rendering — karty rekomendacji # ============================================================================= PLACEHOLDER_SVG = ( "data:image/svg+xml;base64," + base64.b64encode( b'' b'' b'No banner available' b'' ).decode() ) CSS = """ """ def _confidence_color(pct: float) -> str: """Kolor paska w zaleznosci od pewnosci dopasowania.""" if pct >= 80: return "linear-gradient(90deg, #22c55e, #4ade80)" if pct >= 60: return "linear-gradient(90deg, #3b82f6, #60a5fa)" return "linear-gradient(90deg, #f59e0b, #fbbf24)" def build_recommendation_html(recs: List[Dict[str, Any]]) -> str: """Buduje HTML z kartami rekomendacji. Tytuł i autor sa zaznaczalne.""" if not recs: return f'{CSS}
No recommendations for this query.
' cards = [] for rank, rec in enumerate(recs, 1): title = str(rec.get("title", "Unknown")) author = str(rec.get("author", "Unknown")) f95_id = str(rec.get("f95_id") or rec.get("_f95_id") or rec.get("id") or "") hybrid = _safe_float(rec.get("hybrid_score", 0.0)) pct = min(max(round(hybrid * 100, 1), 1.0), 99.9) banner_b64 = _load_banner_b64(f95_id) banner_src = banner_b64 if banner_b64 else PLACEHOLDER_SVG banner_alt = f"Banner: {title}" bar_color = _confidence_color(pct) cards.append(f"""
{banner_alt}
{title}
by {author}
""") return CSS + '
' + "\n".join(cards) + "
" # ============================================================================= # Logika predykcji # ============================================================================= def parse_liked_games(raw_text: str) -> List[str]: return [p.strip() for p in (raw_text or "").split(",") if p.strip()] def run_recommendation( liked_games_list: List[str], top_k: int, request: gr.Request, ) -> Tuple[str, str, Dict[str, Any]]: """ Zwraca: (status_markdown, recommendations_html, session_state) """ liked_games = [g.strip() for g in (liked_games_list or []) if str(g).strip()] req_payload = { "liked_games": liked_games, "category": None, "art_style": None, "protagonist": None, "include_tags": [], "exclude_tags": [], "top_k": int(top_k), } if BACKEND is None: msg = "The recommendation backend could not be loaded." if BACKEND_ERROR: msg += f"\n\n{BACKEND_ERROR}" state = {"request": req_payload, "response": [], "user": get_user_context(request)} return msg, build_recommendation_html([]), state if not liked_games: msg = "Add at least one game to the list before generating recommendations." state = {"request": req_payload, "response": [], "user": get_user_context(request)} return msg, build_recommendation_html([]), state unknown_queries = find_unknown_queries(liked_games) unknown_msg = "" if unknown_queries: lines = [] for q, suggestions in unknown_queries.items(): if suggestions: lines.append(f"- '{q}' not found, did you mean: {', '.join(suggestions)}?") else: lines.append(f"- '{q}' not found") unknown_msg = "\n\nSome titles were not recognized:\n" + "\n".join(lines) if len(unknown_queries) == len(liked_games): msg = "None of the provided titles were found in the database." + unknown_msg state = {"request": req_payload, "response": [], "user": get_user_context(request)} return msg, build_recommendation_html([]), state try: recs = BACKEND.get_recommendations(req_payload) recommendation_id = uuid.uuid4().hex state = { "recommendation_id": recommendation_id, "request": req_payload, "response": recs, "generated_at": now_iso(), "user": get_user_context(request), } if not recs: msg = "No recommendations found for this set of games." + unknown_msg return msg, build_recommendation_html([]), state msg = unknown_msg.strip() return msg, build_recommendation_html(recs), state except Exception as exc: traceback.print_exc() msg = f"Something went wrong while generating recommendations: {exc}" state = {"request": req_payload, "response": [], "user": get_user_context(request)} return msg, build_recommendation_html([]), state # ============================================================================= # Feedback handlers # ============================================================================= def submit_feedback(label: str, comment: str, state: Dict[str, Any], request: gr.Request) -> str: if not state or not state.get("response"): return "You need to generate recommendations before sending a report." record = _build_feedback_record(label=label, comment=comment, state=state) try: write_local_feedback(record) ok, hf_msg = write_hf_feedback(record) if ok: return "Report sent. We'll look into it." if str(hf_msg).startswith("disabled"): return "Report saved. Thanks for flagging this." return ( f"Report saved locally but could not be synced: {hf_msg}" ) except Exception as exc: traceback.print_exc() return f"Could not save your report: {exc}" # ============================================================================= # UI # ============================================================================= MODEL_TITLES, _TITLE_TO_AUTHOR = _build_model_titles() MODEL_TITLE_LOWER_TO_ORIG: Dict[str, str] = {t.lower(): t for t in MODEL_TITLES} def _update_suggestions(query: str) -> gr.Radio: """Zwraca Radio z sugestami 'Tytuł — Autor' — widoczne od razu bez klikania.""" q = (query or "").strip() if len(q) < 2: return gr.Radio(choices=[], visible=False, value=None) titles = suggest_similar_titles(q, limit=7) if not titles: return gr.Radio(choices=[], visible=False, value=None) choices = [] for t in titles: author = _TITLE_TO_AUTHOR.get(t, "") label = f"{t} · {author}" if author and author not in ("Unknown", "") else t choices.append(label) return gr.Radio(choices=choices, visible=True, value=None) def _extract_title_from_choice(choice: str) -> str: """Wyciąga tytuł z 'Tytuł · Autor'.""" return choice.split(" · ")[0].strip() if " · " in choice else choice.strip() def _render_suggestions_html(query: str) -> str: """Renderuje sugestie: najpierw bezpośrednie dopasowania, fallback do fuzzy.""" q = (query or "").strip() if len(q) < 2: return "" titles = suggest_similar_titles(q, limit=5) if not titles: return '
No results found, try a different phrase.
' # Sprawdź czy to fuzzy (brak bezpośrednich dopasowań słownych) direct = [t for t in MODEL_TITLES if q.lower() in t.lower()] is_fuzzy = len(direct) == 0 hint = '
Similar titles (no exact matches):
' if is_fuzzy else "" rows = [] for t in titles: author = _TITLE_TO_AUTHOR.get(t, "") author_html = f'by {author}' if author and author not in ("Unknown", "") else "" rows.append( f'
' f'{t}{author_html}' f'
' ) return hint + '
' + "".join(rows) + "
" def _render_chips_html(titles: List[str]) -> str: """Renderuje nagłówek + chipy jako jeden blok HTML.""" low_review_titles = [ (t, _TITLE_TO_N_REVIEWS[t]) for t in titles if t in _TITLE_TO_N_REVIEWS and _TITLE_TO_N_REVIEWS[t] < LOW_REVIEWS_THRESHOLD ] warn_html = "" if low_review_titles: warn_html = ( '
' '⚠ Less-known titles selected. ' 'Titles highlighted in yellow are less-known games, so recommendations may be less accurate.' '
' ) count = len(titles) badge = f'{count}' if count else '' clear = ( '' ) if titles else '' header = ( f'
' f'
Selected games{badge}
' f' {clear}' f'
' ) if not titles: body = '
No games selected yet. Type a title above and press Enter.
' else: chips_rows: List[str] = [] for i, t in enumerate(titles): n_reviews = _TITLE_TO_N_REVIEWS.get(t) is_low = n_reviews is not None and n_reviews < LOW_REVIEWS_THRESHOLD chip_cls = "game-chip low-reviews" if is_low else "game-chip" chip_title = ( f' title="Less-known game ({n_reviews} reviews) — recommendations may be less accurate"' if is_low else "" ) chips_rows.append( f'' f'{t}' f'' f'' ) chips = "".join(chips_rows) body = f'
{chips}
' return warn_html + header + body def _add_from_sugg_bridge( title_str: str, current_titles: List[str], ) -> Tuple[List[str], str, str, str]: """Dodaje grę z JS bridge sugestii.""" title = (title_str or "").strip() if title and title not in current_titles: current_titles = current_titles + [title] return current_titles, _render_chips_html(current_titles), "", "" # czyści bridge + input def _remove_by_index(idx_str: str, titles: List[str]) -> Tuple[List[str], str, str]: """Usuwa grę po indeksie z JS bridge.""" try: idx = int((idx_str or "").strip()) new_titles = [t for i, t in enumerate(titles) if i != idx] except (ValueError, TypeError): new_titles = titles[:] return new_titles, _render_chips_html(new_titles), "" BLOCKS_CSS = """ .gradio-container { max-width: none !important; width: 100% !important; margin: 0 auto; padding: 0 20px; } footer { display: none !important; } #status-box { min-height: 24px; } #rec-output { min-height: 200px; width: 100%; } /* Bridge'e w DOM ale niewidoczne */ #chip-bridge, #sugg-bridge, #clear-bridge { position: absolute; width: 1px; height: 1px; overflow: hidden; opacity: 0; pointer-events: none; left: -9999px; } /* Ściśnij odstępy w sekcji wyszukiwania */ #search-heading { margin-bottom: 4px !important; padding-bottom: 0 !important; } #search-heading p, #search-heading h3 { margin: 0 !important; padding: 0 !important; } #title-search { margin-top: 0 !important; } #suggestions-box { margin-top: 2px !important; margin-bottom: 0 !important; } #suggestions-box > .wrap { padding: 0 !important; } #chips-section { margin-top: 4px !important; } #chips-section .wrap { padding: 0 !important; } /* Ściśnij globalny gap kolumny Gradio w sekcji wejściowej */ .gradio-container > .main > .wrap > .gap { gap: 8px !important; } /* Sugestie — kompaktowe */ .sug-hint { font-size: 11px; color: #64748b; padding: 4px 2px 2px; font-style: italic; } .sug-list { border: 1px solid #1e3a5f; border-radius: 8px; overflow: hidden; margin-top: 2px; } .sug-row { padding: 7px 13px; border-bottom: 1px solid #152236; cursor: pointer; transition: background .1s; display: flex; align-items: baseline; gap: 8px; } .sug-row:last-child { border-bottom: none; } .sug-row:hover { background: #1e3a5f55; } .sug-title { font-size: 14px; font-weight: 700; color: #e2e8f0; } .sug-author { font-size: 12px; color: #7a90ab; } .sug-author em { font-style: italic; } .sug-empty { padding: 6px 11px; font-size: 12px; color: #64748b; font-style: italic; } /* Nagłówek sekcji chipów — czyste HTML wewnątrz chips-section */ .chips-header-row { display: flex; align-items: center; justify-content: space-between; margin-bottom: 8px; } .chips-header-left { display: flex; align-items: center; gap: 8px; } .chips-label { font-size: 15px; font-weight: 700; color: #e2e8f0; } .chips-count { display: inline-flex; align-items: center; justify-content: center; background: #1e3a6e; border: 1px solid #2d5299; border-radius: 12px; font-size: 12px; font-weight: 700; color: #60a5fa; padding: 1px 8px; min-width: 22px; } .chips-clear-btn { background: #1e2a3a; border: 1px solid #475569; color: #cbd5e1; font-size: 14px; font-weight: 600; padding: 6px 18px; border-radius: 10px; cursor: pointer; transition: all .15s; } .chips-clear-btn:hover { background: #3b1f1f; border-color: #e11d48; color: #f87171; } /* Generate btn full width */ #generate-btn { width: 100% !important; } .game-chips-wrap { display: flex; flex-wrap: wrap; gap: 8px; padding: 0; min-height: 40px; } .game-chip { display: inline-flex; align-items: center; gap: 6px; background: #1e3a6e; border: 1px solid #3b63b0; border-radius: 24px; padding: 6px 10px 6px 16px; font-size: 14px; color: #e2e8f0; box-shadow: 0 1px 4px rgba(0,0,0,.3); transition: border-color .15s; } .game-chip:hover { border-color: #60a5fa; } .game-chip.low-reviews { background: #5a4b16; border-color: #eab308; color: #fef3c7; } .game-chip.low-reviews:hover { border-color: #facc15; } .game-chip.low-reviews .chip-x { border-color: #b45309; color: #fde68a; } .game-chip.low-reviews .chip-x:hover { color: #fff; background: #dc2626; border-color: #dc2626; } .chip-title { font-weight: 600; } .chip-x { display: inline-flex; align-items: center; justify-content: center; width: 18px; height: 18px; flex-shrink: 0; background: transparent; border: 1px solid #2d5299; cursor: pointer; color: #64748b; font-size: 11px; line-height: 1; padding: 0; border-radius: 50%; transition: color .1s, background .1s, border-color .1s; } .chip-x:hover { color: #fff; background: #e11d48; border-color: #e11d48; } .chips-empty { color: #475569; font-size: 13px; padding: 4px 0; font-style: italic; } .low-reviews-note { margin: 0 0 10px 0; padding: 8px 12px; border-radius: 10px; border: 1px solid #d97706; background: #3f2a0c; color: #fde68a; font-size: 13px; line-height: 1.35; } /* Zgłoszenia — pigułki poziome */ #problem-radio .wrap { flex-direction: row !important; flex-wrap: wrap !important; gap: 6px !important; } #problem-radio label { padding: 5px 13px !important; border-radius: 16px !important; background: #1e3a5f22 !important; border: 1px solid #1e3a5f !important; cursor: pointer !important; font-size: 13px !important; white-space: nowrap !important; transition: background .15s, border-color .15s, color .15s !important; color: #94a3b8 !important; } #problem-radio label:hover { background: #1e3a5f66 !important; color: #e2e8f0 !important; } /* Zaznaczona pigułka */ #problem-radio label:has(input:checked) { background: #1e4d8c !important; border-color: #3b82f6 !important; color: #fff !important; font-weight: 600 !important; } #problem-radio input[type="radio"] { display: none !important; } /* Pierwsza pigułka ("Dodaj grę") — wyróżniona kolorem */ #problem-radio .wrap > label:first-child { background: #2d1a0e !important; border-color: #c2440e !important; color: #fb923c !important; font-weight: 600 !important; } #problem-radio .wrap > label:first-child:hover { background: #3d2010 !important; } #problem-radio .wrap > label:first-child:has(input:checked) { background: #c2440e !important; border-color: #fb923c !important; color: #fff !important; } /* Panel dodania gry */ #missing-game-panel { border: 1px solid #7c2d12; border-radius: 8px; padding: 12px 14px; background: #1c0f07; margin-top: 6px; } /* Responsive — mobile */ @media (max-width: 640px) { .gradio-container { padding: 0 10px !important; } .game-chip { font-size: 13px; padding: 5px 8px 5px 12px; } .chips-label { font-size: 14px; } .sug-row { padding: 8px 10px; } .sug-title { font-size: 13px; } #problem-radio label { font-size: 12px !important; padding: 4px 10px !important; } } """ BLOCKS_HEAD = """""" def build_app() -> gr.Blocks: with gr.Blocks(title="Adult Game AI Recommender") as demo: # ── Nagłówek ────────────────────────────────────────────────── gr.Markdown( "# Adult Game Recommender\n\n" "I am actively experimenting on the **full dataset of ~25,000 games**, but right now only around **8,000 games** have enough interactions for more reliable recommendations.\n\n" "**Quality over Quantity:** For best results, search for **similar titles** and provide **2–4 games** that share a specific fetish, atmosphere, or trope. A few vibe-aligned examples work better than a long mixed list.\n\n" "**IMPORTANT:** Games marked in **yellow** are less-known titles, so their recommendations can be less accurate.\n\n" "**NOTE:** This app runs on a free Hugging Face tier. If it has been inactive, it may need to reload, which can take a few minutes. Thanks for your patience!" ) # ── Wyszukiwarka ────────────────────────────────────────────── gr.Markdown("### Add games", elem_id="search-heading") title_search_input = gr.Textbox( placeholder="Type a title and press Enter, or click a suggestion below", lines=1, show_label=False, container=False, elem_id="title-search", ) # Sugestie jako HTML (bold tytuł + italic autor) suggestions_html = gr.HTML(value="", elem_id="suggestions-box") # Bridge: kliknięcie sugestii → Python sugg_bridge = gr.Textbox(value="", elem_id="sugg-bridge") # ── Wybrane gry — chipy ─────────────────────────────────────── selected_titles_state = gr.State(value=[]) chips_html = gr.HTML(value=_render_chips_html([]), elem_id="chips-section") # Bridge: kliknięcie ✕ na chipie → Python chip_bridge = gr.Textbox(value="", elem_id="chip-bridge") # Bridge: clear all → Python clear_bridge = gr.Textbox(value="", elem_id="clear-bridge") gr.Markdown("---") # ── Liczba wyników + Generuj ────────────────────────────────── run_btn = gr.Button( "Generate recommendations", variant="primary", size="lg", elem_id="generate-btn", ) status = gr.Markdown("", elem_id="status-box") output_html = gr.HTML(value="", elem_id="rec-output") session_state = gr.State(value={}) # ── Zgłoś problem lub zasugeruj grę ────────────────────────── gr.Markdown("---\n### Report an issue or suggest a game") problem_type = gr.Radio( choices=[ "Add game to database", "Missing / wrong banner", "Recommendations are not relevant", "Incorrect game information", "Other issue", ], label="Report type:", value=None, elem_id="problem-radio", ) # Panel dodania gry — z czerwonym nagłówkiem with gr.Group(visible=False, elem_id="missing-game-panel") as missing_game_panel: gr.HTML('

Game not in the database? Provide the title and author below:

') with gr.Row(): missing_name_input = gr.Textbox(label="Game title", placeholder="e.g. Mythic Manor", scale=3) missing_author_input = gr.Textbox(label="Author / developer", placeholder="e.g. Jikijy", scale=2) feedback_comment = gr.Textbox( label="Details (optional)", placeholder="Add any details that might help.", lines=2, visible=False, ) report_btn = gr.Button("Send report", variant="secondary", size="md") feedback_status = gr.Markdown("") # ── Bindings ────────────────────────────────────────────────── # Autouzupełnianie → HTML sugestii title_search_input.change( fn=lambda q: _render_suggestions_html(q), inputs=[title_search_input], outputs=[suggestions_html], ) # Bridge sugestii → dodaj tytuł sugg_bridge.change( fn=_add_from_sugg_bridge, inputs=[sugg_bridge, selected_titles_state], outputs=[selected_titles_state, chips_html, sugg_bridge, title_search_input], ) # Enter → dodaj pierwszą sugestię def _add_on_enter(q: str, titles: List[str]): q = (q or "").strip() if not q: return titles, _render_chips_html(titles), "", q hits = suggest_similar_titles(q, limit=1) if not hits: return titles, _render_chips_html(titles), "", q t = hits[0] if t not in titles: titles = titles + [t] return titles, _render_chips_html(titles), "", "" title_search_input.submit( fn=_add_on_enter, inputs=[title_search_input, selected_titles_state], outputs=[selected_titles_state, chips_html, suggestions_html, title_search_input], ) # Bridge chipów → usuń chip_bridge.change( fn=_remove_by_index, inputs=[chip_bridge, selected_titles_state], outputs=[selected_titles_state, chips_html, chip_bridge], ) # Clear all bridge def _clear_all(val): if (val or "").strip() != "1": return [], _render_chips_html([]), "" return [], _render_chips_html([]), "" clear_bridge.change( fn=_clear_all, inputs=[clear_bridge], outputs=[selected_titles_state, chips_html, clear_bridge], ) # Pokaż/ukryj panel brakującej gry def _toggle_missing_panel(ptype: Optional[str]): is_add_game = (ptype == "Add game to database") return ( gr.Group(visible=is_add_game), gr.Textbox(visible=not is_add_game and ptype is not None), ) problem_type.change( fn=_toggle_missing_panel, inputs=[problem_type], outputs=[missing_game_panel, feedback_comment], ) # Generuj rekomendacje run_btn.click( fn=lambda titles, req: run_recommendation(titles, 10, req), inputs=[selected_titles_state], outputs=[status, output_html, session_state], ) # Wyślij zgłoszenie def _submit_problem( ptype: Optional[str], comment: str, missing_name: str, missing_author: str, state: Dict[str, Any], request: gr.Request, ) -> str: label = ptype or "Problem" details = (comment or "").strip() if ptype == "Add game to database": name = (missing_name or "").strip() author = (missing_author or "").strip() if not name: return "Please fill in at least the game title." details = f"Title: {name}" + (f", author: {author}" if author else "") + (f". {details}" if details else "") full_comment = f"[{label}] {details}".strip() return submit_feedback(label, full_comment, state, request) report_btn.click( fn=_submit_problem, inputs=[problem_type, feedback_comment, missing_name_input, missing_author_input, session_state], outputs=[feedback_status], ) return demo app = build_app() if __name__ == "__main__": app.launch( server_name="0.0.0.0", server_port=7860, theme=gr.themes.Base(primary_hue="blue", secondary_hue="slate", neutral_hue="slate"), css=BLOCKS_CSS, head=BLOCKS_HEAD, )