Clipador: Equipe de IA (papéis com IA própria), juiz de contexto e linha do tempo JSON

- roles.py: varredura, analista, editor e juiz, cada um com provedor, modelo, raciocínio
  (Codex), liga/desliga (o editor não desliga) e instruções do administrador somadas às
  padrão; gravado em settings `judge.roles`, com migração automática da configuração antiga
  (provedor/modelo único vira o de todos; o modelo do analista é respeitado). A reserva vale
  por papel.
- Juiz de contexto (só texto): vê só o que vai no corte (+20 s antes/15 s depois marcados
  out=1), escreve o que um espectador frio entende e responde sim/não; context_judge.decide
  decide pelo código: aprova, ajusta o trecho e confere uma vez de novo, frase de contexto
  na tela (vira o texto de abertura do projeto) ou descarta com motivo em português
  (forçável). Corte manual só recebe aviso.
- timeline.py: linha do tempo JSON curta (fala com falante, chat, rosto, volume e a frase
  de tela que a varredura/analista escrevem ao ver os quadros, em scene_notes); mosaico 4x2
  (media.mosaic) no lugar dos quadros soltos; perfil do jogo enxuto. O formato antigo fica
  atrás da opção timelineJson.
- Medição (F0): ai_calls por chamada (papel, IA, tamanho do prompt/imagens, tokens quando a
  CLI informa: codex --json, claude e gemini), avaliação do dono (owner_label: bom/ruim/sem
  contexto) e GET /v1/judge/report (taxa de aprovação, decisões do juiz, concordância).
