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:
co-authored by
Claude Opus 5.5
parent
e4a5bc026c
commit
44bb961d1a
+166
-9
@@ -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:
|
||||
|
||||
Reference in New Issue
Block a user