Clipador: detecção do jogo cruzando categoria e tela (confiança, evidência e sugestão de troca)

Trabalho de outra sessão, commitado na sincronização de 18/11/2026 (doc/clipador/DETECCAO-JOGO.md).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Mateuus
2026-11-18 05:08:57 -03:00
co-authored by Claude Opus 5.5
parent e4a5bc026c
commit 44bb961d1a
13 changed files with 780 additions and 41 deletions
+6 -3
View File
@@ -75,9 +75,12 @@ saída: …" no contexto.
## Contexto do jogo
- Categoria da plataforma (Streamlink `--json`, `metadata.category`) no início e a cada 10 min (troca registrada em
`games_json`). Sem categoria (YouTube/VOD), o jogo vem da tela (`screen_game` da varredura). A IA também diz o que
vê na tela; divergência (categoria "ROB RUN", tela "GTA V") vai para o contexto dos juízes.
- **Detecção automática** (18/11/2026, `doc/clipador/DETECCAO-JOGO.md`): a cada ~3 min o Clipador cruza categoria da
plataforma (Streamlink `--json`), título, o que a IA lê na tela (`screen_game` + confiança + evidência, da varredura),
chat e fala (jogos cadastrados) e decide: `agreed` / `probable` / `conflict` / `unknown` (`sessions.game_status`,
pistas em `game_detect_json`). Categoria genérica (Just Chatting) não é jogo. Conflito (categoria "ROB RUN", tela
"GTA V") mantém o jogo e o painel pergunta. Jogo confirmado por você não muda sozinho (vira `suggestion`).
`POST /v1/sessions/{id}/game/detect` = "Detectar agora". Trocas ficam em `games_json`.
- **Perfil do jogo** pesquisado na web pela CLI (`codex --search`), guardado por jogo (tabela `games`): resumo,
mecânicas, o que rende corte, o que não rende, gírias, novidades, fontes. Medido: ~15–35 s por jogo.
- Correção manual: `PUT /v1/sessions/{id}/game` (trava a troca automática).
+7
View File
@@ -243,6 +243,13 @@ SCHEMA = [
PRIMARY KEY (session_id, idx)
);
""",
# v16: detecção do jogo (doc/clipador/DETECCAO-JOGO.md). `game_status`: user | agreed | probable | conflict | unknown
# ('' = sessão antiga, ainda não checada). `game_detect_json`: as pistas guardadas (categoria, tela), os candidatos
# com a nota, a sugestão de troca e a contagem de checagens seguidas.
"""
ALTER TABLE sessions ADD COLUMN game_status TEXT NOT NULL DEFAULT '';
ALTER TABLE sessions ADD COLUMN game_detect_json TEXT;
""",
]
+164
View File
@@ -0,0 +1,164 @@
"""Detecção do jogo da live: junta as pistas e decide qual é o jogo, com o grau de certeza.
Pedido do dono (18/11/2026): se ninguém lembrou de dizer o jogo, o Clipador descobre sozinho a cada ~3 min cruzando
várias fontes (a API da plataforma, o título, o que a IA lê na tela, o chat e a fala) e deixa o usuário
confirmar ou trocar. Este módulo é só a regra de decisão (sem banco, sem IA) para ser testável.
Pistas (`source`):
- platform: categoria da live (Streamlink/API). Autoridade da plataforma, mas pode estar abreviada, errada ou
genérica ("Just Chatting").
- screen: o jogo que a IA vê nos frames (logo, HUD, texto na tela), com a confiança que ela mesma declarou.
- title: o título da live cita um jogo conhecido.
- chat / speech: o chat e a fala dos últimos minutos citam um jogo conhecido (o nome ou um dos outros nomes).
Estados (`status`) do resultado:
- agreed: duas ou mais fontes independentes apontam o mesmo jogo.
- probable: uma fonte boa sozinha (ex.: só a categoria).
- conflict: a categoria e a tela (ou outras fontes fortes) apontam jogos diferentes — pergunta ao usuário.
- unknown: nenhuma pista útil.
"""
from __future__ import annotations
import re
import unicodedata
from dataclasses import dataclass, field
# Peso máximo de cada fonte (a força da pista, 0–1, multiplica). A categoria e a tela se equivalem de propósito:
# quando divergem, quem decide é o usuário (conflito), não um empate arbitrário.
SOURCE_WEIGHT = {"platform": 0.55, "screen": 0.5, "title": 0.25, "chat": 0.35, "speech": 0.35}
STRONG_SOURCES = ("platform", "screen")
CONFIDENCE = {"high": 1.0, "medium": 0.7, "low": 0.4}
AGREED_MIN = 0.6 # nota mínima para "várias fontes concordam"
PROBABLE_MIN = 0.34 # só a tela com confiança "média" (0,5 × 0,7 = 0,35) já vale como "provável"
CLEAR_LEAD = 0.25 # vantagem do 1º sobre o 2º para não ser conflito
CHAT_MIN_MESSAGES = 2 # uma mensagem solta citando um jogo é ruído
CHAT_FULL_AT = 6 # mensagens que dão força 1
SPEECH_FULL_AT = 3
# Categorias que não são jogo: não valem como pista de jogo (mas ficam registradas).
GENERIC_CATEGORIES = {
"just-chatting", "irl", "special-events", "music", "art", "asmr", "talk-shows-podcasts", "talk-shows",
"sports", "food-drink", "travel-outdoors", "pools-hot-tubs-beaches", "science-technology", "politics",
"software-and-game-development", "animals-aquariums-zoos", "fitness-health", "makers-crafting", "slots",
"games-demos", "just-sleeping", "retro", "gambling", "podcasts", "variety", "bate-papo", "so-bate-papo",
"unknown", "desconhecido", "nao-identificavel", "nenhum", "none", "n-a",
}
def deaccent(text: str) -> str:
return "".join(c for c in unicodedata.normalize("NFKD", text or "") if not unicodedata.combining(c))
def slug(text: str) -> str:
"""Sem acento ("Só Bate-papo" → "so-bate-papo"), minúsculo, palavras ligadas por hífen."""
return re.sub(r"[^a-z0-9]+", "-", deaccent(text).lower()).strip("-")[:60]
def is_generic(name: str) -> bool:
return not slug(name) or slug(name) in GENERIC_CATEGORIES
def form_ok(form: str) -> bool:
"""Forma de nome boa para procurar em texto solto: curta demais vira falso positivo ("it", "go")."""
return len(form) >= 4 or (len(form) >= 3 and any(c.isdigit() for c in form))
def count_mentions(texts: list[str], forms_by_game: dict[str, set[str]]) -> dict[str, int]:
"""Em quantas mensagens/frases cada jogo é citado. `forms_by_game`: id do jogo → nomes (já em `slug`).
O texto vira `-a-b-c-` e a forma `-gta-6-` precisa aparecer inteira (palavra inteira, sem pegar pedaço)."""
out: dict[str, int] = {}
wanted = {gid: [f"-{f}-" for f in forms if form_ok(f)] for gid, forms in forms_by_game.items()}
for text in texts:
# Duas leituras do texto: sem acento ("pokemon") e como o id do jogo foi gerado, que não tira acento
# (`intel.game_id("Pokémon")` = "pok-mon"). Casar com qualquer uma.
padded = (f"-{slug_all(text)}-", f"-{slug_all(text, fold=False)}-")
for gid, needles in wanted.items():
if any(n in p for n in needles for p in padded):
out[gid] = out.get(gid, 0) + 1
return out
def slug_all(text: str, fold: bool = True) -> str:
"""Como `slug`, sem o corte de 60 caracteres (textos longos: a fala de uns minutos). `fold=False` mantém os
acentos como separador (igual ao `game_id` do Clipador)."""
return re.sub(r"[^a-z0-9]+", "-", (deaccent(text) if fold else text or "").lower()).strip("-")
@dataclass
class Evidence:
source: str
game: str # nome como a fonte disse
gid: str # id canônico (resolvido pelo chamador: categoria "Grand Theft Auto VI" e tela "GTA 6" → o mesmo)
strength: float = 1.0 # 0–1
detail: str = ""
def score(self) -> float:
return SOURCE_WEIGHT.get(self.source, 0.1) * max(0.0, min(1.0, self.strength))
@dataclass
class Candidate:
gid: str
game: str
score: float = 0.0
evidence: list[Evidence] = field(default_factory=list)
@property
def sources(self) -> list[str]:
return sorted({e.source for e in self.evidence})
def view(self) -> dict:
return {"gid": self.gid, "game": self.game, "score": round(self.score, 2),
"sources": [{"source": e.source, "game": e.game, "strength": round(e.strength, 2), "detail": e.detail}
for e in self.evidence]}
@dataclass
class Decision:
status: str # agreed | probable | conflict | unknown
top: Candidate | None
candidates: list[Candidate]
def view(self) -> dict:
return {"status": self.status, "top": self.top.view() if self.top else None,
"candidates": [c.view() for c in self.candidates[:4]]}
def screen_strength(confidence: str) -> float:
return CONFIDENCE.get((confidence or "").strip().lower(), 0.7)
def fuse(evidence: list[Evidence]) -> Decision:
"""Pistas → candidatos (ruído-ou: cada fonte conta uma vez, a mais forte dela) → decisão."""
best: dict[tuple[str, str], Evidence] = {}
for e in evidence:
if not e.gid or e.strength <= 0:
continue
key = (e.gid, e.source)
if key not in best or e.score() > best[key].score():
best[key] = e
by_game: dict[str, Candidate] = {}
for (gid, _), e in best.items():
cand = by_game.setdefault(gid, Candidate(gid, e.game))
cand.evidence.append(e)
for cand in by_game.values():
miss = 1.0
for e in cand.evidence:
miss *= 1.0 - e.score()
cand.score = 1.0 - miss
# O nome mostrado: o da fonte mais forte (categoria > tela > resto).
cand.game = max(cand.evidence, key=lambda e: (e.source == "platform", e.source == "screen", e.score())).game
ranked = sorted(by_game.values(), key=lambda c: c.score, reverse=True)
if not ranked or ranked[0].score < 0.15:
return Decision("unknown", None, ranked)
top = ranked[0]
second = ranked[1] if len(ranked) > 1 else None
if second and second.score >= PROBABLE_MIN and top.score - second.score < CLEAR_LEAD \
and any(s in STRONG_SOURCES for s in second.sources):
return Decision("conflict", top, ranked)
if len(top.sources) >= 2 and top.score >= AGREED_MIN:
return Decision("agreed", top, ranked)
if top.score >= PROBABLE_MIN:
return Decision("probable", top, ranked)
return Decision("unknown", None, ranked)
+166 -9
View File
@@ -22,6 +22,10 @@ from . import clip_delete, layout
from .db import loads, now
from .emotes import EmoteCatalog, extract, learn_delta, message_bonus
from .face import FaceError, FaceUnavailable
from .game_detect import (
CHAT_FULL_AT, CHAT_MIN_MESSAGES, SPEECH_FULL_AT, Evidence, count_mentions, fuse, is_generic, screen_strength,
slug_all,
)
from .hashtags import fold, to_tag
from .judge import JudgeError, build_scan_prompt, game_context, lang_key, output_language_note
from .scoring import fit_window
@@ -36,7 +40,11 @@ log = logging.getLogger("cenaforge_clipper.intel")
OPTION_DEFAULTS = {"scanEnabled": True, "scanIntervalS": 180, "vision": True, "camDetect": True, "faceTrack": True}
CAM_RETRY_S = 300 # câmera não achada enquanto grava: nova tentativa depois de mais 5 min de gravação
CAM_MAX_ATTEMPTS = 6 # falha sem rosto decidido (poucos quadros legíveis): no máximo isto de tentativas
GAME_CHECK_S = 600 # rechecar a categoria da live a cada 10 min (o streamer troca de jogo)
GAME_CHECK_S = 180 # rechecar a categoria da live (e cruzar com tela, chat e fala) a cada 3 min: o streamer troca de jogo
UNKNOWN_GAMES = {"", "desconhecido", "não identificável", "nao identificavel", "unknown", "none", "n/a", "não sei", "nenhum"}
SCREEN_FRESH_S = 900 # o que a IA viu na tela vale como pista por 15 min
CHAT_WINDOW_S = 360 # chat e fala dos últimos 6 min entram na detecção do jogo
SPEECH_SEGMENTS = 12 # = 6 min de blocos de 30 s
SCAN_FRAME_EVERY_S = 30
SCAN_MAX_FRAMES = 7
MEMORY_KEEP = 6
@@ -132,6 +140,7 @@ class Intel:
self._weights: dict[str, tuple[float, dict[str, float]]] = {}
self._rooms_ready: set[str] = set()
self._game_checked: dict[int, float] = {}
self._detect_lock = threading.RLock() # `game_detect_json` é lido-e-gravado pelo laço de contexto e pela varredura
self._cam_retry_at: dict[int, float] = {} # falha transitória da câmera local (modelo/download): só em memória
self.last_scan_error: str | None = None
saved = {r["key"]: r["value"] for r in engine.db.all("SELECT key, value FROM settings")}
@@ -255,8 +264,8 @@ class Intel:
return len(names)
# ---------------------------------------------------------------- jogo
def check_game(self, session: dict, force: bool = False) -> None:
"""Categoria atual da live (Streamlink) → jogo da sessão; troca registrada; perfil pesquisado se novo."""
def check_game(self, session: dict, force: bool = False, detect: bool = True) -> None:
"""Categoria atual da live (Streamlink) e título → pistas da sessão; depois cruza tudo (`detect_game`)."""
if session["kind"] != "live":
return
last = self._game_checked.get(session["id"], 0)
@@ -268,9 +277,154 @@ class Intel:
return
if meta.get("title") and not session.get("title"):
self.e.db.run("UPDATE sessions SET title = ? WHERE id = ?", meta["title"][:200], session["id"])
category = (meta.get("category") or "").strip()
if category and category != session.get("game") and session.get("game_source") != "user":
self.set_game(session["id"], category, "platform")
with self._detect_lock:
state = self._detect_state(session["id"])
state["platform"] = {"game": (meta.get("category") or "").strip()[:120], "title": (meta.get("title") or "")[:200],
"at": now()}
self._save_detect_state(session["id"], state)
if detect:
self.detect_game(session["id"])
# ---- detecção do jogo (game_detect.py: a regra; aqui: juntar as pistas e aplicar)
def _detect_state(self, session_id: int) -> dict:
row = self.e.db.get("SELECT game_detect_json FROM sessions WHERE id = ?", session_id) or {}
state = loads(row.get("game_detect_json"), {})
return state if isinstance(state, dict) else {}
def _save_detect_state(self, session_id: int, state: dict) -> None:
self.e.db.run("UPDATE sessions SET game_detect_json = ? WHERE id = ?", json.dumps(state, ensure_ascii=False), session_id)
def canon(self, name: str) -> tuple[str, str]:
"""(id canônico, nome para mostrar): "GTA 6" e "Grand Theft Auto VI" dão o mesmo id quando o jogo está cadastrado."""
row = self.find_game(name)
return (row["id"], row["name"]) if row else (game_id(name), name.strip())
def note_screen(self, session_id: int, game: str, confidence: str = "", evidence: str = "") -> None:
"""O que a IA viu na tela (varredura ou "Detectar agora") vira pista; vale por SCREEN_FRESH_S."""
game = (game or "").strip()
if not game or game.lower() in UNKNOWN_GAMES:
return
with self._detect_lock:
state = self._detect_state(session_id)
state["screen"] = {"game": game[:120], "confidence": (confidence or "medium").lower()[:10],
"evidence": (evidence or "")[:240], "at": now(), "ts": time.time()}
self._save_detect_state(session_id, state)
def _mention_forms(self) -> tuple[dict[str, set[str]], dict[str, str]]:
"""Jogos conhecidos → formas de nome para procurar no texto (id, nome e outros nomes) e o nome de cada um."""
forms: dict[str, set[str]] = {}
names: dict[str, str] = {}
for row in self.e.db.all("SELECT id, name, aliases_json FROM games"):
if is_generic(row["id"]):
continue
forms[row["id"]] = {row["id"], slug_all(row["name"]), *loads(row["aliases_json"], [])}
names[row["id"]] = row["name"]
return forms, names
def _recent_texts(self, session_id: int) -> tuple[list[str], list[str]]:
"""(mensagens do chat, trechos de fala) dos últimos minutos — só texto cru, sem montar a linha do tempo."""
from .speakers import parse_words # import local: speakers importa módulos que importam este
chat = [r["text"] for r in self.e.db.all(
"SELECT text FROM chat WHERE session_id = ? AND wall >= (SELECT COALESCE(MAX(wall), 0) - ? FROM chat WHERE session_id = ?)",
session_id, CHAT_WINDOW_S, session_id)]
speech = [" ".join(w.word for w in parse_words(r["words_json"])) for r in self.e.db.all(
"SELECT words_json FROM segments WHERE session_id = ? AND analyzed = 1 ORDER BY idx DESC LIMIT ?",
session_id, SPEECH_SEGMENTS)]
return chat, speech
def gather_evidence(self, session: dict, state: dict) -> list[Evidence]:
out: list[Evidence] = []
forms, names = self._mention_forms()
plat = state.get("platform") or {}
if plat.get("game") and not is_generic(plat["game"]):
gid, _ = self.canon(plat["game"])
out.append(Evidence("platform", plat["game"], gid, 1.0, "categoria da live na plataforma"))
title = plat.get("title") or session.get("title") or ""
for gid, n in count_mentions([title], forms).items():
out.append(Evidence("title", names.get(gid, gid), gid, 1.0, "o título da live cita o jogo"))
screen = state.get("screen") or {}
if screen.get("game") and time.time() - float(screen.get("ts") or 0) < SCREEN_FRESH_S and not is_generic(screen["game"]):
gid, _ = self.canon(screen["game"])
out.append(Evidence("screen", screen["game"], gid, screen_strength(screen.get("confidence", "")),
screen.get("evidence") or "a IA viu o jogo nos frames"))
chat, speech = self._recent_texts(session["id"])
for gid, n in count_mentions(chat, forms).items():
if n >= CHAT_MIN_MESSAGES:
out.append(Evidence("chat", names.get(gid, gid), gid, min(1.0, n / CHAT_FULL_AT), f"{n} mensagem(ns) do chat citam o jogo"))
for gid, n in count_mentions(speech, forms).items():
out.append(Evidence("speech", names.get(gid, gid), gid, min(1.0, n / SPEECH_FULL_AT), f"citado em {n} trecho(s) da fala"))
return out
def detect_game(self, session_id: int, immediate: bool = False) -> dict | None:
"""Cruza as pistas (categoria, título, tela, chat e fala) e atualiza o jogo da sessão.
Regras: jogo que VOCÊ confirmou nunca muda sozinho (se as pistas apontarem outro jogo duas vezes seguidas,
vira `suggestion` para o painel perguntar); sem confirmação, só troca de jogo se a categoria da plataforma
apoiar ou se a mesma resposta vier duas checagens seguidas (`immediate` pula isso: pedido do usuário);
categoria e tela discordando = `conflict` (mantém o jogo e pergunta)."""
with self._detect_lock:
session = self.e.db.get("SELECT * FROM sessions WHERE id = ?", session_id)
if not session:
return None
state = self._detect_state(session_id)
decision = fuse(self.gather_evidence(session, state))
current = session.get("game") or ""
cur_gid = self.canon(current)[0] if current else ""
locked = session.get("game_source") == "user" and bool(current)
top = decision.top
state["candidates"] = [c.view() for c in decision.candidates[:4]]
state["checkedAt"] = now()
state["suggestion"] = None
status = decision.status
if locked:
status = "user"
if top and top.gid != cur_gid and decision.status == "agreed":
state["pending"] = self._streak(state, top.gid)
if state["pending"]["n"] >= 2:
state["suggestion"] = {"game": self.canon(top.game)[1], "score": round(top.score, 2), "sources": top.sources}
else:
state["pending"] = None
elif top and top.gid != cur_gid and (decision.status in ("agreed", "probable") or (decision.status == "conflict" and not current)):
platform_backs = any(e.source == "platform" for e in top.evidence)
state["pending"] = self._streak(state, top.gid)
if immediate or not current or is_generic(current) or platform_backs or state["pending"]["n"] >= 2:
source = "platform" if platform_backs else "screen" if "screen" in top.sources else "chat"
self.set_game(session_id, self.canon(top.game)[1], source)
state["pending"] = None
else:
state["pending"] = None
self.e.db.run("UPDATE sessions SET game_status = ? WHERE id = ?", status, session_id)
self._save_detect_state(session_id, state)
return {"status": status, **{k: state[k] for k in ("candidates", "suggestion")}}
@staticmethod
def _streak(state: dict, gid: str) -> dict:
pending = state.get("pending") or {}
return {"gid": gid, "n": pending.get("n", 0) + 1 if pending.get("gid") == gid else 1}
def detect_game_now(self, session_id: int) -> dict:
""""Detectar agora" (painel): a IA olha 3 frames recentes e diz que jogo é; depois cruza com o resto."""
session = self.e.db.get("SELECT * FROM sessions WHERE id = ?", session_id)
if not session:
raise JudgeError("sessão não encontrada")
if not (self.opts["vision"] and self.e.judge.enabled):
raise JudgeError("a detecção pela tela precisa da IA ligada e da visão ligada (Configurações → IA)")
d = session["duration_s"]
if d < 5:
raise JudgeError("gravação curta demais para olhar a tela")
times = sorted({max(1.0, d - 120), max(1.0, d - 60), max(1.0, d - 6)})
frames = self.frames(session, times, "game")
if not frames:
raise JudgeError("sem frames da tela (blocos apagados ou visão sem vídeo)")
data = self.e.judge.detect_game([p for _, p in frames], (self._detect_state(session_id).get("platform") or {}).get("title", ""))
game = str(data.get("game") or "").strip()
if game and game.lower() not in UNKNOWN_GAMES:
self.note_screen(session_id, game, str(data.get("confidence") or ""), str(data.get("evidence") or ""))
self.e.db.run("UPDATE sessions SET screen_game = ? WHERE id = ?", game[:120], session_id)
self.check_game(session, force=True, detect=False)
result = self.detect_game(session_id, immediate=True) or {}
return result | {"screen": {"game": game, "confidence": data.get("confidence", ""), "evidence": data.get("evidence", "")}}
def set_game(self, session_id: int, name: str, source: str) -> None:
session = self.e.db.get("SELECT * FROM sessions WHERE id = ?", session_id)
@@ -667,12 +821,15 @@ class Intel:
item["summaryPt"] = str(data["summary_pt"])[:240]
memory.append(item)
screen = str(data.get("screen_game") or "")
if screen.lower() in ("desconhecido", "não identificável", "nao identificavel", "unknown"):
if screen.strip().lower() in UNKNOWN_GAMES:
screen = ""
self.e.db.run("UPDATE sessions SET scanned_until = ?, memory_json = ?, screen_game = CASE WHEN ? != '' THEN ? ELSE screen_game END WHERE id = ?",
hi, json.dumps(memory[-MEMORY_KEEP:], ensure_ascii=False), screen, screen[:120], session["id"])
if screen and not session.get("game"):
self.set_game(session["id"], screen, "screen") # sem categoria (YouTube/VOD): o jogo vem da tela
if screen:
# A tela é uma pista (com a confiança e o que a IA leu), não a palavra final: cruza com categoria, título,
# chat e fala. Sem categoria (YouTube/VOD), a tela sozinha ainda define o jogo (estado "provável").
self.note_screen(session["id"], screen, str(data.get("screen_game_confidence") or ""), str(data.get("screen_evidence") or ""))
self.detect_game(session["id"])
return created
def _insert_scan_moment(self, session: dict, m: dict, lo: float, hi: float, dur: dict, existing: list) -> bool:
+34 -3
View File
@@ -181,11 +181,13 @@ SCAN_SCHEMA = {
"type": "object",
"properties": {
"screen_game": {"type": "string"},
"screen_game_confidence": {"type": "string", "enum": ["high", "medium", "low"]},
"screen_evidence": {"type": "string"},
"has_webcam": {"type": "boolean"},
"summary": {"type": "string"},
"moments": {"type": "array", "items": _MOMENT},
},
"required": ["screen_game", "has_webcam", "summary", "moments"],
"required": ["screen_game", "screen_game_confidence", "screen_evidence", "has_webcam", "summary", "moments"],
"additionalProperties": False,
}
_MISSION = {
@@ -268,7 +270,10 @@ Tarefa: aponte de 0 a 2 momentos desta janela que dariam um bom corte SOZINHOS.
moments=[] (é o normal na maior parte do tempo — não force). Não repita um corte já feito.
- start_s/end_s dentro da janela recebida (pode começar até o limite de "volta" informado para pegar a ação),
com a duração mínima/máxima informada.
- screen_game: o jogo que aparece na tela (ou "desconhecido"); has_webcam: há câmera do streamer no quadro?
- screen_game: o jogo que aparece na tela (ou "desconhecido"); screen_game_confidence: high (viu logo, nome ou HUD
inconfundível), medium (reconhece pelo visual) ou low (palpite); screen_evidence: o que você LEU ou VIU que prova
(ex.: "HUD com minimapa e estrelas de procurado", "texto MISSION PASSED"), em 1 frase curta e em português.
has_webcam: há câmera do streamer no quadro?
- summary: 1 frase do que está acontecendo na janela (vira memória para as próximas janelas).
- title/caption/reason como um editor faria (título ≤ 70 caracteres, verdadeiro; hashtags só do que há aqui).
Não use ferramentas além do que foi entregue. Responda só com o JSON pedido."""
@@ -335,6 +340,24 @@ PROFILE_SECTIONS = {"summary": "Resumo", "clip_worthy": "O que rende corte", "av
"hashtags": "Hashtags", "news": "Novidades", "jargon": "Gírias e termos", "sources": "Fontes",
"missions": "Missões", "end_triggers": "Gatilhos de fim de missão", "aliases": "Outros nomes"}
GAME_SCHEMA = {
"type": "object",
"properties": {
"game": {"type": "string"},
"confidence": {"type": "string", "enum": ["high", "medium", "low"]},
"evidence": {"type": "string"},
},
"required": ["game", "confidence", "evidence"],
"additionalProperties": False,
}
GAME_SYSTEM = """Você identifica QUAL JOGO está na tela de uma live, olhando frames do mesmo trecho (instantes diferentes).
Use só o que aparece: logo, nome do jogo, menus, HUD, interface, texto na tela, estilo visual. O título da live pode
dar uma dica, mas não é prova. Ignore overlays do streamer (alertas, chat, webcam). game: o nome oficial do jogo em
inglês (ex.: "Grand Theft Auto VI", "Call of Duty: Warzone") ou "desconhecido" se não der para saber, ou se a tela
mostra só conversa/menu da plataforma/área de trabalho. confidence: high (viu logo, nome ou HUD inconfundível),
medium (reconhece pelo visual) ou low (palpite). evidence: o que você LEU ou VIU que prova, em 1 frase curta em
português. Não invente. Responda só com o JSON pedido."""
CAM_SYSTEM = """Você analisa frames de uma live. Diga se há uma webcam/câmera do streamer sobreposta ao jogo e,
se houver, o retângulo DELA (só a câmera, sem bordas do overlay) em coordenadas normalizadas 0–1 do quadro:
x, y = canto superior esquerdo; w, h = largura e altura. Sem webcam: has_webcam=false e x=y=w=h=0.
@@ -497,7 +520,10 @@ Task: point out 0 to 2 moments in this window that would make a good clip ON THE
moments=[] (that's normal most of the time — don't force it). Don't repeat a clip already made.
- start_s/end_s inside the window (may start back to the "backtrack" limit to catch the action), within the
min/max duration given.
- screen_game: the game on screen (or "unknown"); has_webcam: is there a streamer camera in the frame?
- screen_game: the game on screen (or "unknown"); screen_game_confidence: high (saw the logo, title or an
unmistakable HUD), medium (recognised by the look) or low (a guess); screen_evidence: what you READ or SAW that
proves it (e.g. "minimap and wanted stars HUD", "MISSION PASSED text"), one short sentence, in Portuguese.
has_webcam: is there a streamer camera in the frame?
- summary: 1 sentence of what's going on in the window (becomes memory for the next windows).
- title/caption/reason in English like an editor would write (title ≤ 70 characters, true).
- summary_pt and each moment's pt (title, reason): translated. """ + PT_NOTE + """
@@ -1022,6 +1048,11 @@ class Judge:
"Return the translated profile.")
return self.ask(TRANSLATE_SYSTEM, prompt, PROFILE_SCHEMA, [], timeout=RESEARCH_TIMEOUT_S)
def detect_game(self, images: list[Path], live_title: str = "") -> dict:
prompt = (f"Título da live (só uma dica): {live_title or '(sem título)'}\n"
"Identifique o jogo nos frames anexados.")
return self.ask(GAME_SYSTEM, prompt, GAME_SCHEMA, images)
def detect_cam(self, images: list[Path]) -> dict:
return self.ask(CAM_SYSTEM, "Analise os frames anexados (mesma live, instantes diferentes).", CAM_SCHEMA, images)
+27
View File
@@ -213,6 +213,18 @@ def clip_view(row: dict) -> dict:
}
def game_detect_view(row: dict) -> dict | None:
"""O que o painel mostra da detecção do jogo: pistas guardadas, candidatos, sugestão de troca e quando checou."""
state = loads(row.get("game_detect_json"), None)
if not isinstance(state, dict):
return None
screen = state.get("screen") or {}
return {"checkedAt": state.get("checkedAt"), "candidates": state.get("candidates") or [],
"suggestion": state.get("suggestion"),
"platform": {"game": (state.get("platform") or {}).get("game", ""), "at": (state.get("platform") or {}).get("at")},
"screen": {k: screen.get(k, "") for k in ("game", "confidence", "evidence", "at")} if screen else None}
def session_view(row: dict, engine: Engine) -> dict:
counts = {r["status"]: r["n"] for r in engine.db.all(
"SELECT status, COUNT(*) AS n FROM clips WHERE session_id = ? GROUP BY status", row["id"])}
@@ -231,6 +243,9 @@ def session_view(row: dict, engine: Engine) -> dict:
# Contexto do jogo: categoria da plataforma, o que a IA viu na tela, trocas e se você corrigiu à mão.
"game": row.get("game", ""), "gameSource": row.get("game_source", ""), "screenGame": row.get("screen_game", ""),
"gameHistory": loads(row.get("games_json"), []), "gameProfileReady": bool(engine.intel.profile(row.get("game", ""))),
# Detecção do jogo (doc/clipador/DETECCAO-JOGO.md): estado (user|agreed|probable|conflict|unknown), as pistas
# (categoria, tela), os candidatos com nota e, se o jogo confirmado por você parece ter mudado, a sugestão.
"gameStatus": row.get("game_status", ""), "gameDetect": game_detect_view(row),
"scannedUntilS": row.get("scanned_until", 0), "memory": loads(row.get("memory_json"), []),
"camDetect": loads(row.get("cam_json"), None), "roomId": row.get("room_id"),
"hasOwnSettings": bool(loads(row.get("settings_json"), {})),
@@ -461,8 +476,20 @@ def create_app(settings: Settings | None = None, engine: Engine | None = None, s
"""Corrige o jogo à mão (categoria errada). Fica travado: a checagem automática não troca mais."""
_session(session_id)
engine.intel.set_game(session_id, body.name.strip(), "user")
engine.intel.detect_game(session_id) # grava o estado "confirmado" e limpa a sugestão
return session_view(_session(session_id), engine)
@app.post("/v1/sessions/{session_id}/game/detect")
def detect_game(session_id: int):
""""Detectar agora": a IA olha frames recentes, cruza com categoria, título, chat e fala e atualiza o jogo.
Jogo confirmado por você não muda (só aparece como sugestão). Leva de 10 s a 1 min (chamada à IA)."""
_session(session_id)
try:
result = engine.intel.detect_game_now(session_id)
except JudgeError as exc:
raise UserError(str(exc)) from exc
return {"result": result, "session": session_view(_session(session_id), engine)}
def game_view(g: dict) -> dict:
# `profile` = português (o painel mostra); `profileAi` = inglês (vai nos prompts; null = jogo antigo, a IA
# usa `profile`). Contrato em doc/clipador/JOGOS.md.
+189
View File
@@ -0,0 +1,189 @@
"""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"]