- Banco v17 (v16 fica reservada às expressões, como marcador sem efeito).
- Testes: test_roles.py e test_context_judge.py; os testes bloqueiam qualquer CLI de IA real.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Mateuus
2026-11-18 04:36:25 -03:00
co-authored by Claude Opus 5.5
parent 5be6c09c16
commit cb8450399d
17 changed files with 2081 additions and 116 deletions
+482 -45
View File
@@ -30,11 +30,13 @@ import sys
import tempfile
import threading
import time
from contextlib import contextmanager
from dataclasses import dataclass, field
from datetime import datetime, timezone
from pathlib import Path
from . import layout
from . import roles as roles_module
from .ai_settings import AiConfig
from .scoring import ChatMessage, Word, fit_window
@@ -111,6 +113,14 @@ CHAT_GLOSSARY = """Gírias comuns do chat (interprete pelo contexto):
"clipa/clip it" → pedido de corte; "hack/hackudo" → suspeita de trapaça; "gg" → fim de partida.
- Emotes próprios do canal (prefixo do streamer, ex.: skpPog) carregam a mesma reação do emote original."""
# Frase curta do que está na tela em cada quadro/ladrilho do mosaico (`n` = nº do quadro, 1 = primeiro). Vira o
# campo `v` da linha do tempo (app/timeline.py), guardado em `scene_notes` e reaproveitado por editor e juiz.
SCENE_LINES = {
"type": "array",
"items": {"type": "object", "properties": {"n": {"type": "integer"}, "v": {"type": "string"}},
"required": ["n", "v"], "additionalProperties": False},
}
SITUATIONS = ("lag_ou_bug", "jogada", "falha_engracada", "morte", "susto", "treta", "conversa_engracada",
"historia", "informacao_do_jogo", "reacao", "outro")
@@ -126,11 +136,14 @@ ANALYSIS_SCHEMA = {
"action_start_s": {"type": "number"},
"reaction_end_s": {"type": "number"},
"hook": {"type": "string"},
"lines": SCENE_LINES,
},
"required": ["situation", "what_happened", "screen", "speech", "chat_meaning", "confidence",
"action_start_s", "reaction_end_s", "hook"],
"action_start_s", "reaction_end_s", "hook", "lines"],
"additionalProperties": False,
}
# Campos que a resposta pode não trazer (modelo antigo/cache): a análise segue sem eles.
ANALYSIS_OPTIONAL = ("lines",)
ANALYST_SYSTEM = """Você é o ANALISTA de uma equipe de cortes de live. Não escreve título: descreve com fidelidade
O QUE ACONTECEU no trecho, para o editor decidir. Recebe contexto do jogo, transcrição com tempos, FRAMES da tela
@@ -152,6 +165,8 @@ Campos:
- action_start_s: instante (s da gravação) em que começa a AÇÃO que gerou a reação (pode ser antes da fala).
- reaction_end_s: instante em que a reação/pagamento termina.
- hook: o que prenderia alguém nos 2 primeiros segundos do corte.
- lines: para cada frame/quadro do mosaico anexado (n = o número dele), v = o que está na tela em até 12 palavras,
factual (ação, lugar, texto grande do jogo). Sem imagem anexada: lista vazia.
Não use ferramentas além do que foi entregue. Responda só com o JSON pedido."""
VERDICT_SCHEMA = {
@@ -184,8 +199,9 @@ SCAN_SCHEMA = {
"has_webcam": {"type": "boolean"},
"summary": {"type": "string"},
"moments": {"type": "array", "items": _MOMENT},
"lines": SCENE_LINES,
},
"required": ["screen_game", "has_webcam", "summary", "moments"],
"required": ["screen_game", "has_webcam", "summary", "moments", "lines"],
"additionalProperties": False,
}
_MISSION = {
@@ -271,6 +287,8 @@ moments=[] (é o normal na maior parte do tempo — não force). Não repita um
- screen_game: o jogo que aparece na tela (ou "desconhecido"); 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).
- lines: para cada frame/quadro do mosaico (n = o número dele), v = o que está na tela em até 12 palavras, factual.
Sem imagem anexada: lista vazia.
Não use ferramentas além do que foi entregue. Responda só com o JSON pedido."""
# Perfil do jogo em INGLÊS (doc/clipador/JOGOS.md): é o que vai nos prompts; a tradução para português é só para o
@@ -454,6 +472,8 @@ Fields (in English):
- action_start_s: second of the recording where the ACTION that caused the reaction starts (may be before the speech).
- reaction_end_s: second where the reaction/payoff ends.
- hook: what would hook someone in the first 2 seconds of the clip (English, it goes on screen).
- lines: for each attached frame/mosaic tile (n = its number), v = what is on screen in up to 12 words, factual
(action, place, big on-screen game text), in English. No image attached: empty list.
- pt: what_happened, screen, speech, chat_meaning and hook translated. """ + PT_NOTE + """
Do not use tools beyond what was given. Answer only with the requested JSON."""
@@ -500,6 +520,8 @@ moments=[] (that's normal most of the time — don't force it). Don't repeat a c
- screen_game: the game on screen (or "unknown"); 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).
- lines: for each frame/mosaic tile (n = its number), v = what is on screen in up to 12 words, factual, in English.
No image attached: empty list.
- summary_pt and each moment's pt (title, reason): translated. """ + PT_NOTE + """
Do not use tools beyond what was given. Answer only with the requested JSON."""
@@ -535,6 +557,213 @@ names; translate the slang's meaning, e.g. "he's cooked" -> "ele tá ferrado").
as is. Answer only with the requested JSON."""
# ---------------------------------------------------------------- JUIZ de contexto (doc/clipador/EQUIPE-IA.md)
# Pedido do dono (18/11/2026): "não trazer corte sem sentido, principalmente em inglês". O juiz vê SÓ o que vai no
# corte final (linha do tempo do trecho + 20 s antes marcados out=1), escreve primeiro o que um espectador frio
# entenderia e depois responde sim/não. Quem decide pelas respostas é o código (context_judge.decide), não uma nota.
CONTEXT_CHECKS = roles_module.CHECKS
_CHECK = {"type": "object",
"properties": {"ok": {"type": "boolean"}, "t": {"type": ["number", "null"]}, "why": {"type": "string"}},
"required": ["ok", "t", "why"], "additionalProperties": False}
CONTEXT_SCHEMA = {
"type": "object",
"properties": {
"viewer_summary": {"type": "string"},
"checks": {"type": "object", "properties": {c: _CHECK for c in CONTEXT_CHECKS}, "required": list(CONTEXT_CHECKS),
"additionalProperties": False},
"fix": {"type": "object",
"properties": {"start_s": {"type": ["number", "null"]}, "end_s": {"type": ["number", "null"]},
"context_line": {"type": "string"}},
"required": ["start_s", "end_s", "context_line"], "additionalProperties": False},
"confidence": {"type": "number"},
"reason": {"type": "string"},
},
"required": ["viewer_summary", "checks", "fix", "confidence", "reason"],
"additionalProperties": False,
}
CONTEXT_SCHEMA_EN = _with(CONTEXT_SCHEMA, pt={
"type": "object",
"properties": {"viewer_summary": {"type": "string"}, "reason": {"type": "string"}, "context_line": {"type": "string"},
"checks": _pt_block(*CONTEXT_CHECKS)},
"required": ["viewer_summary", "reason", "context_line", "checks"], "additionalProperties": False})
CONTEXT_SYSTEM_EN = """You are the CONTEXT JUDGE of a live-stream clipping team. The editor already picked the segment and
wrote the title. You check ONE thing: will someone who has NEVER seen this stream understand the clip and feel it makes
sense on its own? You only get what the viewer will see: the clip's timeline (entries with out=1 are just BEFORE or AFTER
the clip — the viewer does NOT see them; use them only to notice a missing setup or payoff), the title, caption and opening on-screen text, the
intended story (from the analyst) and one line about the game.
First write viewer_summary: what a cold viewer understands from the clip alone (1–2 sentences) — BEFORE the checks.
Then answer every check with ok (true/false), t (second of the recording that is the evidence, or null) and why
(up to 15 words):
- setup: the clip includes the start of the situation the moment depends on. Fails if the key setup is only in the
out=1 entries before the clip (or earlier).
- payoff: the clip includes the outcome/punchline/result (of the fight, escape, mission, joke). Fails if it ends before
(e.g. the result is only in the out=1 entries after the clip).
- who_what: it is clear who is involved and what is happening.
- standalone: it works without knowing earlier events of the stream, the channel's lore or inside jokes.
- intelligible: the key line is in the transcript; fails if the important line is a teammate's/other player's that is
missing, or the streamer only reacts to something we never hear.
- faithful: title/caption only claim what the clip shows ("caught a hacker" when he only accuses him = false).
- strong_open: the first ~3 s already hook (not calm chatter).
Red flags in English streams: references to things outside the clip ("that guy", "again", "like I said", "remember
when", names never introduced), callbacks to donations/raids/subs, chat or channel inside jokes. Irony/slang ("he's
cooked", "Clueless", "W") only counts if the screen confirms it.
fix — only when a check fails and the timeline shows the answer: start_s (earlier, to include the setup) and/or end_s
(later, to include the payoff; or earlier, to drop a tail that depends on other context), seconds of the recording,
within the limits given; null when not needed. context_line: on-screen text for the first seconds (up to 8 words, in
English) that gives a cold viewer the missing context (e.g. "Tfue tries to talk his way out of a robbery"); "" when not
needed. Never invent facts.
confidence: 0–1. reason: one sentence.
pt: viewer_summary, reason, context_line and every check's why, translated. """ + PT_NOTE + """
Do not use tools. Answer only with the requested JSON."""
CONTEXT_SYSTEM = """Você é o JUIZ DE CONTEXTO de uma equipe de cortes de live. O editor já escolheu o trecho e escreveu o
título. Você confere UMA coisa: alguém que NUNCA viu esta live entende o corte e sente que ele faz sentido sozinho?
Você recebe só o que o espectador vai ver: a linha do tempo do corte (entradas com out=1 vêm logo ANTES ou DEPOIS do
corte — o espectador NÃO as vê; use só para notar o começo ou o desfecho que faltam), título, legenda e texto de abertura na tela, a história
pretendida (do analista) e uma linha sobre o jogo.
Escreva primeiro viewer_summary: o que um espectador frio entende só com o corte (1–2 frases) — ANTES das checagens.
Depois responda cada checagem com ok (true/false), t (segundo da gravação que é a evidência, ou null) e why (até 15
palavras):
- setup: o corte inclui o começo da situação de que o momento depende. Falha se o começo importante só está nas
entradas out=1 (ou antes).
- payoff: o corte inclui o desfecho/resultado/piada (da treta, da fuga, da missão). Falha se termina antes (ex.: o
resultado só aparece nas entradas out=1 depois do corte).
- who_what: dá para entender quem está envolvido e o que está acontecendo.
- standalone: funciona sem saber o que aconteceu antes na live, a história do canal ou piadas internas.
- intelligible: a fala principal está na transcrição; falha se ela é de um colega/outro jogador que não aparece, ou se
o streamer só reage a algo que não se ouve.
- faithful: título/legenda só afirmam o que o corte mostra ("pegou um hacker" quando ele só acusa = falso).
- strong_open: os ~3 primeiros segundos já prendem (não é conversa morna).
Sinais de alerta: referência a algo fora do corte ("aquele cara", "de novo", "como eu falei", "lembra quando", nome
nunca apresentado), menção a doação/raid/sub, piada interna do chat ou do canal. Ironia/gíria só vale se a tela
confirma.
fix — só quando uma checagem falha e a linha do tempo mostra a resposta: start_s (mais cedo, para incluir o começo) e/ou
end_s (mais tarde, para incluir o desfecho; ou mais cedo, para tirar uma cauda que depende de outro contexto), em
segundos da gravação, dentro dos limites informados; null quando não precisa. context_line: texto na tela para os
primeiros segundos (até 8 palavras, no idioma do corte) que dá ao espectador frio o contexto que falta; "" se não
precisa. Nunca invente fatos.
confidence: 0–1. reason: uma frase.
Não use ferramentas. Responda só com o JSON pedido."""
def clean_context(data: dict) -> dict:
"""Resposta do juiz normalizada: checagem ausente/inválida conta como "não respondida" (ok=True, sem motivo) —
o código não descarta por falta de resposta. Sem `checks` nem `viewer_summary` é erro de conteúdo."""
if not isinstance(data, dict) or not isinstance(data.get("checks"), dict) or "viewer_summary" not in data:
raise JudgeError("juiz sem viewer_summary/checks", unavailable=False)
checks = {}
for name in CONTEXT_CHECKS:
raw = data["checks"].get(name)
raw = raw if isinstance(raw, dict) else {}
t = raw.get("t")
checks[name] = {"ok": raw.get("ok") is not False,
"t": float(t) if isinstance(t, (int, float)) and not isinstance(t, bool) else None,
"why": str(raw.get("why") or "").strip()[:200]}
fix = data.get("fix") if isinstance(data.get("fix"), dict) else {}
def num(value):
return float(value) if isinstance(value, (int, float)) and not isinstance(value, bool) else None
pt = data.get("pt") if isinstance(data.get("pt"), dict) else {}
pt_checks = pt.get("checks") if isinstance(pt.get("checks"), dict) else {}
try:
confidence = max(0.0, min(1.0, float(data.get("confidence", 0.5))))
except (TypeError, ValueError):
confidence = 0.5
out_pt = {k: str(pt.get(k) or "").strip()[:600] for k in ("viewer_summary", "reason", "context_line") if pt.get(k)}
if pt_checks:
out_pt["checks"] = {c: str(pt_checks.get(c) or "").strip()[:200] for c in CONTEXT_CHECKS if pt_checks.get(c)}
return {
"viewer_summary": str(data.get("viewer_summary") or "").strip()[:600],
"checks": checks,
"fix": {"start_s": num(fix.get("start_s")), "end_s": num(fix.get("end_s")),
"context_line": " ".join(str(fix.get("context_line") or "").split())[:80]},
"confidence": confidence,
"reason": str(data.get("reason") or "").strip()[:300],
"pt": out_pt,
}
# ---------------------------------------------------------------- prompts com a linha do tempo (v1)
def images_block(tiles: list[float], mosaic: bool, lang: str = "pt") -> str:
"""O que vai anexado. `tiles` = instante de cada quadro (no mosaico, da esquerda para a direita, de cima para
baixo). As frases `lines[].n` da resposta se referem a esses números."""
if not tiles:
return "Images: none." if lang == "en" else "Imagens: nenhuma."
numbered = ", ".join(f"#{i + 1}={t:.0f}s" for i, t in enumerate(tiles))
if mosaic:
return (f"Attached: ONE mosaic image with {len(tiles)} frames in a grid (left→right, top→bottom): {numbered}."
if lang == "en" else
f"Anexo: UMA imagem em mosaico com {len(tiles)} quadros em grade (esquerda→direita, cima→baixo): {numbered}.")
return (f"Attached frames, in order: {numbered}." if lang == "en" else f"Frames anexados, em ordem: {numbered}.")
def timeline_section(timeline_text: str, lang: str, streamer: str) -> str:
"""Legenda das chaves + (se há fala de outra pessoa) a nota de quem fala + a linha do tempo."""
from .timeline import legend
me = (streamer or "streamer").replace("[", "(").replace("]", ")")
note = ""
if "[other" in timeline_text: # fala de outra pessoa no trecho (FALANTES.md): sem marca = o streamer
note = "\n" + SPEAKER_NOTE["en" if lang == "en" else "pt"].format(s=me).replace(f"[{me}]", "no tag")
return f"{legend(lang)}{note}\n{timeline_text}"
def build_timeline_prompt(streamer: str, platform: str, start_s: float, end_s: float, peak_s: float,
heuristic: dict, *, context: str, timeline_text: str, tiles: list[float], mosaic: bool,
lo: float, hi: float, min_s: float, max_s: float, lang: str = "pt",
analysis: dict | None = None) -> str:
"""Prompt do ANALISTA e do EDITOR no formato novo: cabeçalho + imagens + linha do tempo JSON (no lugar da
transcrição, do chat e da linha do rosto, que já estão dentro dela)."""
L, to = LABELS[lang], ("to" if lang == "en" else "a")
signals = {k: v for k, v in heuristic.items() if k not in ("topMessages", "face", "emotes")}
text = (f"{L['channel']}: {streamer} ({platform})\n{context}\n\n"
f"{L['window']}: {lo:.0f}s {to} {hi:.0f}s. {L['candidate']}: {start_s:.0f}s {to} {end_s:.0f}s; "
f"{L['peak']} {peak_s:.0f}s. {L['duration']}: {min_s:.0f} {to} {max_s:.0f} s.\n"
f"{L['signals']}: {json.dumps(signals, ensure_ascii=False, separators=(',', ':'))}\n"
f"{images_block(tiles, mosaic, lang)}\n\n{timeline_section(timeline_text, lang, streamer)}")
if analysis:
text += "\n\n" + analysis_block(analysis, lang)
return text
def build_scan_timeline_prompt(streamer: str, platform: str, lo: float, hi: float, back_lo: float, context: str,
timeline_text: str, tiles: list[float], mosaic: bool,
existing: list[tuple[float, float, str]], min_s: float, max_s: float,
lang: str = "pt") -> str:
L, to = LABELS[lang], ("to" if lang == "en" else "a")
done = "; ".join(f"{a:.0f}–{b:.0f}s ({t[:40]})" for a, b, t in existing) or L["none"]
return (f"{L['channel']}: {streamer} ({platform})\n{context}\n\n"
f"{L['new_window']}: {lo:.0f}s {to} {hi:.0f}s ({L['back_to'].format(s=f'{back_lo:.0f}')}).\n"
f"{L['duration']}: {min_s:.0f} {to} {max_s:.0f} s. {L['done']}: {done}\n"
f"{images_block(tiles, mosaic, lang)}\n\n{timeline_section(timeline_text, lang, streamer)}")
def build_context_prompt(*, streamer: str, game: str, game_line: str, start_s: float, end_s: float, title: str,
caption: str, opening: str, story: str, timeline_text: str, lo: float, hi: float,
min_s: float, max_s: float, lang: str = "pt") -> str:
"""Prompt do JUIZ: só o que o espectador verá (e 20 s antes / 15 s depois, marcados out=1) + limites do ajuste."""
if lang == "en":
lines = [f"Game: {game or 'unknown'}" + (f" — {game_line}" if game_line else ""),
f"Streamer: {streamer}",
f"Clip the viewer will see: {start_s:.0f}s to {end_s:.0f}s ({end_s - start_s:.0f} s).",
f"Title: {title}", f"Caption: {caption or '(none)'}", f"Opening on-screen text: {opening or '(none)'}",
f"Intended story (analyst): {story or '(not available)'}",
f"Limits for a fix: start back to {lo:.0f}s at most, end up to {hi:.0f}s; duration {min_s:.0f} to {max_s:.0f} s."]
else:
lines = [f"Jogo: {game or 'desconhecido'}" + (f" — {game_line}" if game_line else ""),
f"Streamer: {streamer}",
f"Corte que o espectador verá: {start_s:.0f}s a {end_s:.0f}s ({end_s - start_s:.0f} s).",
f"Título: {title}", f"Legenda: {caption or '(nenhuma)'}", f"Texto de abertura na tela: {opening or '(nenhum)'}",
f"História pretendida (analista): {story or '(não disponível)'}",
f"Limites para o ajuste: início até {lo:.0f}s no máximo para trás, fim até {hi:.0f}s; duração de "
f"{min_s:.0f} a {max_s:.0f} s."]
return "\n".join(lines) + f"\n\n{timeline_section(timeline_text, lang, streamer)}"
def lang_key(language: str | None) -> str:
"""'en' para fonte em inglês (juízes em inglês); 'pt' para o resto (prompts em português + nota de saída)."""
return "en" if (language or "").strip().lower().startswith("en") else "pt"
@@ -611,6 +840,23 @@ def mission_lines(profile: dict, lang: str = "pt") -> list[str]:
return lines
LEAN_LIMITS = {"clip_worthy": 6, "avoid": 4, "mechanics": 6, "jargon": 10, "news": 2}
LEAN_ITEM_CHARS = 100
def lean_profile(profile: dict | None) -> dict | None:
"""Perfil enxuto para os prompts da linha do tempo (o perfil completo ia inteiro em TODA chamada: ~1.000
tokens no ROB RUN). Resumo em 2 frases, listas menores e itens curtos; missões seguem com o teto de sempre."""
if not profile:
return profile
out = dict(profile)
summary = str(profile.get("summary") or "")
out["summary"] = ". ".join(summary.split(". ")[:2]).strip()
for key, limit in LEAN_LIMITS.items():
out[key] = [str(item)[:LEAN_ITEM_CHARS] for item in (profile.get(key) or [])[:limit]]
return out
def game_context(game: str, screen_game: str, profile: dict | None, live_title: str, history: str = "",
confirmed: bool = False, lang: str = "pt") -> str:
if lang == "en":
@@ -852,14 +1098,70 @@ def codex_models(cache: Path | None = None) -> list[dict]:
return out or [{"id": DEFAULT_MODELS["codex"], "label": DEFAULT_MODELS["codex"]}]
# ---------------------------------------------------------------- uso de tokens (F0: medir antes de otimizar)
def _int(value) -> int | None:
try:
return int(value) if value is not None else None
except (TypeError, ValueError):
return None
def codex_usage(stdout: str) -> dict | None:
"""Uso do `codex exec --json` (eventos JSONL): o último evento com `usage` (`turn.completed`). None = não veio."""
found = None
for line in (stdout or "").splitlines():
line = line.strip()
if not line.startswith("{") or "input_tokens" not in line:
continue
try:
event = json.loads(line)
except json.JSONDecodeError:
continue
usage = event.get("usage") if isinstance(event, dict) else None
if not isinstance(usage, dict): # formato antigo: {"msg": {"type": "token_count", "info": {...}}}
info = ((event.get("msg") or {}).get("info") or {}) if isinstance(event, dict) else {}
usage = info.get("total_token_usage") or info.get("last_token_usage")
if isinstance(usage, dict) and "input_tokens" in usage:
found = {"in": _int(usage.get("input_tokens")), "out": _int(usage.get("output_tokens")),
"cached": _int(usage.get("cached_input_tokens"))}
return found
def claude_usage(envelope: dict) -> dict | None:
"""Uso do envelope `claude -p --output-format json`: entrada = nova + criação de cache + leitura de cache."""
usage = envelope.get("usage") if isinstance(envelope, dict) else None
if not isinstance(usage, dict):
return None
parts = [_int(usage.get(k)) or 0 for k in ("input_tokens", "cache_creation_input_tokens", "cache_read_input_tokens")]
return {"in": sum(parts), "out": _int(usage.get("output_tokens")), "cached": _int(usage.get("cache_read_input_tokens"))}
def gemini_usage(envelope: dict) -> dict | None:
"""Uso do `gemini -o json` (`stats.models.<modelo>.tokens`), somado entre os modelos que a CLI usou."""
models = ((envelope or {}).get("stats") or {}).get("models") if isinstance(envelope, dict) else None
if not isinstance(models, dict) or not models:
return None
total = {"in": 0, "out": 0, "cached": 0}
for data in models.values():
tokens = (data or {}).get("tokens") or {}
total["in"] += _int(tokens.get("prompt")) or 0
total["out"] += (_int(tokens.get("candidates")) or 0) + (_int(tokens.get("thoughts")) or 0)
total["cached"] += _int(tokens.get("cached")) or 0
return total
# ---------------------------------------------------------------- IA
class Judge:
"""As IAs da equipe (doc/clipador/EQUIPE-IA.md). Cada papel (varredura, analista, editor, juiz) tem provedor e
modelo próprios (`roles`); `provider`/`model` continuam existindo como a IA do EDITOR — a "principal", que também
faz os serviços gerais (pesquisa de jogo, tradução, câmera). `provider == "off"` desliga a equipe inteira."""
def __init__(self, provider: str, model: str, workdir: Path, analyst_model: str = "",
ai: AiConfig | None = None, clock=time.time):
self.provider = provider if provider in PROVIDERS else "codex"
self.model = model or DEFAULT_MODELS.get(self.provider, "")
# Modelo do ANALISTA (1º juiz, vê os frames). Vazio = o mesmo do editor.
self.analyst_model = analyst_model
ai: AiConfig | None = None, clock=time.time, roles: dict | None = None):
legacy = provider if provider in PROVIDERS else "codex"
self._master = "off" if legacy == "off" else "on"
base = roles_module.default_roles(legacy if legacy != "off" else "codex", model, analyst_model)
self.roles = roles_module.normalize_roles(roles, base)
self.workdir = workdir
# Configurações → IA do painel (data/ai): login/chave por provedor e ordem da reserva.
self.ai = ai or AiConfig()
@@ -869,14 +1171,85 @@ class Judge:
self._pause_lock = threading.Lock()
# Quem respondeu a última chamada DESTA thread ("provedor:modelo"): o juiz roda em várias threads.
self._local = threading.local()
# Medição (F0): o motor liga isto para gravar cada chamada em `ai_calls`. None = não mede.
self.meter = None
def configure(self, provider: str, model: str, analyst_model: str | None = None) -> None:
# ---------- papéis
@property
def provider(self) -> str:
return "off" if self._master == "off" else self.roles["editor"]["provider"]
@provider.setter
def provider(self, value: str) -> None:
"""Compatível com o jeito antigo (um provedor só): "off" desliga a equipe; outro vale para todos os papéis."""
if value == "off":
self._master = "off"
return
if value not in AI_ENABLED:
raise JudgeError(f"provedor precisa ser um de {', '.join(PROVIDERS)}")
self._master = "on"
for role in self.roles.values():
if role["provider"] != value:
role["provider"], role["model"] = value, ""
@property
def model(self) -> str:
return self.role_model("editor")
@property
def analyst_model(self) -> str:
return self.roles["analyst"]["model"]
def role_model(self, role: str) -> str:
conf = self.roles[role]
return conf["model"] or DEFAULT_MODELS.get(conf["provider"], "")
def role_enabled(self, role: str) -> bool:
return self.enabled and bool(self.roles[role]["enabled"])
def system_for(self, role: str, base: str, lang: str = "pt") -> str:
"""Instruções padrão do papel + as do administrador (somadas, nunca no lugar)."""
return base + roles_module.admin_notes(self.roles.get(role) or {}, lang)
def configure(self, provider: str, model: str, analyst_model: str | None = None, roles: dict | None = None) -> None:
"""`roles` = configuração por papel (painel novo). Sem ela (painel antigo): `provider`/`model` valem para
todos os papéis e `analyst_model` para o analista. `provider == "off"` desliga a equipe."""
if provider not in PROVIDERS:
raise JudgeError(f"provedor precisa ser um de {', '.join(PROVIDERS)}")
self.provider = provider
self.model = model.strip() or DEFAULT_MODELS.get(provider, "")
if roles is not None:
self.roles = roles_module.normalize_roles(roles, self.roles)
self._master = "off" if provider == "off" else "on"
return
if provider == "off":
self._master = "off"
return
self._master = "on"
model = model.strip()
for name, role in self.roles.items():
role["provider"] = provider
role["model"] = "" if model == DEFAULT_MODELS.get(provider) else model
if analyst_model is not None:
self.analyst_model = analyst_model.strip()
self.roles["analyst"]["model"] = analyst_model.strip()
elif self.roles["analyst"]["model"] and provider != self.roles["analyst"]["provider"]:
self.roles["analyst"]["model"] = ""
def roles_view(self) -> dict:
"""Papéis para o painel: a configuração + instruções padrão (só leitura) e a cadeia de reserva de cada um."""
out = {}
for name in roles_module.ROLES:
conf = dict(self.roles[name])
conf["resolvedModel"] = self.role_model(name)
conf["chain"] = self.fallback_chain(conf["provider"]) if self.enabled else []
out[name] = conf
return out
@staticmethod
def default_instructions() -> dict:
"""Texto padrão de cada papel nos dois idiomas (o painel mostra só para leitura)."""
return {"scan": {"pt": SCAN_SYSTEM, "en": SCAN_SYSTEM_EN},
"analyst": {"pt": ANALYST_SYSTEM, "en": ANALYST_SYSTEM_EN},
"editor": {"pt": JUDGE_SYSTEM, "en": JUDGE_SYSTEM_EN},
"judge": {"pt": CONTEXT_SYSTEM, "en": CONTEXT_SYSTEM_EN}}
@property
def enabled(self) -> bool:
@@ -889,6 +1262,16 @@ class Judge:
""""provedor:modelo" de quem respondeu a última chamada desta thread (a reserva pode ter respondido)."""
return getattr(self._local, "responder", None) or f"{self.provider}:{self.model}"
@contextmanager
def scope(self, **context):
"""Contexto das chamadas desta thread para a medição (`session_id`, `clip_id`, `mode`)."""
previous = getattr(self._local, "scope", None) or {}
self._local.scope = {**previous, **context}
try:
yield
finally:
self._local.scope = previous
# ---------- reserva
def pauses(self) -> dict[str, tuple[float, str]]:
"""Pausas ainda valendo (as vencidas saem)."""
@@ -916,17 +1299,18 @@ class Judge:
return "modo chave de API sem chave no cofre"
return None
def fallback_chain(self) -> list[str]:
"""Ordem em que `ask` tenta as IAs: a escolhida no juiz primeiro, depois a `order` do painel, só as ligadas,
com CLI e (no modo chave) com chave; as em pausa são puladas e as perto do limite de uso vão para o fim.
Reserva desligada: só a escolhida.
def fallback_chain(self, primary: str | None = None) -> list[str]:
"""Ordem em que `ask` tenta as IAs: a do papel (`primary`; padrão = a do editor) primeiro, depois a `order`
do painel, só as ligadas, com CLI e (no modo chave) com chave; as em pausa são puladas e as perto do limite
de uso vão para o fim. Reserva desligada: só a escolhida.
Se TODAS as prontas estiverem em pausa, elas voltam como último recurso (melhor tentar do que parar)."""
if not self.enabled:
return []
primary = primary if primary in AI_ENABLED else self.provider
settings = self.ai.settings()
candidates = [self.provider]
candidates = [primary]
if settings["fallback"]["enabled"]:
candidates += [p for p in settings["order"] if p != self.provider and p in AI_ENABLED]
candidates += [p for p in settings["order"] if p != primary and p in AI_ENABLED]
ready = [p for p in candidates if self._skip_reason(p, settings) is None]
if not settings["fallback"]["enabled"]:
return ready
@@ -941,7 +1325,7 @@ class Judge:
settings = self.ai.settings()
primary_skip = self._skip_reason(self.provider, settings) if self.enabled else None
return {"provider": self.provider, "model": self.model if self.enabled else None,
"analystModel": (self.analyst_model or self.model) if self.enabled else None,
"analystModel": self.role_model("analyst") if self.enabled else None,
"available": bool(cmd) if self.enabled else None, "path": cmd[-1] if cmd else None,
# Por que a escolhida não roda (desligada no painel, sem CLI, sem chave); None = pronta.
"unavailableReason": primary_skip,
@@ -950,18 +1334,24 @@ class Judge:
"cooldownMin": settings["fallback"]["cooldownMin"],
"chain": self.fallback_chain()},
"pauses": [{"provider": p, "until": datetime.fromtimestamp(until, timezone.utc).isoformat(timespec="seconds"),
"reason": reason} for p, (until, reason) in sorted(self.pauses().items())]}
"reason": reason} for p, (until, reason) in sorted(self.pauses().items())],
# Equipe de IA: cada papel com a sua IA (doc/clipador/EQUIPE-IA.md).
"roles": self.roles_view(),
"providers": {p: {"ready": self._skip_reason(p, settings) is None,
"reason": self._skip_reason(p, settings),
"enabled": bool((settings["providers"].get(p) or {}).get("enabled"))}
for p in AI_ENABLED}}
def models(self) -> dict:
return {"codex": codex_models(), "claude": CLAUDE_MODELS, "gemini": GEMINI_MODELS, "defaults": DEFAULT_MODELS}
# ---------- usos
def analyze(self, prompt: str, images: list[Path], lang: str = "pt") -> dict:
"""1º juiz (ANALISTA): o que aconteceu, cruzando tela + fala + chat. Não decide nem escreve título.
"""ANALISTA: o que aconteceu, cruzando tela + fala + chat. Não decide nem escreve título.
`lang="en"`: prompt em inglês e bloco `pt` (tradução para o painel) na mesma resposta."""
system, schema = (ANALYST_SYSTEM_EN, ANALYSIS_SCHEMA_EN) if lang == "en" else (ANALYST_SYSTEM, ANALYSIS_SCHEMA)
data = self.ask(system, prompt, schema, images, model=self.analyst_model or self.model)
missing = [k for k in ANALYSIS_SCHEMA["required"] if k not in data]
data = self.ask(self.system_for("analyst", system, lang), prompt, schema, images, role="analyst")
missing = [k for k in ANALYSIS_SCHEMA["required"] if k not in data and k not in ANALYSIS_OPTIONAL]
if missing:
raise JudgeError(f"análise sem os campos {missing}")
data["confidence"] = max(0.0, min(1.0, float(data["confidence"])))
@@ -970,18 +1360,26 @@ class Judge:
def judge(self, prompt: str, start_s: float, end_s: float, images: list[Path] | None = None, *,
lo: float | None = None, hi: float | None = None, min_s: float = DEFAULT_MIN_S,
max_s: float = DEFAULT_MAX_S, lang: str = "pt") -> Verdict:
"""EDITOR: decide se vira corte, o trecho, título, legenda e hashtags."""
system, schema = (JUDGE_SYSTEM_EN, VERDICT_SCHEMA_EN) if lang == "en" else (JUDGE_SYSTEM, VERDICT_SCHEMA)
data = self.ask(system, prompt, schema, images or [])
data = self.ask(self.system_for("editor", system, lang), prompt, schema, images or [], role="editor")
# Modelo de quem DE FATO respondeu (a reserva pode ter entrado no lugar da escolhida).
return _clean(data, start_s, end_s, self.responder(), lo, hi, min_s, max_s)
def check_context(self, prompt: str, lang: str = "pt") -> dict:
"""JUIZ de contexto (só texto): o que um espectador frio entende + as checagens sim/não. Quem decide pelas
respostas é o código (`context_judge.decide`)."""
system, schema = (CONTEXT_SYSTEM_EN, CONTEXT_SCHEMA_EN) if lang == "en" else (CONTEXT_SYSTEM, CONTEXT_SCHEMA)
data = self.ask(self.system_for("judge", system, lang), prompt, schema, [], role="judge")
return clean_context(data)
def translate_lines(self, lines: list[str]) -> list[str]:
"""Fala de um corte (frases em ordem) → português, mesma quantidade. Para o painel e a legenda de
desenvolvimento; o vídeo publicado continua no idioma da fonte."""
if not lines:
return []
prompt = "\n".join(f"{i + 1}. {text}" for i, text in enumerate(lines))
data = self.ask(LINES_SYSTEM, prompt, LINES_SCHEMA, [])
data = self.ask(LINES_SYSTEM, prompt, LINES_SCHEMA, [], purpose="translate")
out = [str(x).strip() for x in (data.get("lines") or [])]
if len(out) != len(lines):
raise JudgeError(f"tradução com {len(out)} linhas para {len(lines)} frases", unavailable=False)
@@ -989,7 +1387,7 @@ class Judge:
def scan(self, prompt: str, images: list[Path], lang: str = "pt") -> dict:
system, schema = (SCAN_SYSTEM_EN, SCAN_SCHEMA_EN) if lang == "en" else (SCAN_SYSTEM, SCAN_SCHEMA)
data = self.ask(system, prompt, schema, images)
data = self.ask(self.system_for("scan", system, lang), prompt, schema, images, role="scan")
if not isinstance(data.get("moments"), list):
raise JudgeError("varredura sem a lista de momentos")
return data
@@ -999,7 +1397,8 @@ class Judge:
if notes:
prompt += "User requests (respect them; may be in Portuguese):\n" + "\n".join(f"- {n}" for n in notes) + "\n"
prompt += "Research and return the game profile in English."
return self.ask(PROFILE_SYSTEM, prompt, PROFILE_SCHEMA, [], search=True, timeout=RESEARCH_TIMEOUT_S)
return self.ask(PROFILE_SYSTEM, prompt, PROFILE_SCHEMA, [], search=True, timeout=RESEARCH_TIMEOUT_S,
purpose="research")
def refine_game(self, name: str, profile: dict, instruction: str, search: bool = True, section: str = "",
history: list[dict] | None = None) -> dict:
@@ -1013,39 +1412,48 @@ class Judge:
f"{'User' if h.get('role') == 'user' else 'AI'}: {str(h.get('text', ''))[:400]}" for h in history[-8:]) + "\n"
prompt += f"User REQUEST:\n{instruction}\n\nReturn the complete updated profile (English) and the reply (Portuguese)."
return self.ask(REFINE_SYSTEM, prompt, REFINE_SCHEMA, [], search=search,
timeout=RESEARCH_TIMEOUT_S if search else TIMEOUT_S)
timeout=RESEARCH_TIMEOUT_S if search else TIMEOUT_S, purpose="research")
def translate_game(self, profile: dict, target: str) -> dict:
"""Traduz o perfil inteiro (pt-BR <-> en-US), mesmo formato, sem busca. Nomes oficiais e hashtags ficam."""
language = TRANSLATE_TARGETS.get(target, target)
prompt = (f"Target language: {language}\nProfile JSON:\n{json.dumps(profile, ensure_ascii=False, indent=1)}\n\n"
"Return the translated profile.")
return self.ask(TRANSLATE_SYSTEM, prompt, PROFILE_SCHEMA, [], timeout=RESEARCH_TIMEOUT_S)
return self.ask(TRANSLATE_SYSTEM, prompt, PROFILE_SCHEMA, [], timeout=RESEARCH_TIMEOUT_S, purpose="translate")
def detect_cam(self, images: list[Path]) -> dict:
return self.ask(CAM_SYSTEM, "Analise os frames anexados (mesma live, instantes diferentes).", CAM_SCHEMA, images)
return self.ask(CAM_SYSTEM, "Analise os frames anexados (mesma live, instantes diferentes).", CAM_SCHEMA, images,
purpose="cam")
# ---------- execução
def ask(self, system: str, prompt: str, schema: dict, images: list[Path], *, search: bool = False,
timeout: int = TIMEOUT_S, model: str | None = None) -> dict:
"""Chama a IA escolhida; se ela falhar por indisponibilidade, a próxima da cadeia de reserva (com o modelo
padrão DELA) e a que falhou fica em pausa. Erro de conteúdo (JSON inválido, campos faltando) não troca."""
timeout: int = TIMEOUT_S, model: str | None = None, role: str = "editor", purpose: str | None = None) -> dict:
"""Chama a IA do papel `role`; se ela falhar por indisponibilidade, a próxima da cadeia de reserva (com o
modelo padrão DELA) e a que falhou fica em pausa. Erro de conteúdo (JSON inválido, campos faltando) não troca.
Cada tentativa é medida (`meter`), com o papel, a IA, o tamanho do prompt e das imagens e os tokens."""
if not self.enabled:
raise JudgeError("IA desligada", unavailable=False)
chain = self.fallback_chain()
conf = self.roles.get(role) or self.roles["editor"]
primary = conf["provider"]
chain = self.fallback_chain(primary)
if not chain:
why = self._skip_reason(self.provider, self.ai.settings()) or "nenhuma IA pronta"
raise JudgeError(f"{PROVIDER_NAMES[self.provider]} indisponível: {why} (veja Configurações → IA)",
why = self._skip_reason(primary, self.ai.settings()) or "nenhuma IA pronta"
raise JudgeError(f"{PROVIDER_NAMES.get(primary, primary)} indisponível: {why} (veja Configurações → IA)",
unavailable=True)
fallback_on = self.ai.settings()["fallback"]["enabled"]
attempts: list[str] = []
for provider in chain:
use_model = (model or self.model) if provider == self.provider else DEFAULT_MODELS[provider]
use_model = (model or self.role_model(role if role in self.roles else "editor")) if provider == primary \
else DEFAULT_MODELS[provider]
effort = conf.get("effort", "") if provider == primary else ""
self._local.usage = None
started = time.monotonic()
try:
data = self._call(provider, system, prompt, schema, images, search, timeout, use_model)
data = self._call(provider, system, prompt, schema, images, search, timeout, use_model, effort)
except JudgeError as exc:
text = str(exc)
unavailable = exc.unavailable if exc.unavailable is not None else is_availability_error(text)
self._measure(role, purpose, provider, use_model, system, prompt, images, started, text)
attempts.append(f"{provider}:{use_model}: {text}")
if not unavailable:
# Erro de conteúdo: a IA respondeu, o pedido é que não deu certo. Não troca de IA.
@@ -1055,16 +1463,38 @@ class Judge:
log.warning("IA %s indisponível (%s); tentando a reserva", provider, text[:160])
continue
raise JudgeError(text, unavailable=True) from exc
self._measure(role, purpose, provider, use_model, system, prompt, images, started, None)
self._local.responder = f"{provider}:{use_model}"
if provider != self.provider:
if provider != primary:
log.info("respondido pela reserva %s:%s", provider, use_model)
return data
raise JudgeError("nenhuma IA respondeu — " + " · ".join(attempts)[:900], unavailable=True)
def _measure(self, role: str, purpose: str | None, provider: str, model: str, system: str, prompt: str,
images: list[Path], started: float, error: str | None) -> None:
if self.meter is None:
return
image_bytes = 0
for img in images:
try:
image_bytes += Path(img).stat().st_size
except OSError:
pass
usage = getattr(self._local, "usage", None) or {}
record = {"role": role, "purpose": purpose or role, "provider": provider, "model": model, "ok": error is None,
"error": (error or "")[:300] or None, "ms": int((time.monotonic() - started) * 1000),
"systemChars": len(system), "promptChars": len(prompt), "images": len(images),
"imageBytes": image_bytes, "tokensIn": usage.get("in"), "tokensOut": usage.get("out"),
"tokensCached": usage.get("cached"), **(getattr(self._local, "scope", None) or {})}
try:
self.meter(record)
except Exception as exc: # noqa: BLE001 - medir nunca derruba a chamada
log.debug("medição da chamada falhou: %s", exc)
def _call(self, provider: str, system: str, prompt: str, schema: dict, images: list[Path], search: bool,
timeout: int, model: str) -> dict:
timeout: int, model: str, effort: str = "") -> dict:
if provider == "codex":
return self._codex(system, prompt, schema, images, search, timeout, model)
return self._codex(system, prompt, schema, images, search, timeout, model, effort)
if provider == "claude":
return self._claude(system, prompt, schema, images, search, timeout, model)
if provider == "gemini":
@@ -1090,7 +1520,7 @@ class Judge:
return result
def _codex(self, system: str, prompt: str, schema: dict, images: list[Path], search: bool, timeout: int,
model: str) -> dict:
model: str, effort: str = "") -> dict:
cmd = find_codex()
if not cmd:
raise JudgeError("Codex CLI não encontrado (npm install -g @openai/codex; codex login)", unavailable=True)
@@ -1109,12 +1539,16 @@ class Judge:
instructions.write_text(system, encoding="utf-8")
lean += ["-c", f"model_instructions_file='{instructions}'"]
stdin = prompt
# Esforço de raciocínio por papel (Equipe de IA); padrão = low, o de sempre.
reasoning = effort if effort in ("low", "medium", "high") else "low"
# `--search` é opção global (antes de `exec`). Cada imagem com seu `-i`; o "-" (prompt pela entrada
# padrão) vem depois de uma opção de valor único para não ser lido como mais uma imagem.
# `--json`: eventos JSONL na saída padrão — o `turn.completed` traz o uso de tokens (medição F0).
args = [*cmd, *(["--search"] if search else []), "exec", "--skip-git-repo-check", "--ephemeral",
"--sandbox", "read-only", "-c", 'model_reasoning_effort="low"', *lean, "-m", model, *image_args,
"--output-schema", str(schema_file), "-o", str(out), "-C", tmp, "-"]
self._run(args, stdin, Path(tmp), timeout, "codex")
"--sandbox", "read-only", "--json", "-c", f'model_reasoning_effort="{reasoning}"', *lean,
"-m", model, *image_args, "--output-schema", str(schema_file), "-o", str(out), "-C", tmp, "-"]
result = self._run(args, stdin, Path(tmp), timeout, "codex")
self._local.usage = codex_usage(result.stdout.decode("utf-8", errors="replace"))
try:
return json.loads(out.read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError) as exc:
@@ -1144,6 +1578,7 @@ class Judge:
envelope = json.loads(result.stdout.decode("utf-8", errors="replace"))
except json.JSONDecodeError as exc:
raise JudgeError("o Claude não devolveu JSON", unavailable=False) from exc
self._local.usage = claude_usage(envelope)
if envelope.get("is_error"):
# Pode ser cota/login ("Credit balance is too low", "Not logged in"): o texto decide (unavailable=None).
raise JudgeError(f"o Claude terminou com erro: {str(envelope.get('result'))[:200]}")
@@ -1190,7 +1625,9 @@ class Judge:
short += " Frames anexados, na ordem: " + " ".join(refs)
args = [*cmd, "-p", short, "-o", "json", "--approval-mode", "plan", "--skip-trust", "-m", model]
result = self._run(args, stdin, Path(tmp), timeout, "gemini")
return parse_gemini_output(result.stdout.decode("utf-8", errors="replace"))
stdout = result.stdout.decode("utf-8", errors="replace")
self._local.usage = gemini_usage(extract_json_object(stdout, fences=False) or {})
return parse_gemini_output(stdout)
def parse_gemini_output(stdout: str) -> dict: