"""Detecção do jogo (doc/clipador/DETECCAO-JOGO.md): fusão das pistas, aplicação na sessão e rota "Detectar agora".""" import json from pathlib import Path from app.game_detect import Evidence, count_mentions, fuse, is_generic from tests.test_sources_and_api import FakeJudge, auth, env, seed_session # noqa: F401 - fixture reaproveitada GTA = "grand-theft-auto-vi" ALIASES = {GTA: {GTA, "gta-6", "gta6", "gta-vi"}, "rob-run": {"rob-run", "robrun"}} # ---------------------------------------------------------------- regra pura def test_generic_categories_are_not_games(): assert is_generic("Just Chatting") and is_generic("Só Bate-papo") and is_generic("") and not is_generic("Rust") def test_mentions_match_whole_names_only(): texts = ["olha o GTA 6 que loucura", "gta6 hype", "gtavi", "o artista fez isso", "robrunner hoje", "ROB RUN!!"] counts = count_mentions(texts, ALIASES) assert counts == {GTA: 2, "rob-run": 1} # "gtavi" não é alias aqui; "robrunner" não é "rob run" def test_platform_alone_is_probable_and_agreement_is_agreed(): alone = fuse([Evidence("platform", "Rust", "rust")]) assert alone.status == "probable" and alone.top.gid == "rust" agreed = fuse([Evidence("platform", "Rust", "rust"), Evidence("screen", "Rust", "rust", 0.7)]) assert agreed.status == "agreed" and agreed.top.sources == ["platform", "screen"] def test_category_and_screen_disagreeing_is_a_conflict(): decision = fuse([Evidence("platform", "ROB RUN", "rob-run"), Evidence("screen", "GTA V", "gta-v", 1.0)]) assert decision.status == "conflict" and {c.gid for c in decision.candidates} == {"rob-run", "gta-v"} def test_screen_alone_counts_and_weak_signals_do_not(): assert fuse([Evidence("screen", "Rust", "rust", 0.7)]).status == "probable" # tela com confiança média assert fuse([Evidence("screen", "Rust", "rust", 0.4)]).status == "unknown" # palpite assert fuse([Evidence("speech", "Rust", "rust", 0.33)]).status == "unknown" # citada uma vez só assert fuse([]).status == "unknown" def test_chat_and_screen_beat_a_lone_category(): # Categoria diz A; tela, chat e fala dizem B: B passa com folga, não é conflito. decision = fuse([Evidence("platform", "A", "a"), Evidence("screen", "B", "b", 1.0), Evidence("chat", "B", "b", 1.0), Evidence("speech", "B", "b", 1.0)]) assert decision.top.gid == "b" and decision.status in ("agreed", "conflict") # ---------------------------------------------------------------- aplicação na sessão def add_game(engine, gid=GTA, name="Grand Theft Auto VI", aliases=("gta-6", "gta6", "gta-vi")): engine.db.run("INSERT INTO games (id, name, status, aliases_json) VALUES (?, ?, 'ready', ?)", gid, name, json.dumps(list(aliases))) def platform(engine, sid, category, title=""): state = engine.intel._detect_state(sid) state["platform"] = {"game": category, "title": title, "at": "2026-11-18T00:00:00+00:00"} engine.intel._save_detect_state(sid, state) def session(engine, sid): return engine.db.get("SELECT * FROM sessions WHERE id = ?", sid) def test_category_sets_the_game_immediately(env): # noqa: F811 _, engine = env sid = seed_session(engine) platform(engine, sid, "Rust") result = engine.intel.detect_game(sid) row = session(engine, sid) assert row["game"] == "Rust" and row["game_source"] == "platform" and row["game_status"] == "probable" assert result["status"] == "probable" def test_generic_category_is_not_a_game_and_screen_fills_in(env): # noqa: F811 _, engine = env sid = seed_session(engine) platform(engine, sid, "Just Chatting") engine.intel.detect_game(sid) assert session(engine, sid)["game"] == "" and session(engine, sid)["game_status"] == "unknown" engine.intel.note_screen(sid, "Rust", "high", "logo do Rust no menu") engine.intel.detect_game(sid) row = session(engine, sid) assert row["game"] == "Rust" and row["game_source"] == "screen" def test_chat_and_title_find_a_known_game_without_category(env): # noqa: F811 _, engine = env add_game(engine) sid = seed_session(engine) wall = engine.db.get("SELECT MAX(wall) AS w FROM chat WHERE session_id = ?", sid)["w"] engine.db.many("INSERT INTO chat (session_id, wall, user, text) VALUES (?, ?, ?, ?)", [(sid, wall - i, "u", "esse GTA 6 é lindo demais") for i in range(8)]) platform(engine, sid, "", title="Primeira vez no GTA VI!!") engine.intel.detect_game(sid) row = session(engine, sid) assert row["game"] == "Grand Theft Auto VI" and row["game_source"] == "chat" evidence = json.loads(row["game_detect_json"])["candidates"][0]["sources"] assert {e["source"] for e in evidence} >= {"chat", "title"} and row["game_status"] == "probable" def test_screen_with_another_alias_agrees_with_the_category(env): # noqa: F811 _, engine = env add_game(engine) sid = seed_session(engine) platform(engine, sid, "Grand Theft Auto VI") engine.intel.note_screen(sid, "GTA 6", "high", "HUD com estrelas de procurado") engine.intel.detect_game(sid) row = session(engine, sid) assert row["game_status"] == "agreed" and row["game"] == "Grand Theft Auto VI" def test_conflict_keeps_the_game_and_asks(env): # noqa: F811 _, engine = env sid = seed_session(engine) platform(engine, sid, "ROB RUN") engine.intel.detect_game(sid) engine.intel.note_screen(sid, "GTA V", "high", "mapa de Los Santos") engine.intel.detect_game(sid) row = session(engine, sid) assert row["game"] == "ROB RUN" and row["game_status"] == "conflict" assert {c["game"] for c in json.loads(row["game_detect_json"])["candidates"]} == {"ROB RUN", "GTA V"} def test_screen_only_change_needs_two_checks_in_a_row(env): # noqa: F811 _, engine = env engine.db.run("INSERT INTO games (id, name, status) VALUES ('rust', 'Rust', 'ready')") sid = seed_session(engine) engine.intel.set_game(sid, "Rust", "screen") engine.intel.note_screen(sid, "Hollow Knight", "high", "tela de título") engine.intel.detect_game(sid) assert session(engine, sid)["game"] == "Rust" # 1ª vez: espera engine.intel.detect_game(sid) row = session(engine, sid) assert row["game"] == "Hollow Knight" and [h["game"] for h in json.loads(row["games_json"])] == ["Rust", "Hollow Knight"] def test_confirmed_game_never_changes_but_suggests(env): # noqa: F811 client, engine = env add_game(engine) sid = seed_session(engine) r = client.put(f"/v1/sessions/{sid}/game", json={"name": "Rust"}, headers=auth()) assert r.json()["gameStatus"] == "user" and r.json()["gameDetect"]["suggestion"] is None platform(engine, sid, "Grand Theft Auto VI") engine.intel.note_screen(sid, "GTA 6", "high", "HUD") engine.intel.detect_game(sid) assert session(engine, sid)["game"] == "Rust" assert engine.intel._detect_state(sid)["suggestion"] is None # 1ª vez: ainda não sugere engine.intel.detect_game(sid) row = session(engine, sid) assert row["game"] == "Rust" and row["game_source"] == "user" and row["game_status"] == "user" assert json.loads(row["game_detect_json"])["suggestion"]["game"] == "Grand Theft Auto VI" view = client.get(f"/v1/sessions/{sid}", headers=auth()).json() assert view["gameDetect"]["suggestion"]["game"] == "Grand Theft Auto VI" # ---------------------------------------------------------------- "Detectar agora" class VisionJudge(FakeJudge): def __init__(self, answer): super().__init__() self.answer, self.asked = answer, [] @property def enabled(self): return True def detect_game(self, images, live_title=""): self.asked.append((len(images), live_title)) return self.answer def test_detect_now_uses_frames_and_applies_immediately(env, monkeypatch): # noqa: F811 client, engine = env engine.judge = VisionJudge({"game": "Hollow Knight", "confidence": "high", "evidence": "tela de título do jogo"}) monkeypatch.setattr(engine.intel, "frames", lambda s, times, tag: [(t, Path(f"{tag}-{int(t)}.jpg")) for t in times]) sid = seed_session(engine) r = client.post(f"/v1/sessions/{sid}/game/detect", headers=auth()) assert r.status_code == 200, r.text body = r.json() assert body["session"]["game"] == "Hollow Knight" and body["session"]["gameSource"] == "screen" assert body["result"]["screen"]["evidence"] == "tela de título do jogo" assert engine.judge.asked and engine.judge.asked[0][0] == 3 def test_detect_now_explains_when_ai_is_off(env): # noqa: F811 client, engine = env engine.judge.provider = "off" sid = seed_session(engine) r = client.post(f"/v1/sessions/{sid}/game/detect", headers=auth()) assert r.status_code == 400 and "IA" in r.json()["error"]