Files
CenaForge/clipper/app/judge.py
T
MateuusandClaude Opus 5.5 dbb5e8ef92 Sincronização: detecção do jogo + revisão/final, dublagem, falantes, expressões e Equipe de IA
Conflitos resolvidos juntando os dois lados:
- db.py: v16 (detecção do jogo) e v17 (Equipe de IA) em sequência.
- judge.py: a varredura exige os campos das duas frentes (screen_game_confidence/screen_evidence e lines).
- proxy do painel: libera judge/report e sessions/id/game/detect.
- skill: detecção do jogo vira a 1.55.0 (gotcha 180 → 186), acima da 1.54.0 das cinco frentes.

Suíte do Clipador inteira passa; painel: tsc + 119 testes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 05:11:47 -03:00

1690 lines
101 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""IA do Clipador pelas CLIs já logadas no PC (Codex/GPT por padrão, ou Claude) — sem chave de API.
Quatro usos, todos com saída JSON validada por schema:
1. **juiz** de candidato (chat/áudio apontaram): manter/descartar, nota, início/fim, título e legenda. Vê a
transcrição com bastante tempo para trás (o comentário vem DEPOIS da ação), o chat, os emotes, o perfil do
jogo e FRAMES da tela.
2. **varredura**: a cada poucos minutos de gravação a IA olha a janela inteira (fala + tela + chat) e propõe
momentos mesmo sem pico de chat — essencial em live pequena (3–5 pessoas) ou chat que reage pouco.
3. **pesquisa do jogo** (com busca na web): o que é o jogo, o que rende corte nele, gírias, novidades.
4. **webcam**: onde está a câmera do streamer no quadro (retângulo normalizado), para o layout câmera-em-cima.
Provedores: `codex` (`codex exec`, imagens com `-i`, web com `--search`, `--output-schema`), `claude`
(`claude -p --json-schema`; imagens pela ferramenta Read, web por WebSearch/WebFetch) ou `gemini`
(`gemini -p -o json --approval-mode plan`; schema no prompt, imagens por `@arquivo`, web por google_web_search).
Login, chave de API e IA reserva vêm de Configurações → IA no painel (`data/ai/`, contrato em `doc/ia.md`): se a
IA escolhida falhar por indisponibilidade (cota, sobrecarga, login, rede, CLI ausente, tempo esgotado), a próxima
da ordem tenta com o modelo padrão dela, e a que falhou fica em pausa por `cooldownMin`.
"""
from __future__ import annotations
import json
import logging
import os
import re
import shutil
import subprocess
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
log = logging.getLogger("cenaforge_clipper.judge")
PROVIDERS = ("codex", "claude", "gemini", "off")
AI_ENABLED = ("codex", "claude", "gemini")
DEFAULT_MODELS = {"codex": "gpt-6-luna", "claude": "haiku", "gemini": "gemini-3.5-flash"}
CLAUDE_MODELS = [
{"id": "haiku", "label": "Haiku (mais barato)"},
{"id": "sonnet", "label": "Sonnet (equilíbrio)"},
{"id": "opus", "label": "Opus (mais capaz, mais caro)"},
]
# Lista estática (`gemini models -o json` existe, mas custa um processo Node a cada abertura do painel).
GEMINI_MODELS = [
{"id": "gemini-3.5-flash", "label": "3.5 Flash (rápido e barato)"},
{"id": "gemini-3.1-flash-lite", "label": "3.1 Flash-Lite (mais barato)"},
{"id": "gemini-2.5-pro", "label": "2.5 Pro (mais capaz, mais caro)"},
]
CONTEXT_AFTER_S = 15.0
# Padrões de duração = os da configuração do corte (layout.DEFAULTS): mínimo 60 s, máximo 90 s, volta até 2 min.
DEFAULT_MIN_S = float(layout.DEFAULTS["duration"]["minS"])
DEFAULT_MAX_S = float(layout.DEFAULTS["duration"]["maxS"])
DEFAULT_BACKTRACK_S = float(layout.DEFAULTS["duration"]["backtrackS"])
TIMEOUT_S, RESEARCH_TIMEOUT_S = 240, 420
NO_WINDOW = subprocess.CREATE_NO_WINDOW if sys.platform == "win32" else 0
# Economia de tokens (medido em 17/11/2026, codex-cli 0.169.0): cada chamada do juiz é um processo novo e
# pagava ~77 mil caracteres fixos (~19 mil tokens) antes do prompt — instruções de agente de código (18 mil),
# ferramentas (46 mil: exec, plugins, computer-use) e listas de skills/apps. Uma live de 3,7 h = 150 chamadas.
# Sem busca na web o juiz não usa ferramenta nenhuma (as imagens vão por `-i`), então: o texto do juiz
# substitui as instruções de base e os recursos com ferramentas saem. Resultado: ~35 mil caracteres fixos.
# Com `--search` (pesquisa de jogo) só saem os extras; a web do Codex depende das ferramentas de execução.
CODEX_TOOL_FEATURES = ("plugins", "apps", "shell_tool", "unified_exec", "code_mode_host", "sleep_tool",
"skill_search", "tool_suggest", "in_app_browser", "browser_use")
CODEX_EXTRA_FEATURES = ("computer_use", "image_generation", "goals", "hooks")
CODEX_UNUSED_PLUGINS = ("computer-use@openai-bundled", "unified-computer-use@openai-bundled")
def codex_lean_overrides(search: bool, config_file: Path | None = None) -> list[str]:
"""Overrides `-c` só para esta chamada (a config global do Codex não muda)."""
features = CODEX_EXTRA_FEATURES + (() if search else CODEX_TOOL_FEATURES)
overrides = [f"features.{name}=false" for name in features]
try:
config = (config_file or Path.home() / ".codex" / "config.toml").read_text(encoding="utf-8")
except OSError:
config = ""
# `-c mcp_servers={}` não desliga (o Codex mescla tabelas): é preciso `enabled=false` por servidor.
for name in dict.fromkeys(re.findall(r'^\s*\[mcp_servers\.("?)([A-Za-z0-9_-]+)\1\]\s*$', config, re.M)):
overrides.append(f"mcp_servers.{name[1]}.enabled=false")
for plugin in CODEX_UNUSED_PLUGINS:
if f'[plugins."{plugin}"]' in config:
overrides.append(f'plugins."{plugin}".enabled=false')
return [arg for item in overrides for arg in ("-c", item)]
# ---------------------------------------------------------------- guia editorial (pesquisa de 16–17/11/2026)
CLIP_GUIDE = """O que faz um bom corte de live (pesquisa de mercado, 2026):
- Abre no momento forte: o espectador decide em 1–2 s. Nada de "como eu tava falando".
- Se explica sozinho: quem nunca viu a live entende em poucos segundos (contexto mínimo no começo).
- Rende corte: reação forte (susto, risada, raiva), jogada absurda/virada, falha engraçada, treta, história que
se desenrola, fala marcante, e INFORMAÇÃO NOVA DO JOGO (mecânica, segredo, novidade, comparação) — em
lançamentos (ex.: GTA 6) informação vale tanto quanto reação.
- Não rende: espera, menu/loading, leitura de doação/propaganda, conversa sem gancho, piada interna da live.
- TEMPO: o streamer costuma comentar DEPOIS da ação. Volte até o início da AÇÃO que motivou o comentário (pode
ser de 20 s a 2 min antes da fala, até o limite de volta informado) — o corte precisa mostrar a ação e a reação.
- Corte justo: termina logo depois do pagamento (reação/resolução)."""
# Gírias/memes do chat (BR/Twitch) que mudam o sentido do momento. O analista interpreta com o contexto.
CHAT_GLOSSARY = """Gírias comuns do chat (interprete pelo contexto):
- "server chinês", "ping", "lag", "travou/travando", "exit lag", "bugou", "rubberband", "teleportou" → o jogo ou a
live está travando/com atraso (personagem pulando de lugar, morrendo do nada) — a graça é o lag.
- "kkkk", "KEKW", "LUL", "OMEGALUL", "ICANT", "PepeLaugh" → risada; "?????" → confusão/não entenderam;
"F" → morte/perda/luto; "W"/"L" → vitória/derrota; "Pog/POGGERS" → impressionados; "monkaS/monkaW" → tensão;
"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")
ANALYSIS_SCHEMA = {
"type": "object",
"properties": {
"situation": {"type": "string", "enum": list(SITUATIONS)},
"what_happened": {"type": "string"},
"screen": {"type": "string"},
"speech": {"type": "string"},
"chat_meaning": {"type": "string"},
"confidence": {"type": "number"},
"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", "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
com o instante de cada um e o chat.
Cruze as três fontes antes de concluir: a fala sozinha engana (ex.: "tô jogando três jogos… morri, morri" junto
de chat "server chinês?/kkkk" e a tela pulando = o jogo está travando e ele morre por causa do lag, não está
jogando três jogos). O chat reage alguns segundos depois do acontecimento.
""" + CHAT_GLOSSARY + """
Campos:
- situation: o tipo do momento (um da lista).
- what_happened: 2–3 frases factuais do que aconteceu, na ordem, sem exagero.
- screen: o que os frames mostram (cite o nº do frame) — ou "frames não ajudam".
- speech: o que a fala revela (cite o instante).
- chat_meaning: o que o chat está dizendo/rindo e por quê.
- confidence: 0–1, quanto você tem certeza da interpretação (baixe se as fontes não batem).
- 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 = {
"type": "object",
"properties": {
"keep": {"type": "boolean"},
"score": {"type": "number"},
"start_s": {"type": "number"},
"end_s": {"type": "number"},
"title": {"type": "string"},
"caption": {"type": "string"},
"hashtags": {"type": "array", "items": {"type": "string"}},
"reason": {"type": "string"},
},
"required": ["keep", "score", "start_s", "end_s", "title", "caption", "hashtags", "reason"],
"additionalProperties": False,
}
# A varredura só aponta momentos (o juiz escreve título/legenda/hashtags depois): sem `keep` e sem `hashtags`.
_MOMENT = {
"type": "object",
"properties": {k: v for k, v in VERDICT_SCHEMA["properties"].items() if k not in ("keep", "hashtags")},
"required": ["score", "start_s", "end_s", "title", "caption", "reason"],
"additionalProperties": False,
}
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},
"lines": SCENE_LINES,
},
"required": ["screen_game", "screen_game_confidence", "screen_evidence", "has_webcam", "summary", "moments", "lines"],
"additionalProperties": False,
}
_MISSION = {
"type": "object",
"properties": {
"name": {"type": "string"},
"chapter": {"type": "string"},
"summary": {"type": "string"},
"completion_triggers": {"type": "array", "items": {"type": "string"}},
},
"required": ["name", "chapter", "summary", "completion_triggers"],
"additionalProperties": False,
}
PROFILE_SCHEMA = {
"type": "object",
"properties": {
"name": {"type": "string"},
"aliases": {"type": "array", "items": {"type": "string"}},
"summary": {"type": "string"},
"genre": {"type": "string"},
"mechanics": {"type": "array", "items": {"type": "string"}},
"clip_worthy": {"type": "array", "items": {"type": "string"}},
"avoid": {"type": "array", "items": {"type": "string"}},
"jargon": {"type": "array", "items": {"type": "string"}},
"news": {"type": "array", "items": {"type": "string"}},
"hashtags": {"type": "array", "items": {"type": "string"}},
"sources": {"type": "array", "items": {"type": "string"}},
"missions": {"type": "array", "items": _MISSION},
"end_triggers": {"type": "array", "items": {"type": "string"}},
},
"required": ["name", "aliases", "summary", "genre", "mechanics", "clip_worthy", "avoid", "jargon", "news", "hashtags",
"sources", "missions", "end_triggers"],
"additionalProperties": False,
}
CAM_SCHEMA = {
"type": "object",
"properties": {
"has_webcam": {"type": "boolean"},
"x": {"type": "number"}, "y": {"type": "number"}, "w": {"type": "number"}, "h": {"type": "number"},
"game_on_screen": {"type": "string"},
},
"required": ["has_webcam", "x", "y", "w", "h", "game_on_screen"],
"additionalProperties": False,
}
JUDGE_SYSTEM = """Você é o EDITOR de cortes de live para Shorts, TikTok, Reels e YouTube, em português do Brasil.
Recebe um trecho candidato de uma live (contexto do jogo, transcrição com tempos, chat, emotes) e, quando houver,
a ANÁLISE do analista da equipe, que já cruzou tela, fala e chat. Confie na análise para entender O QUE
aconteceu; o seu trabalho é decidir se rende corte e escrever título e legenda FIÉIS a isso.
""" + CLIP_GUIDE + """
""" + CHAT_GLOSSARY + """
Título e legenda: descrevem a situação real (ex.: se a análise diz lag, o título é sobre o lag/travamento, não
sobre a frase solta da transcrição). Com confidence da análise < 0,5, seja descritivo e não invente detalhes.
Use action_start_s/reaction_end_s da análise como base para start_s/end_s."""
JUDGE_SYSTEM += """
Regras da resposta:
- keep=false para o que não rende; score de 0 a 10 (7+ = corte forte; abaixo de 5 = descartar).
- start_s e end_s em segundos da gravação, DENTRO da janela recebida e respeitando a duração mínima/máxima
informada; comece antes da ação (contexto) e termine logo depois da reação. Não corte no meio de uma frase.
- title: até 70 caracteres, chamativo mas verdadeiro, sem inventar o que não está na fala/tela.
- caption: 1–2 frases, SEM hashtags e sem link (o sistema acrescenta as hashtags do canal e do jogo e o crédito).
- hashtags: 2 a 4 tags DO MOMENTO, sem "#": a missão/atividade, o evento, o modo, o lugar, o item ou o personagem
que aparece NESTE trecho (ex.: nome da missão ou do assalto, "perseguição", "sorteio", "Lamborghini", "lag").
Prefira os termos do perfil do jogo (mecânicas, gírias) e o que o streamer e o chat falam. Nada genérico
("gameplay", "live", "viral"), nada que não aconteça aqui, e não repita o canal nem o nome do jogo.
- reason: uma frase dizendo por que manteve ou descartou (cite o que viu na tela, se ajudou).
- Não use ferramentas nem leia nada além do que foi entregue. Responda só com o JSON pedido."""
SCAN_SYSTEM = """Você é editor de cortes de live e está ASSISTINDO uma live por janelas de alguns minutos.
Recebe o contexto do jogo, a transcrição com tempos (segundos da gravação), frames da tela com o instante de
cada um, o chat (pode ser quase vazio: live pequena) e os cortes já feitos nessa região.
""" + CLIP_GUIDE + """
Tarefa: aponte de 0 a 2 momentos desta janela que dariam um bom corte SOZINHOS. Se nada rende, devolva
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"); 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).
- 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
# dono ler no painel. Pesquisar em inglês também acha mais fonte (wikis, guias) — sobretudo lista de missões.
PROFILE_SYSTEM = """You research video games for a live-stream clip editor. Use web search to confirm what the game
is (a Twitch category name can be abbreviated or ambiguous). Be factual and cite sources (URLs). Answer only with the
requested JSON, all text in ENGLISH.
- aliases: up to 10 other names streamers, chat and stream categories use (abbreviations, numbers, local titles).
- summary: 2-3 sentences on what the game is and how it plays.
- mechanics: up to 8 systems/activities that show up in gameplay.
- clip_worthy: up to 10 situations that make a good clip IN THIS GAME (specific, not generic).
- avoid: up to 6 situations that look like a moment but are not (menus, grinding, queues...).
- jargon: up to 12 terms/slang streamers and chat use (to understand the transcript), including Brazilian
Portuguese slang when the game is popular in Brazil.
- news: up to 6 recent news items with month/year (release, update, controversy) that make information valuable.
- hashtags: 3 to 6 hashtags the audience uses for THIS game on TikTok, Shorts and Reels (international and Brazil):
the game name without spaces, the known abbreviation, the mode/genre when people search it (e.g. GTARP). The
first one is the main tag. Write them with "#" and never invent a tag nobody uses.
- missions: the game's STORY missions exactly as reliable sources list them (official wiki, major guides), ONLY if
that list is public; official mission names, in story order; up to 120. For each: name; chapter (act/chapter or
""); summary (one sentence); completion_triggers (up to 4): what visibly or audibly marks the end of THAT mission
(e.g. "MISSION PASSED" banner, result/score screen, final cutscene, a specific objective text or line). If the
game is not released yet or the list is not public, return missions=[] - NEVER invent missions.
- end_triggers: up to 10 general signs that a mission/objective just ended in this game (banner text, sound,
result screen, money/reward popup, cutscene, failure screen like "MISSION FAILED"/"WASTED").
- sources: up to 8 URLs you used.
If "user requests" come along, they outweigh the research: add what the user asked to add and respect what they
asked to remove or fix (they know the channel and the game). The requests may be written in Portuguese."""
REFINE_SYSTEM = """You maintain the profile of a game used by a live-stream clip editor. The profile is in ENGLISH.
You receive the CURRENT profile (JSON) and a REQUEST from the user, usually written in Brazilian Portuguese (add,
fix, remove or detail something). Return the COMPLETE updated profile, same format, all profile text in ENGLISH:
- keep everything the request does not touch, with the same text;
- apply the request to the right field (clip-worthy situation -> clip_worthy; what is not -> avoid; slang -> jargon;
mechanic -> mechanics; news -> news with month/year; game hashtag -> hashtags with "#", main one first; story
mission -> missions; general "mission is over" sign -> end_triggers; other name -> aliases), in the style of the
existing items;
- lists may grow up to 15 items when the user asks to add (missions up to 120);
- to confirm a fact you may use web search and add the URL to sources; never invent missions;
- the user knows the channel and the game: what they state is right, even if you cannot find it online;
- if a SECTION in focus comes along, the request is about it (touch other sections only if the request says so);
- you may turn a vague request into concrete, useful items for the editor;
- reply: 1-2 sentences IN BRAZILIAN PORTUGUESE telling the user what you changed (or, if the request is a
question, the answer, also in Portuguese).
Answer only with the requested JSON."""
TRANSLATE_SYSTEM = """You translate the profile of a video game (JSON) between English and Brazilian Portuguese for a
live-stream clip editor. Return the same JSON structure with the same number of items in every list and in the same
order. Translate summaries and descriptions naturally. Keep AS IS: the game name, proper names (characters, places,
gangs, vehicles), OFFICIAL mission names, on-screen texts quoted in triggers (e.g. "MISSION PASSED"), hashtags,
aliases and URLs. Slang in jargon stays as players say it (you may add a short meaning). Answer only with the JSON."""
TRANSLATE_TARGETS = {"pt-BR": "Brazilian Portuguese (pt-BR)", "en-US": "English (en-US)"}
REFINE_SCHEMA = {
"type": "object",
"properties": {**PROFILE_SCHEMA["properties"], "reply": {"type": "string"}},
"required": [*PROFILE_SCHEMA["required"], "reply"],
"additionalProperties": False,
}
PROFILE_SECTIONS = {"summary": "Resumo", "clip_worthy": "O que rende corte", "avoid": "Evitar", "mechanics": "Mecânicas",
"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.
game_on_screen: o jogo que aparece (ou "desconhecido"). Responda só com o JSON pedido."""
@dataclass(frozen=True)
class Verdict:
keep: bool
score: float
start_s: float
end_s: float
title: str
caption: str
reason: str
model: str
# Tags DO MOMENTO (sem "#"), escolhidas pela IA; as do canal e do jogo o sistema põe (app/hashtags.py).
hashtags: tuple[str, ...] = ()
# Fonte em inglês: título, legenda e motivo traduzidos para o painel ({} = sessão em português).
pt: dict = field(default_factory=dict)
class JudgeError(RuntimeError):
"""Falha da IA. `unavailable`: True = indisponibilidade (dispara a reserva), False = erro de conteúdo (não
troca de IA), None = decidir pelo texto (`is_availability_error`)."""
def __init__(self, message: str, unavailable: bool | None = None):
super().__init__(message)
self.unavailable = unavailable
# ---------------------------------------------------------------- reserva: o que é "indisponível" (doc/ia.md)
# Falha que não é culpa do pedido: cota/limite, sobrecarga, login/chave, rede, CLI ausente e tempo esgotado.
_AVAILABILITY_PATTERNS = re.compile(
r"rate[\s_-]?limit|too many requests|\b429\b|quota|resource[\s_]exhausted|usage limit|credit balance"
r"|overloaded|\b529\b|\b503\b|unavailable"
r"|\b401\b|\b403\b|unauthori[sz]ed|not logged in|invalid[\s_-]?api[\s_-]?key|api key not valid|IneligibleTier"
r"|\bECONN\w*|ETIMEDOUT|ENOTFOUND|EAI_AGAIN|network"
r"|timed? ?out|tempo esgotado|passou de \d+ s"
r"|n[ãa]o encontrad[oa]|not found in path|n[ãa]o consegui rodar|command not found|is not recognized",
re.IGNORECASE,
)
def is_availability_error(text: str) -> bool:
"""True quando a mensagem de erro indica que a IA está indisponível (e vale tentar a reserva)."""
return bool(text) and bool(_AVAILABILITY_PATTERNS.search(text))
def extract_json_object(text: str, fences: bool = True) -> dict | None:
"""Primeiro objeto JSON do texto (tolera cercas ```json e texto em volta). None se não houver.
`fences=False` ignora cercas (para o envelope da CLI, cujo texto escapado pode conter uma)."""
if not text:
return None
body = text.strip()
fence = re.search(r"```(?:json)?\s*(.*?)```", body, re.S | re.I) if fences else None
candidates = ([fence.group(1).strip()] if fence else []) + [body]
decoder = json.JSONDecoder()
for candidate in candidates:
for match in re.finditer(r"\{", candidate):
try:
value, _end = decoder.raw_decode(candidate, match.start())
except json.JSONDecodeError:
continue
if isinstance(value, dict):
return value
return None
# ---------------------------------------------------------------- juízes em inglês (fonte gringa)
# Pedido do dono (18/11/2026): "se a fonte está em inglês, os juízes trabalham em inglês". A equipe não fala inglês:
# o vídeo (gancho, título, legenda, hashtags) sai em inglês e a MESMA resposta traz um bloco `pt` com a tradução
# para o painel — sem chamada extra. Regras completas em doc/clipador/IDIOMAS.md.
CLIP_GUIDE_EN = """What makes a good live-stream clip (market research, 2026):
- Opens on the strong moment: viewers decide in 1–2 s. No "like I was saying".
- Explains itself: someone who never saw the stream gets it in a few seconds (minimal context at the start).
- Clip-worthy: strong reaction (jump scare, laughing fit, rage), insane play/comeback, funny fail, beef/drama, a story
that unfolds, a memorable line, and NEW GAME INFO (mechanic, secret, news, comparison) — around launches
(e.g. GTA 6) information is worth as much as a reaction.
- Not clip-worthy: waiting, menus/loading, reading donations/ads, chatter with no hook, stream inside jokes.
- TIMING: streamers usually comment AFTER the action. Go back to the start of the ACTION that triggered the
comment (20 s to 2 min before the line, up to the backtrack limit given) — the clip must show action and reaction.
- Tight ending: end right after the payoff (reaction/resolution)."""
CHAT_GLOSSARY_EN = """Common chat slang on English-speaking Twitch/Kick/YouTube (read it by context):
- Laughing: "LUL", "LULW", "KEKW", "OMEGALUL", "ICANT", "pepeLaugh", "LMAO", "LMFAO", "LOL", "ROFL", "💀"/"☠️"
("I'm dead" = so funny), "😭" (crying laughing), "dead", "I'm crying".
- Shock/confusion: "HUH", "?????", "WTF", "OMG", "no way", "nah", "bruh", "monkaS"/"monkaW" (tension), "Aware",
"Clueless" (ironic: he doesn't realise), "COPIUM" (denial), "Sadge" (sad).
- Hype/praise: "Pog", "POGGERS", "PogU", "W"/"dub" (win), "L" (loss), "LETSGO", "Clap", "EZ", "GG", "clutch",
"cracked" (very skilled), "goated", "sheesh", "diff" (skill gap).
- "F" = death/loss; "cooked"/"he's cooked" = doomed; "throwing"/"sold" = blew it; "bot"/"NPC" = bad/robotic play.
- "lag", "ping", "rubberbanding", "desync", "server dying" → the game/stream is lagging; the joke is the lag.
- "clip it"/"CLIP IT" → clip request; "hacker"/"cheater"/"aimbot" → suspected cheating.
- Channel emotes (streamer prefix + base emote, e.g. tfueLUL) carry the same reaction as the base emote."""
PT_NOTE = ("The team that reviews clips only reads Brazilian Portuguese: fill `pt` with a faithful Brazilian "
"Portuguese translation of the listed fields (keep game terms, names and slang meaning; do not add facts).")
ANALYST_SYSTEM_EN = """You are the ANALYST of a live-stream clipping team. You do not write titles: you describe
faithfully WHAT HAPPENED in the segment so the editor can decide. You get game context, a timed transcript (the
streamer speaks English), screen FRAMES with their timestamps and the chat.
Cross-check all three sources before concluding: speech alone misleads (e.g. "I'm playing three games... I died, I
died" plus chat "server dying?/LMAO" and the screen jumping = the game is lagging and he dies because of the lag).
Chat reacts a few seconds after the event.
""" + CHAT_GLOSSARY_EN + """
Fields (in English):
- situation: the moment type (one from the list; the ids are fixed, keep them as they are).
- what_happened: 2–3 factual sentences of what happened, in order, no exaggeration.
- screen: what the frames show (cite the frame #) — or "frames don't help".
- speech: what the speech reveals (cite the timestamp).
- chat_meaning: what chat is saying/laughing at and why.
- confidence: 0–1, how sure you are (lower it when sources disagree).
- 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."""
JUDGE_SYSTEM_EN = """You are the EDITOR of live-stream clips for Shorts, TikTok, Reels and YouTube, for an
English-speaking (US) audience. You get a candidate segment of a stream (game context, timed transcript, chat,
emotes) and, when available, the ANALYST's analysis, which already cross-checked screen, speech and chat. Trust the
analysis to understand WHAT happened; your job is to decide whether it makes a clip and write a title and caption
FAITHFUL to it.
""" + CLIP_GUIDE_EN + """
""" + CHAT_GLOSSARY_EN + """
Title and caption describe the real situation (if the analysis says lag, the title is about the lag, not about a
random line of the transcript). With analysis confidence < 0.5, be descriptive and do not invent details.
Use the analysis action_start_s/reaction_end_s as the base for start_s/end_s.
Answer rules:
- keep=false for what doesn't work; score 0–10 (7+ = strong clip; below 5 = discard).
- start_s and end_s in seconds of the recording, INSIDE the window given and within the min/max duration given;
start before the action (context) and end right after the reaction. Never cut mid-sentence.
- title: up to 70 characters, English, catchy but true, written like a native US clip channel (not a literal
translation), nothing that isn't in the speech/screen.
- caption: 1–2 sentences in English, NO hashtags and no links (the system adds channel/game hashtags and credit).
- hashtags: 2 to 4 tags OF THE MOMENT, English, without "#": the mission/activity, event, mode, place, item or
character in THIS segment. Prefer game-profile terms and what streamer and chat say. Nothing generic ("gameplay",
"live", "viral"), nothing that doesn't happen here, and do not repeat the channel or the game name.
- reason: one sentence on why you kept or discarded it (cite the screen if it helped).
- pt: title, caption and reason translated. """ + PT_NOTE + """
- Do not use tools or read anything beyond what was given. Answer only with the requested JSON."""
SCAN_SYSTEM_EN = """You are a live-stream clip editor WATCHING a stream in windows of a few minutes. The streamer
speaks English. You get game context, a timed transcript (seconds of the recording), screen frames with their
timestamps, the chat (may be almost empty) and clips already made in this region.
""" + CLIP_GUIDE_EN + """
""" + CHAT_GLOSSARY_EN + """
Task: point out 0 to 2 moments in this window that would make a good clip ON THEIR OWN. If nothing works, return
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"); 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).
- 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."""
def _pt_block(*keys: str) -> dict:
return {"type": "object", "properties": {k: {"type": "string"} for k in keys}, "required": list(keys),
"additionalProperties": False}
def _with(schema: dict, **extra: dict) -> dict:
"""Schema + campos novos obrigatórios (os CLIs exigem `required` com todas as propriedades)."""
return {**schema, "properties": {**schema["properties"], **extra}, "required": [*schema["required"], *extra]}
ANALYSIS_SCHEMA_EN = _with(ANALYSIS_SCHEMA, pt=_pt_block("what_happened", "screen", "speech", "chat_meaning", "hook"))
VERDICT_SCHEMA_EN = _with(VERDICT_SCHEMA, pt=_pt_block("title", "caption", "reason"))
SCAN_SCHEMA_EN = _with({**SCAN_SCHEMA, "properties": {**SCAN_SCHEMA["properties"],
"moments": {"type": "array", "items": _with(_MOMENT, pt=_pt_block("title", "reason"))}}},
summary_pt={"type": "string"})
# Tradução da fala de um corte (painel e legenda em português de desenvolvimento): frases numeradas → mesma quantidade.
LINES_SCHEMA = {
"type": "object",
"properties": {"lines": {"type": "array", "items": {"type": "string"}}},
"required": ["lines"],
"additionalProperties": False,
}
LINES_SYSTEM = """You translate the speech of a live-streamer (auto transcript, may have errors and slang) into
Brazilian Portuguese, for a team that doesn't speak English. You get numbered lines in order; they are one
continuous talk, so use the neighbours as context. Return `lines` with EXACTLY the same number of items, same order,
one translation per line: natural spoken Brazilian Portuguese, short, faithful (keep swearing level, game terms and
names; translate the slang's meaning, e.g. "he's cooked" -> "ele tá ferrado"). If a line is noise, translate it
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"
# Rótulos dos prompts montados aqui (o texto do usuário). Mesmas chaves nos dois idiomas.
LABELS = {
"pt": {"live_title": "Título da live", "unknown": "desconhecido", "channel": "Canal", "window": "Janela disponível",
"candidate": "Candidato da heurística", "peak": "pico de reação em", "duration": "Duração do corte",
"signals": "Sinais da heurística", "face": "Rosto do streamer (expressão medida na webcam, relativa ao normal dele)",
"transcript": "Transcrição", "no_speech": "(sem fala transcrita)", "chat_per": "Mensagens do chat por",
"no_chat": "sem chat", "top_emotes": "Emotes mais usados", "none": "nenhum", "chat_sample": "Amostra do chat",
"no_chat_p": "(sem chat)", "frames_none": "Frames: (nenhum)", "frames": "Frames anexados, em ordem",
"new_window": "Janela nova", "back_to": "pode voltar até {s}s para pegar o início de uma ação",
"done": "Cortes já feitos aqui", "analysis": "Análise do ANALISTA (cruzou tela, fala e chat)"},
"en": {"live_title": "Stream title", "unknown": "unknown", "channel": "Channel", "window": "Available window",
"candidate": "Heuristic candidate", "peak": "reaction peak at", "duration": "Clip duration",
"signals": "Heuristic signals", "face": "Streamer face (expression measured on the webcam, relative to his normal)",
"transcript": "Transcript", "no_speech": "(no transcribed speech)", "chat_per": "Chat messages per",
"no_chat": "no chat", "top_emotes": "Top emotes", "none": "none", "chat_sample": "Chat sample",
"no_chat_p": "(no chat)", "frames_none": "Frames: (none)", "frames": "Attached frames, in order",
"new_window": "New window", "back_to": "may go back to {s}s to catch the start of an action",
"done": "Clips already made here", "analysis": "ANALYST's analysis (cross-checked screen, speech and chat)"},
}
# ---------------------------------------------------------------- prompts
# Idiomas que o serviço conhece (fonte/sessão `language`; o painel oferece os mesmos). Nome legível para o prompt.
LANGUAGE_NAMES = {"pt-BR": "português do Brasil", "en-US": "English (US)", "es-419": "Español (Latinoamérica)"}
DEFAULT_LANGUAGE = "pt-BR"
def output_language_note(language: str | None) -> str:
"""Linha que vai no contexto do EDITOR e da VARREDURA quando a saída não é em português: título, legenda e
hashtags no idioma do público. Vazia para pt-BR (os prompts já são em português)."""
code = (language or "").strip() or DEFAULT_LANGUAGE
if code == DEFAULT_LANGUAGE or lang_key(code) == "en":
return "" # inglês: os juízes já trabalham em inglês (ANALYST/JUDGE/SCAN_SYSTEM_EN)
name = LANGUAGE_NAMES.get(code, code)
return (f"Idioma de saída: {name}. Título, legenda e hashtags em {name}, naturais para o público desse idioma "
f"(a transcrição e o chat podem estar em outro idioma; não traduza literalmente, escreva como um editor nativo).")
MISSIONS_IN_PROMPT = 25
MISSIONS_PROMPT_CHARS = 1500
def mission_lines(profile: dict, lang: str = "pt") -> list[str]:
"""Gatilhos de fim de missão e as missões (nome + gatilhos) para o prompt, com teto de tamanho: o perfil do GTA
pode ter 100+ missões, e o contexto vai em todo julgamento."""
lines: list[str] = []
triggers = [str(t) for t in (profile.get("end_triggers") or [])[:10] if t]
if triggers:
lines.append(("Mission/objective end signals in this game: " if lang == "en" else
"Sinais de fim de missão/objetivo neste jogo: ") + "; ".join(triggers))
missions = [m for m in (profile.get("missions") or []) if isinstance(m, dict) and m.get("name")]
if missions:
parts, used = [], 0
for m in missions[:MISSIONS_IN_PROMPT]:
ends = " / ".join(str(t) for t in (m.get("completion_triggers") or [])[:2] if t)
item = f"{m['name']}" + (f" ({'end' if lang == 'en' else 'fim'}: {ends})" if ends else "")
if used + len(item) > MISSIONS_PROMPT_CHARS:
break
parts.append(item)
used += len(item) + 2
extra = len(missions) - len(parts)
more = (f"; …and {extra} more" if lang == "en" else f"; …e mais {extra}") if extra > 0 else ""
lines.append(("Story missions: " if lang == "en" else "Missões da história: ") + "; ".join(parts) + more)
if triggers or missions:
lines.append("If the segment is the end of a mission, end the clip right after the end trigger "
"(the win/fail moment is the climax)." if lang == "en" else
"Se o trecho é o fim de uma missão, termine o corte logo depois do gatilho de fim "
"(o momento de vitória/falha é o clímax).")
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":
return _game_context_en(game, screen_game, profile, live_title, history, confirmed)
lines = [f"Título da live: {live_title or '(desconhecido)'}"]
if confirmed:
# O usuário confirmou no painel: não questionar (jogo novo/pouco conhecido lembra outros na tela).
lines.append(f"Jogo CONFIRMADO pelo usuário: {game}. A tela pode lembrar outro jogo parecido (ex.: GTA, "
f"Warzone) — não questione o jogo; use o perfil abaixo para entender o que acontece.")
else:
lines.append(f"Jogo pela categoria da plataforma: {game or '(desconhecida)'}")
if screen_game and screen_game.lower() not in (game or "").lower():
lines.append(f"Jogo que a IA viu na tela recentemente: {screen_game} (confira nos frames; a categoria pode estar errada)")
if profile:
lines.append(f"Perfil do jogo: {profile.get('summary', '')}")
for key, label in (("clip_worthy", "Rende corte neste jogo"), ("avoid", "Não rende"),
("mechanics", "Mecânicas/atividades (termos para as hashtags do momento)"),
("jargon", "Gírias/termos"), ("news", "Novidades")):
if profile.get(key):
lines.append(f"{label}: " + "; ".join(profile[key][:10]))
lines.extend(mission_lines(profile))
if history:
lines.append(f"O que aconteceu antes na live: {history}")
return "\n".join(lines)
def _game_context_en(game: str, screen_game: str, profile: dict | None, live_title: str, history: str,
confirmed: bool) -> str:
lines = [f"Stream title: {live_title or '(unknown)'}"]
if confirmed:
lines.append(f"Game CONFIRMED by the user: {game}. The screen may look like a similar game (e.g. GTA, Warzone) "
f"— don't question the game; use the profile below to understand what happens.")
else:
lines.append(f"Game from the platform category: {game or '(unknown)'}")
if screen_game and screen_game.lower() not in (game or "").lower():
lines.append(f"Game the AI saw on screen recently: {screen_game} (check the frames; the category may be wrong)")
if profile:
lines.append(f"Game profile: {profile.get('summary', '')}")
for key, label in (("clip_worthy", "Clip-worthy in this game"), ("avoid", "Not clip-worthy"),
("mechanics", "Mechanics/activities (terms for the moment hashtags)"),
("jargon", "Slang/terms"), ("news", "News")):
if profile.get(key):
lines.append(f"{label}: " + "; ".join(profile[key][:10]))
lines.extend(mission_lines(profile, "en"))
if history:
lines.append(f"What happened earlier in the stream: {history}")
return "\n".join(lines)
SPEAKER_NOTE = {
"pt": "Quem fala vem marcado: [{s}] = o streamer; [other1], [other2]… = OUTRA pessoa (colega no Discord, outro "
"jogador no chat de voz do jogo). Nunca atribua a {s} o que outra pessoa disse.",
"en": "Each line is tagged with who speaks: [{s}] = the streamer; [other1], [other2]… = SOMEONE ELSE (teammate on "
"Discord, another player on in-game voice chat). Never attribute to {s} what someone else said.",
}
def _transcript(words: list[Word], lo: float, hi: float, lang: str = "pt", streamer: str = "") -> str:
"""Transcrição com tempo para os prompts. Com fala de outra pessoa no trecho (doc/clipador/FALANTES.md), cada
linha diz quem fala ([Tfue] / [other1]) e nunca mistura falantes; sem outra pessoa, sai igual a antes."""
inside = sorted((w for w in words if lo <= w.start <= hi), key=lambda w: w.start)
tagged = any(w.speaker and w.speaker != "streamer" for w in inside)
me = (streamer or "streamer").replace("[", "(").replace("]", ")")
lines: list[str] = []
current: list[str] = []
current_t: float | None = None
current_sp = ""
def flush() -> None:
tag = f" [{me if current_sp == 'streamer' else current_sp}]" if tagged else ""
lines.append(f"[{current_t:.0f}s]{tag} {' '.join(current)}")
for word in inside:
sp = word.speaker or "streamer"
if current_t is None or word.start - current_t > 4 or len(current) >= 14 or (tagged and sp != current_sp):
if current:
flush()
current, current_t, current_sp = [], word.start, sp
current.append(word.word)
if current:
flush()
if lines and tagged:
lines.insert(0, SPEAKER_NOTE["en" if lang == "en" else "pt"].format(s=me))
return "\n".join(lines) or LABELS[lang]["no_speech"]
def _chat_block(chat: list[ChatMessage], lo: float, hi: float, focus: float | None, bucket_s: int = 5,
lang: str = "pt") -> str:
L = LABELS[lang]
buckets: dict[int, int] = {}
emotes: dict[str, int] = {}
sample: list[str] = []
for message in chat:
if lo <= message.t <= hi:
b = int(message.t // bucket_s * bucket_s)
buckets[b] = buckets.get(b, 0) + 1
for e in set(message.emotes):
emotes[e] = emotes.get(e, 0) + 1
near = focus is None or focus - 10 <= message.t <= focus + 8
if near and len(sample) < 60:
sample.append(f"[{message.t:.0f}s] {message.text[:80]}")
rate = ", ".join(f"{t}s:{n}" for t, n in sorted(buckets.items())) or L["no_chat"]
top = ", ".join(f"{e}×{n}" for e, n in sorted(emotes.items(), key=lambda kv: -kv[1])[:12]) or L["none"]
return (f"{L['chat_per']} {bucket_s} s: {rate}\n{L['top_emotes']}: {top}\n"
f"{L['chat_sample']}:\n" + ("\n".join(sample) or L["no_chat_p"]))
def _frames_block(frames: list[tuple[float, Path]], lang: str = "pt") -> str:
if not frames:
return LABELS[lang]["frames_none"]
return LABELS[lang]["frames"] + ": " + ", ".join(f"#{i + 1} = {t:.0f}s" for i, (t, _) in enumerate(frames))
def build_prompt(streamer: str, platform: str, start_s: float, end_s: float, peak_s: float,
words: list[Word], chat: list[ChatMessage], heuristic: dict, live_title: str = "", *,
context: str = "", frames: list[tuple[float, Path]] | None = None,
backtrack_s: float = DEFAULT_BACKTRACK_S, min_s: float = DEFAULT_MIN_S, max_s: float = DEFAULT_MAX_S,
face: str = "", lang: str = "pt") -> str:
"""Prompt do juiz. Janela = candidato com `backtrack_s` para trás (a ação vem antes do comentário).
`face`: resumo do rosto do streamer na janela (face.FaceService.summary); vazio = sem câmera/rastreio."""
lo, hi = max(0.0, start_s - backtrack_s), end_s + CONTEXT_AFTER_S
L, to = LABELS[lang], ("to" if lang == "en" else "a")
return (
f"{L['channel']}: {streamer} ({platform})\n"
+ (context or f"{L['live_title']}: {live_title or '(' + L['unknown'] + ')'}") + "\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(heuristic, ensure_ascii=False)}\n"
+ (f"{L['face']}: {face}\n" if face else "")
+ f"{_frames_block(frames or [], lang)}\n\n"
f"{L['transcript']}:\n{_transcript(words, lo, hi, lang, streamer)}\n\n"
f"{_chat_block(chat, lo, hi, peak_s, lang=lang)}"
)
def build_scan_prompt(streamer: str, platform: str, lo: float, hi: float, back_lo: float, words: list[Word],
chat: list[ChatMessage], context: str, frames: list[tuple[float, Path]],
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"{_frames_block(frames, lang)}\n\n"
f"{L['transcript']}:\n{_transcript(words, back_lo, hi, lang, streamer)}\n\n"
f"{_chat_block(chat, back_lo, hi, None, bucket_s=10, lang=lang)}"
)
def _clean(data: dict, start_s: float, end_s: float, model: str, lo: float | None = None, hi: float | None = None,
min_s: float = DEFAULT_MIN_S, max_s: float = DEFAULT_MAX_S) -> Verdict:
# `hashtags` é opcional na leitura: resposta sem ele (modelo antigo/cache) segue com as tags do canal e do jogo.
missing = [k for k in VERDICT_SCHEMA["required"] if k not in data and k != "hashtags"]
if missing:
raise JudgeError(f"resposta sem os campos {missing}")
lo = max(0.0, start_s - DEFAULT_BACKTRACK_S) if lo is None else lo
hi = end_s + CONTEXT_AFTER_S if hi is None else hi
# Mínimo de verdade (pedido do dono, 17/11/2026): se o fim bate em `hi`, o início recua (antes ficava curto).
new_start, new_end = fit_window(float(data["start_s"]), float(data["end_s"]), lo, hi, min_s, max_s, keep="start")
if new_end - new_start < min(10.0, min_s): # resposta incoerente: fica com o candidato da heurística
new_start, new_end = start_s, end_s
return Verdict(
keep=bool(data["keep"]), score=max(0.0, min(10.0, float(data["score"]))),
start_s=round(new_start, 2), end_s=round(new_end, 2),
title=str(data["title"]).strip()[:100], caption=str(data["caption"]).strip()[:600],
reason=str(data["reason"]).strip()[:300], model=model,
hashtags=tuple(str(t).strip()[:40] for t in (data.get("hashtags") or [])[:6] if str(t).strip()),
pt={k: str(v).strip()[:600] for k, v in (data.get("pt") or {}).items() if k in ("title", "caption", "reason") and v},
)
# ---------------------------------------------------------------- executáveis das CLIs
def find_codex() -> list[str] | None:
"""Comando do Codex. No Windows o npm instala `codex.cmd` (lote não roda sem shell e escapa mal argumentos):
como no painel (agents.ts), rodamos o `codex.js` do pacote direto pelo Node."""
env = os.environ.get("CODEX_BIN")
if env:
return [shutil.which("node") or "node", env] if env.endswith(".js") else [env]
exe = shutil.which("codex.exe") if sys.platform == "win32" else shutil.which("codex")
if exe:
return [exe]
cmd = shutil.which("codex.cmd") or shutil.which("codex")
node = shutil.which("node")
if cmd and node:
js = Path(cmd).parent / "node_modules" / "@openai" / "codex" / "bin" / "codex.js"
if js.is_file():
return [node, str(js)]
return None
def find_claude() -> list[str] | None:
env = os.environ.get("CLAUDE_BIN")
if env:
return [env]
exe = shutil.which("claude.exe") if sys.platform == "win32" else shutil.which("claude")
return [exe] if exe else None
def find_gemini() -> list[str] | None:
"""Comando do Gemini CLI. No Windows o npm instala `gemini.cmd` (mesmo problema do `codex.cmd`): rodamos o
`bundle/gemini.js` do pacote direto pelo Node. `GEMINI_BIN` força um caminho (.js roda pelo Node)."""
env = os.environ.get("GEMINI_BIN")
if env:
return [shutil.which("node") or "node", env] if env.endswith(".js") else [env]
if sys.platform != "win32":
exe = shutil.which("gemini")
return [exe] if exe else None
cmd = shutil.which("gemini.cmd") or shutil.which("gemini")
node = shutil.which("node")
if cmd and node:
js = Path(cmd).parent / "node_modules" / "@google" / "gemini-cli" / "bundle" / "gemini.js"
if js.is_file():
return [node, str(js)]
exe = shutil.which("gemini.exe")
return [exe] if exe else None
def find_cli(provider: str) -> list[str] | None:
"""Comando da CLI do provedor (None = não instalada). Resolve na hora (os testes trocam as funções)."""
finder = {"codex": find_codex, "claude": find_claude, "gemini": find_gemini}.get(provider)
return finder() if finder else None
PROVIDER_NAMES = {"codex": "Codex", "claude": "Claude", "gemini": "Gemini"}
def codex_models(cache: Path | None = None) -> list[dict]:
"""Modelos que o Codex lista para esta conta (cache que a própria CLI mantém)."""
cache = cache or Path.home() / ".codex" / "models_cache.json"
try:
data = json.loads(cache.read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError):
return [{"id": DEFAULT_MODELS["codex"], "label": DEFAULT_MODELS["codex"]}]
out = []
for m in data.get("models", []):
if isinstance(m, dict) and m.get("slug") and m.get("visibility", "list") == "list":
out.append({"id": m["slug"], "label": m.get("display_name") or m["slug"], "description": m.get("description", "")})
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, 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()
self._clock = clock
# Pausas da reserva, em memória (cada processo tem as suas): provedor → (até, motivo).
self._pauses: dict[str, tuple[float, str]] = {}
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
# ---------- 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)}")
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.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, skip: dict[str, str | None] | None = None) -> dict:
"""Papéis para o painel: a configuração + o modelo efetivo 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"], skip) 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:
return self.provider in AI_ENABLED
def command(self) -> list[str] | None:
return find_cli(self.provider) if self.enabled else None
def responder(self) -> str:
""""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)."""
now = self._clock()
with self._pause_lock:
self._pauses = {p: v for p, v in self._pauses.items() if v[0] > now}
return dict(self._pauses)
def pause(self, provider: str, reason: str, minutes: float | None = None) -> None:
if minutes is None:
minutes = float(self.ai.settings()["fallback"]["cooldownMin"])
if minutes <= 0:
return
with self._pause_lock:
self._pauses[provider] = (self._clock() + minutes * 60, reason[:200])
def _skip_reason(self, provider: str, settings: dict) -> str | None:
"""Por que o provedor não entra na cadeia (None = pronto). Não olha a pausa."""
conf = settings["providers"].get(provider) or {}
if not conf.get("enabled"):
return "desligada em Configurações → IA"
if not find_cli(provider):
return "CLI não encontrada"
if conf.get("authMode") == "apiKey" and not self.ai.has_key(provider):
return "modo chave de API sem chave no cofre"
return None
def fallback_chain(self, primary: str | None = None, skip: dict[str, str | None] | 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).
`skip` = `_skip_reason` já calculado por provedor (o `describe` monta a cadeia de cada papel de uma vez)."""
if not self.enabled:
return []
primary = primary if primary in AI_ENABLED else self.provider
settings = self.ai.settings()
candidates = [primary]
if settings["fallback"]["enabled"]:
candidates += [p for p in settings["order"] if p != primary and p in AI_ENABLED]
ready = [p for p in candidates
if (skip[p] if skip is not None and p in skip else self._skip_reason(p, settings)) is None]
if not settings["fallback"]["enabled"]:
return ready
paused = self.pauses()
# Perto do limite de uso (data/ai/usage.json, do painel): vai para depois das livres, antes das em pausa.
limited = {p for p in ready if p not in paused and self.ai.over_limit(p)}
active = [p for p in ready if p not in paused and p not in limited]
return (active + [p for p in ready if p in limited]) or ready
def describe(self) -> dict:
cmd = self.command() if self.enabled else None
settings = self.ai.settings()
# Uma checagem por provedor (CLI no PATH, ligada, chave) para todas as cadeias: o painel lê isto a cada poucos s.
skip = {p: self._skip_reason(p, settings) for p in AI_ENABLED}
primary_skip = skip.get(self.provider) if self.enabled else None
return {"provider": self.provider, "model": 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,
"authMode": settings["providers"].get(self.provider, {}).get("authMode") if self.enabled else None,
"fallback": {"enabled": settings["fallback"]["enabled"],
"cooldownMin": settings["fallback"]["cooldownMin"],
"chain": self.fallback_chain(skip=skip)},
"pauses": [{"provider": p, "until": datetime.fromtimestamp(until, timezone.utc).isoformat(timespec="seconds"),
"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(skip),
"providers": {p: {"ready": skip[p] is None, "reason": skip[p],
"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:
"""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(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"])))
return data
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(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, [], 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)
return out
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(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
def research_game(self, name: str, live_title: str = "", notes: list[str] | None = None) -> dict:
prompt = f"Stream category / game: {name}\nStream title (extra hint): {live_title or '(none)'}\n"
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,
purpose="research")
def refine_game(self, name: str, profile: dict, instruction: str, search: bool = True, section: str = "",
history: list[dict] | None = None) -> dict:
"""Aplica um pedido do usuário ao perfil do jogo (acrescentar/corrigir/tirar) e devolve o perfil inteiro
mais `reply` (o que a IA fez, em 1–2 frases). `section` = campo em foco; `history` = conversa anterior."""
prompt = f"Game: {name}\nCURRENT profile:\n{json.dumps(profile, ensure_ascii=False, indent=1)}\n\n"
if section in PROFILE_SECTIONS:
prompt += f"SECTION in focus: {section}\n"
if history:
prompt += "Conversation so far:\n" + "\n".join(
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, 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, purpose="translate")
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,
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, 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)
conf = self.roles.get(role) or self.roles["editor"]
primary = conf["provider"]
chain = self.fallback_chain(primary)
if not chain:
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.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, 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.
raise JudgeError(" · ".join(attempts) if len(attempts) > 1 else text, unavailable=False) from exc
if fallback_on:
self.pause(provider, text)
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 != 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, effort: str = "") -> dict:
if provider == "codex":
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":
return self._gemini(system, prompt, schema, images, search, timeout, model)
raise JudgeError("IA desligada", unavailable=False)
def _run(self, args: list[str], stdin: str, cwd: Path, timeout: int, provider: str) -> subprocess.CompletedProcess:
# `env` por provedor: modo chave de API (só nesta chamada) ou sessão logada (doc/ia.md).
try:
result = subprocess.run(args, input=stdin.encode("utf-8"), capture_output=True, timeout=timeout, cwd=cwd,
creationflags=NO_WINDOW, env=self.ai.provider_env(provider))
except subprocess.TimeoutExpired as exc:
raise JudgeError(f"a CLI passou de {timeout} s (tempo esgotado)", unavailable=True) from exc
except OSError as exc:
raise JudgeError(f"não consegui rodar a CLI: {exc}", unavailable=True) from exc
if result.returncode != 0:
err = result.stderr.decode("utf-8", errors="replace").strip()
out = result.stdout.decode("utf-8", errors="replace").strip()
tail = (err or out).splitlines()[-2:]
message = f"a CLI saiu com código {result.returncode}: {' | '.join(tail)[:300]}"
# Classifica pelo texto inteiro (o motivo pode estar antes das 2 últimas linhas, ou só no stdout).
raise JudgeError(message, unavailable=is_availability_error(err + "\n" + out))
return result
def _codex(self, system: str, prompt: str, schema: dict, images: list[Path], search: bool, timeout: int,
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)
self.workdir.mkdir(parents=True, exist_ok=True)
with tempfile.TemporaryDirectory(dir=self.workdir) as tmp:
schema_file, out = Path(tmp) / "schema.json", Path(tmp) / "answer.json"
schema_file.write_text(json.dumps(schema), encoding="utf-8")
image_args = [arg for img in images for arg in ("-i", str(Path(img).resolve()))]
lean = codex_lean_overrides(search)
if search:
stdin = system + "\n\n---\n\n" + prompt
else:
# Sem ferramentas, o texto do juiz faz o papel das instruções de base do Codex (como o
# --system-prompt do Claude). String literal do TOML ('...'): o caminho do Windows não é escapado.
instructions = Path(tmp) / "instructions.md"
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", "--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:
raise JudgeError("o Codex não devolveu o JSON pedido", unavailable=False) from exc
def _claude(self, system: str, prompt: str, schema: dict, images: list[Path], search: bool, timeout: int,
model: str) -> dict:
cmd = find_claude()
if not cmd:
raise JudgeError("Claude Code CLI não encontrado", unavailable=True)
self.workdir.mkdir(parents=True, exist_ok=True)
tools = (["Read"] if images else []) + (["WebSearch", "WebFetch"] if search else [])
extra: list[str] = []
if images:
# O Claude vê imagem lendo o arquivo (ferramenta Read): liberamos só a pasta das imagens.
for folder in sorted({str(Path(i).resolve().parent) for i in images}):
extra += ["--add-dir", folder]
prompt += "\n\nImagens (leia cada uma com a ferramenta Read, na ordem):\n" + "\n".join(
str(Path(i).resolve()) for i in images)
args = [*cmd, "-p", "--model", model, "--output-format", "json", "--json-schema", json.dumps(schema),
"--tools", ",".join(tools), *(["--allowedTools", ",".join(tools)] if tools else []), *extra,
# --setting-sources: sem plugins e hooks do usuário (medido: 3,7 → 2,6 mil tokens fixos, 5,5 → 2,8 s).
"--no-session-persistence", "--strict-mcp-config", "--setting-sources", "project,local",
"--system-prompt", system]
result = self._run(args, prompt, self.workdir, timeout, "claude")
try:
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]}")
data = envelope.get("structured_output")
if not isinstance(data, dict):
try:
data = json.loads(envelope.get("result") or "")
except json.JSONDecodeError as exc:
raise JudgeError("o Claude não devolveu o JSON pedido", unavailable=False) from exc
return data
def _gemini(self, system: str, prompt: str, schema: dict, images: list[Path], search: bool, timeout: int,
model: str) -> dict:
"""Gemini CLI headless (`-o json` → `{"response": "<texto>", "stats": …}`). Não há `--output-schema`: o
schema vai no texto e o JSON é extraído da resposta. `--approval-mode plan` = só leitura (a busca
google_web_search continua liberada). O corpo grande vai pela entrada padrão (o Gemini junta o `-p` ao
stdin), para não estourar o limite de linha de comando do Windows; no `-p` só a instrução curta e os
`@arquivo` das imagens.
Pasta de trabalho FORA do repositório (temp do sistema): o `@arquivo` respeita o .gitignore e `data/` é
ignorado no CenaForge; fora do repo o Gemini também não carrega GEMINI.md do projeto (menos tokens fixos).
As imagens são copiadas para lá com nomes curtos e referenciadas por caminho relativo."""
cmd = find_gemini()
if not cmd:
raise JudgeError("Gemini CLI não encontrado (npm install -g @google/gemini-cli; chave em Configurações → IA)",
unavailable=True)
with tempfile.TemporaryDirectory(prefix="cenaforge-gemini-") as tmp:
refs: list[str] = []
for i, img in enumerate(images):
src = Path(img)
name = f"frame-{i + 1:02d}{src.suffix.lower() or '.jpg'}"
try:
shutil.copyfile(src, Path(tmp) / name)
except OSError as exc:
raise JudgeError(f"não consegui preparar a imagem {src.name}: {exc}", unavailable=False) from exc
refs.append(f"@{name}")
stdin = (system + "\n\n---\n\n" + prompt
+ "\n\n---\n\nResponda SÓ com um objeto JSON válido (sem texto antes ou depois, sem cercas ```), "
"que siga exatamente este JSON Schema:\n" + json.dumps(schema, ensure_ascii=False))
short = ("Siga as instruções e os dados recebidos acima e responda só com o JSON pedido."
+ (" Use a busca na web (google_web_search) para confirmar os fatos." if search else
" Não use ferramentas."))
if refs:
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")
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:
"""Envelope do `gemini -o json` → objeto JSON da resposta. Erro no envelope é classificado pelo texto (cota,
chave…); resposta sem JSON é erro de conteúdo."""
envelope = extract_json_object(stdout, fences=False)
if envelope is None:
raise JudgeError("o Gemini não devolveu JSON", unavailable=False)
error = envelope.get("error")
if error:
message = error.get("message") if isinstance(error, dict) else str(error)
raise JudgeError(f"o Gemini terminou com erro: {str(message or error)[:200]}")
response = envelope.get("response")
if not isinstance(response, str):
raise JudgeError("o Gemini não devolveu a resposta", unavailable=False)
data = extract_json_object(response)
if data is None:
raise JudgeError("o Gemini não devolveu o JSON pedido", unavailable=False)
return data
def analysis_block(analysis: dict, lang: str = "pt") -> str:
"""Análise do 1º juiz no formato que o editor lê (sem o bloco `pt`, que é só para o painel)."""
data = {k: v for k, v in analysis.items() if k != "pt"}
return LABELS[lang]["analysis"] + ":\n" + json.dumps(data, ensure_ascii=False, indent=1)