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
+6
-3
@@ -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).
|
||||
|
||||
@@ -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;
|
||||
""",
|
||||
]
|
||||
|
||||
|
||||
|
||||
@@ -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
@@ -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
@@ -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)
|
||||
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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"]
|
||||
@@ -0,0 +1,65 @@
|
||||
# Clipador — detecção automática do jogo (18/11/2026)
|
||||
|
||||
## Pedido do dono
|
||||
|
||||
Se ninguém lembrar de dizer o jogo, o Clipador descobre sozinho, **a cada ~3 min**, cruzando tudo o que a live dá
|
||||
(API da plataforma, título, o que a IA lê na tela, chat e fala), tenta acertar, **pede confirmação** e deixa
|
||||
**trocar** se estiver errado.
|
||||
|
||||
## Pistas (`app/game_detect.py`, a regra; `app/intel.py`, juntar e aplicar)
|
||||
|
||||
| Fonte | O que é | Peso máx. |
|
||||
|---|---|---|
|
||||
| `platform` | Categoria da live (Streamlink `--json`), lida a cada 3 min. Categoria genérica ("Just Chatting", "IRL", "Música"…) não conta como jogo. | 0,55 |
|
||||
| `screen` | O jogo que a IA vê nos frames (logo, HUD, texto na tela). A varredura de 3 min já devolve `screen_game` + `screen_game_confidence` (high/medium/low) + `screen_evidence` (o que ela leu/viu). Vale por 15 min. | 0,50 × confiança |
|
||||
| `title` | O título da live cita um jogo cadastrado (nome ou outro nome). | 0,25 |
|
||||
| `chat` | Mensagens dos últimos 6 min citam um jogo cadastrado (mínimo 2 mensagens; força 1 com 6). | 0,35 |
|
||||
| `speech` | Trechos de fala dos últimos 6 min (12 blocos) citam um jogo cadastrado (força 1 com 3). | 0,35 |
|
||||
|
||||
Nomes iguais viram o mesmo jogo pelos **outros nomes** (`aliases`): categoria "Grand Theft Auto VI" + tela "GTA 6" +
|
||||
chat "gta6" = um jogo só. A busca em texto só acha jogos **cadastrados** (a lista de Jogos) e só por palavra inteira
|
||||
(nome com 4+ letras, ou 3 com número, ex. `cs2`). Acentos não atrapalham.
|
||||
|
||||
## Decisão
|
||||
|
||||
Cada jogo ganha uma nota (ruído-ou das fontes, cada fonte conta uma vez). O estado (`sessions.game_status`):
|
||||
|
||||
| Estado | Quando | O que o Clipador faz |
|
||||
|---|---|---|
|
||||
| `user` | Você confirmou. | **Nunca troca sozinho.** Se as pistas apontarem outro jogo (várias fontes concordando) em 2 checagens seguidas, grava uma `suggestion` e o painel pergunta "o streamer trocou de jogo?". |
|
||||
| `agreed` | 2+ fontes independentes no mesmo jogo, nota ≥ 0,6. | Aplica. |
|
||||
| `probable` | Uma fonte boa sozinha (só a categoria; ou só a tela com confiança média). | Aplica e pede "Sim, é X". |
|
||||
| `conflict` | Categoria × tela (fontes fortes) em jogos diferentes e sem folga (< 0,25). | **Mantém o jogo atual** e pergunta qual é o certo. |
|
||||
| `unknown` | Sem pista útil (ex.: Just Chatting e nada na tela). | Não mexe. |
|
||||
|
||||
Trocar de um jogo já definido (sem confirmação do usuário) exige a categoria da plataforma apoiando **ou** a mesma
|
||||
resposta em 2 checagens seguidas (evita trocar por um frame de menu). "Detectar agora" pula essa espera.
|
||||
|
||||
## Estado guardado
|
||||
|
||||
- `sessions.game_status` e `sessions.game_detect_json` (v16): pistas (`platform`, `screen`), `candidates` (até 4, com nota
|
||||
e cada pista), `suggestion`, `pending` (checagens seguidas) e `checkedAt`.
|
||||
- `sessions.game` / `game_source` (`platform` | `screen` | `chat` | `user`) / `games_json` (histórico de trocas) continuam
|
||||
como antes; o perfil do jogo é pesquisado se o jogo é novo.
|
||||
|
||||
## Contrato (serviço ↔ painel)
|
||||
|
||||
- `GET /v1/sessions[/{id}]` ganha `gameStatus` e `gameDetect` = `{checkedAt, candidates[{gid, game, score, sources[{source, game, strength, detail}]}], suggestion|null, platform{game, at}, screen{game, confidence, evidence, at}|null}`.
|
||||
- `PUT /v1/sessions/{id}/game {name}`: confirma (estado `user`, limpa a sugestão).
|
||||
- `POST /v1/sessions/{id}/game/detect` ("Detectar agora"): a IA olha 3 frames dos últimos 2 min, cruza com o resto e aplica
|
||||
na hora. Responde `{result: {status, candidates, suggestion, screen{game, confidence, evidence}}, session}`. Exige IA e visão
|
||||
ligadas (erro 400 em português se não).
|
||||
|
||||
## Painel (detalhe da sessão)
|
||||
|
||||
Selo do estado (confirmado por você · detectado, fontes concordam · provável, confirme · em dúvida · não identificado),
|
||||
"Sim, é X", "Escolher/Trocar jogo" (a lista inclui os candidatos), **Detectar agora**, aviso de conflito com um botão por
|
||||
candidato, aviso de sugestão de troca (jogo confirmado) e "Como o jogo foi descoberto" (categoria, tela com o que a IA
|
||||
leu, e cada candidato com nota e pistas). Na lista de sessões o selo "confirmar" aparece nos mesmos casos.
|
||||
|
||||
## Limites conhecidos
|
||||
|
||||
- Sem a varredura (IA/visão desligadas) não há pista de tela; o botão "Detectar agora" também precisa da IA.
|
||||
- Sem leitor de texto (OCR) próprio: o texto na tela é lido pela IA de visão (`screen_evidence`).
|
||||
- Chat e fala só reconhecem jogos já cadastrados em **Jogos** (os que passaram pela categoria entram sozinhos).
|
||||
- Categoria genérica não vira jogo: a sessão fica sem jogo até a tela, o chat ou você dizerem qual é.
|
||||
@@ -87,6 +87,9 @@ export type ClipperSession = {
|
||||
// Fase 2 (opcionais: o serviço antigo não manda).
|
||||
game?: string;
|
||||
gameSource?: GameSource;
|
||||
/** Detecção do jogo: user (você confirmou) | agreed (várias fontes concordam) | probable | conflict | unknown. "" = ainda não checou. */
|
||||
gameStatus?: GameStatus;
|
||||
gameDetect?: GameDetect | null;
|
||||
/** O que a IA viu na tela; pode divergir da categoria da plataforma. */
|
||||
screenGame?: string;
|
||||
gameHistory?: { game: string; source: GameSource; atS: number; at: string }[];
|
||||
@@ -103,7 +106,19 @@ export type ClipperSession = {
|
||||
language?: string;
|
||||
};
|
||||
|
||||
export type GameSource = "platform" | "screen" | "user" | "";
|
||||
export type GameSource = "platform" | "screen" | "chat" | "user" | "";
|
||||
export type GameStatus = "user" | "agreed" | "probable" | "conflict" | "unknown" | "";
|
||||
/** Uma pista do jogo: `source` = platform | screen | title | chat | speech. */
|
||||
export type GameClue = { source: string; game: string; strength: number; detail: string };
|
||||
export type GameCandidate = { gid: string; game: string; score: number; sources: GameClue[] };
|
||||
export type GameDetect = {
|
||||
checkedAt: string | null;
|
||||
candidates: GameCandidate[];
|
||||
/** Jogo confirmado por você que parece ter mudado (as pistas apontaram outro duas vezes seguidas). */
|
||||
suggestion: { game: string; score: number; sources: string[] } | null;
|
||||
platform: { game: string; at: string | null };
|
||||
screen: { game: string; confidence: string; evidence: string; at: string } | null;
|
||||
};
|
||||
/** `summaryPt`: fonte em inglês — o resumo em português para o painel (`summary` é o inglês que vai à IA). */
|
||||
export type MemoryEntry = { fromS: number; toS: number; summary: string; summaryPt?: string };
|
||||
export type CamDetect = {
|
||||
@@ -510,9 +525,20 @@ export const SITUATION_LABEL: Record<Situation, string> = {
|
||||
};
|
||||
|
||||
export const GAME_SOURCE_LABEL: Record<GameSource, string> = {
|
||||
platform: "categoria da plataforma", screen: "a IA viu na tela", user: "confirmado por você", "": "",
|
||||
platform: "categoria da plataforma", screen: "a IA viu na tela", chat: "citado no chat e na fala", user: "confirmado por você", "": "",
|
||||
};
|
||||
|
||||
export const GAME_CLUE_LABEL: Record<string, string> = {
|
||||
platform: "categoria da plataforma", screen: "tela (IA)", title: "título da live", chat: "chat", speech: "fala",
|
||||
};
|
||||
|
||||
/** O jogo da sessão precisa de uma olhada sua: pistas em conflito, ou o jogo confirmado parece ter mudado. */
|
||||
export function gameNeedsReview(s: ClipperSession): boolean {
|
||||
if (s.gameStatus === "user") return Boolean(s.gameDetect?.suggestion);
|
||||
if (s.gameStatus) return s.gameStatus === "conflict";
|
||||
return Boolean(s.game && s.screenGame && s.gameSource !== "user" && gameIdOf(s.screenGame) !== gameIdOf(s.game)); // serviço antigo
|
||||
}
|
||||
|
||||
export const MODE_LABEL: Record<LayoutMode, { label: string; hint: string }> = {
|
||||
auto: { label: "Automático", hint: "câmera em cima se houver" },
|
||||
cam_top: { label: "Câmera em cima", hint: "webcam + jogo" },
|
||||
|
||||
@@ -5,10 +5,11 @@
|
||||
// A página Jogos (lista + modal) fica em clipper-games-page.tsx.
|
||||
import { useEffect, useMemo, useRef, useState, type ReactNode } from "react";
|
||||
import {
|
||||
GAME_SOURCE_LABEL, clipperCall, gameIdOf, useClipperAction, type ClipperSession, type Emote, type Game,
|
||||
ACTIVE_SESSION, GAME_CLUE_LABEL, GAME_SOURCE_LABEL, clipperCall, gameIdOf, gameNeedsReview, useClipperAction,
|
||||
type ClipperSession, type Emote, type Game,
|
||||
} from "./clipper-client";
|
||||
import { GameDialog } from "./clipper-game-dialog";
|
||||
import { AlertIcon, BookIcon, ChatIcon, CheckIcon, ChevronDownIcon, PenIcon } from "./icons";
|
||||
import { AlertIcon, BookIcon, ChatIcon, CheckIcon, ChevronDownIcon, EyeIcon, PenIcon } from "./icons";
|
||||
import { Badge, Button, Feedback, Input, Spinner, Table, Td, Th, THead, Tr, cx, formatRelative } from "./ui";
|
||||
|
||||
/* ---------- Jogo da sessão ---------- */
|
||||
@@ -20,34 +21,52 @@ export function SessionGame({ session, games, onChanged, onGamesChanged }: {
|
||||
const [choosing, setChoosing] = useState(false);
|
||||
const [open, setOpen] = useState(false);
|
||||
const game = session.game ?? "";
|
||||
const screen = session.screenGame ?? "";
|
||||
const confirmed = session.gameSource === "user";
|
||||
const mismatch = Boolean(game && screen && !confirmed && gameIdOf(screen) !== gameIdOf(game));
|
||||
const confirmed = session.gameStatus ? session.gameStatus === "user" : session.gameSource === "user";
|
||||
const detect = session.gameDetect ?? null;
|
||||
const suggestion = confirmed ? detect?.suggestion ?? null : null;
|
||||
const conflict = !confirmed && gameNeedsReview(session);
|
||||
const profile = game ? findGame(games, game) : undefined;
|
||||
const status = STATUS_BADGE[session.gameStatus ?? ""] ?? STATUS_BADGE[""];
|
||||
const active = ACTIVE_SESSION.includes(session.status);
|
||||
// Candidatos do conflito: o jogo atual e os outros que as pistas apontaram (com a nota).
|
||||
const candidates = (detect?.candidates ?? []).filter((c) => c.score >= 0.3).slice(0, 3);
|
||||
|
||||
/** Confirma o jogo: trava a troca automática e a IA deixa de questionar o que vê na tela. */
|
||||
async function confirmGame(name: string) {
|
||||
const ok = await run("game", () => clipperCall<ClipperSession>(`sessions/${session.id}/game`, "PUT", { name }),
|
||||
`Jogo confirmado: “${name}”. A IA não questiona mais o jogo nesta sessão.`);
|
||||
`Jogo confirmado: “${name}”. A detecção automática não troca mais o jogo desta sessão (só sugere).`);
|
||||
if (ok) setChoosing(false);
|
||||
}
|
||||
|
||||
/** "Detectar agora": a IA olha frames recentes e cruza com categoria, título, chat e fala. */
|
||||
async function detectNow() {
|
||||
await run("detect", () => clipperCall<{ session: ClipperSession; result: { status: string; screen?: { game: string } } }>(
|
||||
`sessions/${session.id}/game/detect`, "POST"),
|
||||
(data) => data.result.screen?.game
|
||||
? `A IA viu “${data.result.screen.game}” na tela.`
|
||||
: "A IA não conseguiu reconhecer o jogo na tela agora.");
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="grid gap-2">
|
||||
<div className="flex flex-wrap items-center gap-x-3 gap-y-2 text-xs">
|
||||
<span className="text-eyebrow font-semibold text-fg-subtle uppercase">Jogo</span>
|
||||
<span className="text-sm font-medium text-fg">{game || <span className="text-fg-subtle">não identificado</span>}</span>
|
||||
{session.gameSource && (
|
||||
<Badge tone={confirmed ? "success" : "neutral"} dot={false}>
|
||||
{confirmed && <CheckIcon size={12} />}{GAME_SOURCE_LABEL[session.gameSource]}
|
||||
<Badge tone={status.tone} dot={false}>
|
||||
{status.check && <CheckIcon size={12} />}{status.label}
|
||||
</Badge>
|
||||
)}
|
||||
{game && !confirmed && (
|
||||
<Button variant="secondary" size="sm" disabled={pending !== null} onClick={() => void confirmGame(game)}>
|
||||
{pending === "game" ? <Spinner className="size-3.5" /> : <CheckIcon size={14} />}Sim, é {game}
|
||||
</Button>
|
||||
)}
|
||||
<Button variant="ghost" size="sm" onClick={() => setChoosing(true)}><PenIcon size={14} />{confirmed ? "Trocar jogo" : "Escolher o jogo"}</Button>
|
||||
{active && (
|
||||
<Button variant="ghost" size="sm" disabled={pending !== null} onClick={() => void detectNow()}
|
||||
title="A IA olha frames recentes da tela e cruza com categoria, título, chat e fala">
|
||||
{pending === "detect" ? <Spinner className="size-3.5" /> : <EyeIcon size={14} />}Detectar agora
|
||||
</Button>
|
||||
)}
|
||||
{game && (
|
||||
<Button variant="ghost" size="sm" aria-haspopup="dialog" onClick={() => setOpen(true)}>
|
||||
<BookIcon size={14} />O que a IA sabe do jogo
|
||||
@@ -55,14 +74,54 @@ export function SessionGame({ session, games, onChanged, onGamesChanged }: {
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
{mismatch && (
|
||||
{conflict && (
|
||||
<div className="flex flex-wrap items-center gap-x-3 gap-y-2 rounded-control border border-warning/25 bg-warning-soft px-3 py-2 text-xs text-warning">
|
||||
<AlertIcon size={14} />
|
||||
<span className="min-w-0 flex-1">A categoria diz <strong>{game}</strong>, mas a tela parece <strong>{screen}</strong>. Jogo novo costuma lembrar outro na tela — qual é o certo?</span>
|
||||
<Button size="sm" variant="secondary" disabled={pending !== null} onClick={() => void confirmGame(game)}>Sim, é {game}</Button>
|
||||
<Button size="sm" variant="ghost" onClick={() => setChoosing(true)}>Escolher o jogo</Button>
|
||||
<span className="min-w-0 flex-1">
|
||||
As pistas divergem: {candidates.map((c, i) => (
|
||||
<span key={c.gid}>{i > 0 && " × "}<strong>{c.game}</strong> ({c.sources.map((x) => GAME_CLUE_LABEL[x.source] ?? x.source).join(", ")})</span>
|
||||
))}. Jogo novo costuma lembrar outro na tela — qual é o certo?
|
||||
</span>
|
||||
{candidates.map((c) => (
|
||||
<Button key={c.gid} size="sm" variant="secondary" disabled={pending !== null} onClick={() => void confirmGame(c.game)}>É {c.game}</Button>
|
||||
))}
|
||||
<Button size="sm" variant="ghost" onClick={() => setChoosing(true)}>Outro</Button>
|
||||
</div>
|
||||
)}
|
||||
{suggestion && (
|
||||
<div className="flex flex-wrap items-center gap-x-3 gap-y-2 rounded-control border border-warning/25 bg-warning-soft px-3 py-2 text-xs text-warning">
|
||||
<AlertIcon size={14} />
|
||||
<span className="min-w-0 flex-1">
|
||||
Você confirmou <strong>{game}</strong>, mas as últimas checagens apontam <strong>{suggestion.game}</strong>
|
||||
{" "}({suggestion.sources.map((x) => GAME_CLUE_LABEL[x] ?? x).join(", ")}). O streamer trocou de jogo?
|
||||
</span>
|
||||
<Button size="sm" variant="secondary" disabled={pending !== null} onClick={() => void confirmGame(suggestion.game)}>Sim, é {suggestion.game}</Button>
|
||||
<Button size="sm" variant="ghost" disabled={pending !== null} onClick={() => void confirmGame(game)}>Não, continua {game}</Button>
|
||||
</div>
|
||||
)}
|
||||
{detect && (detect.candidates.length > 0 || detect.platform.game || detect.screen) && (
|
||||
<details className="group text-xs text-fg-muted">
|
||||
<summary className="cursor-pointer text-fg-subtle select-none hover:text-fg">
|
||||
Como o jogo foi descoberto{detect.checkedAt ? ` · checado ${formatRelative(detect.checkedAt)}` : ""}
|
||||
</summary>
|
||||
<ul className="mt-2 grid gap-1.5 pl-1">
|
||||
{detect.platform.game && <li>Categoria da plataforma: <strong className="text-fg">{detect.platform.game}</strong></li>}
|
||||
{detect.screen?.game && (
|
||||
<li>
|
||||
A IA viu na tela: <strong className="text-fg">{detect.screen.game}</strong>
|
||||
{detect.screen.confidence && ` (confiança ${CONFIDENCE_LABEL[detect.screen.confidence] ?? detect.screen.confidence})`}
|
||||
{detect.screen.evidence && <> — {detect.screen.evidence}</>}
|
||||
</li>
|
||||
)}
|
||||
{detect.candidates.map((c) => (
|
||||
<li key={c.gid}>
|
||||
<strong className="text-fg">{c.game}</strong> · nota {Math.round(c.score * 100)}%
|
||||
{" "}— {c.sources.map((x) => x.detail || GAME_CLUE_LABEL[x.source] || x.source).join("; ")}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</details>
|
||||
)}
|
||||
<GameChoiceDialog open={choosing} session={session} pending={pending === "game"}
|
||||
onClose={() => setChoosing(false)} onConfirm={(name) => void confirmGame(name)} />
|
||||
{game && <GameDialog game={profile} name={game} open={open} onClose={() => setOpen(false)} onGamesChanged={onGamesChanged} />}
|
||||
@@ -71,6 +130,18 @@ export function SessionGame({ session, games, onChanged, onGamesChanged }: {
|
||||
);
|
||||
}
|
||||
|
||||
const CONFIDENCE_LABEL: Record<string, string> = { high: "alta", medium: "média", low: "baixa" };
|
||||
|
||||
/** Como o estado da detecção aparece ao lado do nome do jogo. */
|
||||
const STATUS_BADGE: Record<string, { label: string; tone: "success" | "neutral" | "warning"; check: boolean }> = {
|
||||
user: { label: "confirmado por você", tone: "success", check: true },
|
||||
agreed: { label: "detectado · fontes concordam", tone: "success", check: true },
|
||||
probable: { label: "provável · confirme", tone: "neutral", check: false },
|
||||
conflict: { label: "em dúvida", tone: "warning", check: false },
|
||||
unknown: { label: "não identificado", tone: "neutral", check: false },
|
||||
"": { label: "aguardando checagem", tone: "neutral", check: false },
|
||||
};
|
||||
|
||||
/** Jogo cadastrado com esse nome: pelo id ou por um dos outros nomes (aliases). */
|
||||
function findGame(games: Game[], name: string): Game | undefined {
|
||||
const id = gameIdOf(name);
|
||||
@@ -91,9 +162,10 @@ function GameChoiceDialog({ open, session, pending, onClose, onConfirm }: {
|
||||
const clean = (name ?? "").trim();
|
||||
if (clean && !list.some((o) => gameIdOf(o.name) === gameIdOf(clean))) list.push({ name: clean, from });
|
||||
};
|
||||
add(session.game, session.gameSource === "user" ? "confirmado por você" : "categoria da plataforma");
|
||||
add(session.game, session.gameSource === "user" ? "confirmado por você" : session.gameSource ? GAME_SOURCE_LABEL[session.gameSource] : "categoria da plataforma");
|
||||
for (const h of [...(session.gameHistory ?? [])].reverse()) add(h.game, GAME_SOURCE_LABEL[h.source as keyof typeof GAME_SOURCE_LABEL] || "histórico");
|
||||
add(session.screenGame, "a IA viu na tela");
|
||||
for (const c of session.gameDetect?.candidates ?? []) add(c.game, `pistas: ${c.sources.map((x) => GAME_CLUE_LABEL[x.source] ?? x.source).join(", ")}`);
|
||||
return list;
|
||||
}, [session]);
|
||||
const [choice, setChoice] = useState(0);
|
||||
|
||||
@@ -9,7 +9,7 @@ import { useEffect, useState, type ReactNode } from "react";
|
||||
import { askConfirm } from "./confirm-dialog";
|
||||
import {
|
||||
ACTIVE_SESSION, CLIP_STATUS, CLIP_STATUS_ORDER, PLATFORM_LABEL, captureLabel, channelKeyOf, chatStatusInfo, clipperCall, formatClock,
|
||||
formatDuration, gameIdOf, gbPerHourLabel, languageLabel, useClipperAction,
|
||||
formatDuration, gameNeedsReview, gbPerHourLabel, languageLabel, useClipperAction,
|
||||
type Clip, type ClipStatus, type ClipperSession, type Game, type Timeline,
|
||||
} from "./clipper-client";
|
||||
import { CutSettingsDialog, type CutScope } from "./clipper-cut-settings";
|
||||
@@ -68,8 +68,7 @@ function SessionDetail({ session: s, name, clips, games, onChanged, onGamesChang
|
||||
const active = ACTIVE_SESSION.includes(s.status);
|
||||
const totalClips = CLIP_STATUS_ORDER.reduce((n, k) => n + (s.clips[k] ?? 0), 0);
|
||||
const lastMemory = s.memory?.length ? s.memory[s.memory.length - 1] : null;
|
||||
const confirmedGame = s.gameSource === "user";
|
||||
const mismatch = Boolean(s.game && s.screenGame && !confirmedGame && gameIdOf(s.screenGame) !== gameIdOf(s.game));
|
||||
const mismatch = gameNeedsReview(s);
|
||||
const health = sessionHealth(s, mismatch);
|
||||
const showNow = Boolean(lastMemory?.summary) || s.game !== undefined;
|
||||
const clock = useRecordingClock(s.durationS, s.status === "recording");
|
||||
|
||||
@@ -6,7 +6,7 @@ import Link from "next/link";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useState, type MouseEvent } from "react";
|
||||
import {
|
||||
ACTIVE_SESSION, CLIP_STATUS_ORDER, clipperCall, gameIdOf, languageLabel, languageShort, useClipperAction,
|
||||
ACTIVE_SESSION, CLIP_STATUS_ORDER, clipperCall, gameNeedsReview, languageLabel, languageShort, useClipperAction,
|
||||
type ClipperSession, type SessionStatus,
|
||||
} from "./clipper-client";
|
||||
import { useClipper, useClipperData } from "./clipper-provider";
|
||||
@@ -122,8 +122,7 @@ function SessionRow({ session: s, name, onChanged }: { session: ClipperSession;
|
||||
const live = s.status === "recording" || s.status === "starting";
|
||||
const active = ACTIVE_SESSION.includes(s.status);
|
||||
const problem = ["interrupted", "stopped", "error"].includes(s.status);
|
||||
const confirmedGame = s.gameSource === "user";
|
||||
const mismatch = Boolean(s.game && s.screenGame && !confirmedGame && gameIdOf(s.screenGame) !== gameIdOf(s.game));
|
||||
const mismatch = gameNeedsReview(s);
|
||||
const health = sessionHealth(s, mismatch);
|
||||
const clock = useRecordingClock(s.durationS, s.status === "recording");
|
||||
const total = CLIP_STATUS_ORDER.reduce((n, k) => n + (s.clips[k] ?? 0), 0);
|
||||
|
||||
@@ -28,13 +28,13 @@ function serviceUrl(pathname: string): { url: string; key: string } {
|
||||
/**
|
||||
* Caminhos que o navegador pode pedir (sempre sob /v1/). Qualquer outro é recusado aqui, antes do serviço.
|
||||
* status · judge · emotes · games[/id[/research|refine|translate|notes/n]] (POST games = cadastrar; PUT/DELETE games/id) · channels[/id[/check|settings]]
|
||||
* sessions[/id[/timeline|stop|resume|finish|clips|settings|frame|preview|detect-cam|game|face[/reset]]] · clips[/id[/render|rejudge]]
|
||||
* sessions[/id[/timeline|stop|resume|finish|clips|settings|frame|preview|detect-cam|game[/detect]|face[/reset]]] · clips[/id[/render|rejudge]]
|
||||
* editor de cortes: clips/id/(edit|proxy|waveform|export|preview-render|retranscribe|tts|suggest)
|
||||
* vídeo final (doc/clipador/REVISAO.md): POST clips/id/final · tradução da fala (IDIOMAS.md): POST clips/id/translate
|
||||
* vozes da sessão (FALANTES.md): GET sessions/id/speakers
|
||||
* apagar cortes: DELETE clips/id · POST clips/delete (lote) — o método é conferido em METHODS
|
||||
*/
|
||||
const ALLOWED = /^(status|judge|emotes|games(\/[a-z0-9-]{1,60}(\/(research|refine|translate|notes\/\d{1,3}))?)?|channels(\/(twitch|youtube|kick)-[a-z0-9._-]{2,60}(\/(check|settings))?)?|sessions(\/\d{1,9}(\/(timeline|stop|resume|finish|clips|settings|frame|preview|detect-cam|game|face(\/reset)?|speakers))?)?|clips(\/(delete|\d{1,9}(\/(render|rejudge|edit|proxy|waveform|export|preview-render|retranscribe|tts|suggest|final|translate))?))?)$/;
|
||||
const ALLOWED = /^(status|judge|emotes|games(\/[a-z0-9-]{1,60}(\/(research|refine|translate|notes\/\d{1,3}))?)?|channels(\/(twitch|youtube|kick)-[a-z0-9._-]{2,60}(\/(check|settings))?)?|sessions(\/\d{1,9}(\/(timeline|stop|resume|finish|clips|settings|frame|preview|detect-cam|game(\/detect)?|face(\/reset)?|speakers))?)?|clips(\/(delete|\d{1,9}(\/(render|rejudge|edit|proxy|waveform|export|preview-render|retranscribe|tts|suggest|final|translate))?))?)$/;
|
||||
|
||||
/** Métodos aceitos nos caminhos de apagar corte (os demais caminhos seguem só pela regex acima). */
|
||||
const METHODS: [RegExp, string[]][] = [
|
||||
|
||||
Reference in New Issue
Block a user