Files
CenaForge/clipper/app/judge.py
T
MateuusandClaude Opus 5.5 0567c7454a Clipador: subpáginas, jogos, idioma por canal e juiz com Gemini e IA reserva
- Clipador em subpáginas (Cortes, Sessões, Fontes, Jogos, Ajustes) com moldura comum, lista + diálogo
  dos cortes e submenu na barra lateral.
- Perfis de jogo (o que a IA sabe de cada jogo), parar pausa o monitor e idioma por fonte e por canal
  de publicação (migração v9: accounts.language).
- Juiz: Gemini CLI como terceiro provedor e IA reserva por chamada — se a IA escolhida cair por cota,
  login, chave ou rede, a próxima da ordem de Configurações → IA responde (com pausa da que caiu).
  Lê data/ai/settings.json e o cofre data/ai/vault.bin (DPAPI) escritos pelo painel; contrato em doc/ia.md.

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

980 lines
56 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 dataclasses import dataclass
from datetime import datetime, timezone
from pathlib import Path
from . import layout
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."""
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"},
},
"required": ["situation", "what_happened", "screen", "speech", "chat_meaning", "confidence",
"action_start_s", "reaction_end_s", "hook"],
"additionalProperties": False,
}
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.
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"},
"has_webcam": {"type": "boolean"},
"summary": {"type": "string"},
"moments": {"type": "array", "items": _MOMENT},
},
"required": ["screen_game", "has_webcam", "summary", "moments"],
"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"); has_webcam: há câmera do streamer no quadro?
- summary: 1 frase do que está acontecendo na janela (vira memória para as próximas janelas).
- title/caption/reason como um editor faria (título ≤ 70 caracteres, verdadeiro; hashtags só do que há aqui).
Não use ferramentas além do que foi entregue. Responda só com o JSON pedido."""
# 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"}
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, ...] = ()
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
# ---------------------------------------------------------------- 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:
return ""
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) -> 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("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" (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)
lines.append("Missões da história: " + "; ".join(parts) + (f"; …e mais {extra}" if extra > 0 else ""))
if triggers or missions:
lines.append("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
def game_context(game: str, screen_game: str, profile: dict | None, live_title: str, history: str = "",
confirmed: bool = False) -> str:
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 _transcript(words: list[Word], lo: float, hi: float) -> str:
lines, current, current_t = [], [], None
for word in sorted((w for w in words if lo <= w.start <= hi), key=lambda w: w.start):
if current_t is None or word.start - current_t > 4 or len(current) >= 14:
if current:
lines.append(f"[{current_t:.0f}s] {' '.join(current)}")
current, current_t = [], word.start
current.append(word.word)
if current:
lines.append(f"[{current_t:.0f}s] {' '.join(current)}")
return "\n".join(lines) or "(sem fala transcrita)"
def _chat_block(chat: list[ChatMessage], lo: float, hi: float, focus: float | None, bucket_s: int = 5) -> str:
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 "sem chat"
top = ", ".join(f"{e}×{n}" for e, n in sorted(emotes.items(), key=lambda kv: -kv[1])[:12]) or "nenhum"
return (f"Mensagens do chat por {bucket_s} s: {rate}\nEmotes mais usados: {top}\n"
f"Amostra do chat:\n" + ("\n".join(sample) or "(sem chat)"))
def _frames_block(frames: list[tuple[float, Path]]) -> str:
if not frames:
return "Frames: (nenhum)"
return "Frames anexados, em ordem: " + ", ".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 = "") -> 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
return (
f"Canal: {streamer} ({platform})\n"
+ (context or f"Título da live: {live_title or '(desconhecido)'}") + "\n\n"
f"Janela disponível: {lo:.0f}s a {hi:.0f}s. Candidato da heurística: {start_s:.0f}s a {end_s:.0f}s; "
f"pico de reação em {peak_s:.0f}s. Duração do corte: {min_s:.0f} a {max_s:.0f} s.\n"
f"Sinais da heurística: {json.dumps(heuristic, ensure_ascii=False)}\n"
+ (f"Rosto do streamer (expressão medida na webcam, relativa ao normal dele): {face}\n" if face else "")
+ f"{_frames_block(frames or [])}\n\n"
f"Transcrição:\n{_transcript(words, lo, hi)}\n\n"
f"{_chat_block(chat, lo, hi, peak_s)}"
)
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) -> str:
done = "; ".join(f"{a:.0f}–{b:.0f}s ({t[:40]})" for a, b, t in existing) or "nenhum"
return (
f"Canal: {streamer} ({platform})\n{context}\n\n"
f"Janela nova: {lo:.0f}s a {hi:.0f}s (pode voltar até {back_lo:.0f}s para pegar o início de uma ação).\n"
f"Duração do corte: {min_s:.0f} a {max_s:.0f} s. Cortes já feitos aqui: {done}\n"
f"{_frames_block(frames)}\n\n"
f"Transcrição:\n{_transcript(words, back_lo, hi)}\n\n"
f"{_chat_block(chat, back_lo, hi, None, bucket_s=10)}"
)
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()),
)
# ---------------------------------------------------------------- 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"]}]
# ---------------------------------------------------------------- IA
class Judge:
def __init__(self, provider: str, model: str, workdir: Path, analyst_model: str = "",
ai: AiConfig | None = None, clock=time.time):
self.provider = provider if provider in PROVIDERS else "codex"
self.model = model or DEFAULT_MODELS.get(self.provider, "")
# Modelo do ANALISTA (1º juiz, vê os frames). Vazio = o mesmo do editor.
self.analyst_model = analyst_model
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()
def configure(self, provider: str, model: str, analyst_model: str | None = None) -> None:
if provider not in PROVIDERS:
raise JudgeError(f"provedor precisa ser um de {', '.join(PROVIDERS)}")
self.provider = provider
self.model = model.strip() or DEFAULT_MODELS.get(provider, "")
if analyst_model is not None:
self.analyst_model = analyst_model.strip()
@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}"
# ---------- 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) -> list[str]:
"""Ordem em que `ask` tenta as IAs: a escolhida no juiz primeiro, depois a `order` do painel, só as ligadas,
com CLI e (no modo chave) com chave; as em pausa são puladas. Reserva desligada: só a escolhida.
Se TODAS as prontas estiverem em pausa, elas voltam como último recurso (melhor tentar do que parar)."""
if not self.enabled:
return []
settings = self.ai.settings()
candidates = [self.provider]
if settings["fallback"]["enabled"]:
candidates += [p for p in settings["order"] if p != self.provider and p in AI_ENABLED]
ready = [p for p in candidates if self._skip_reason(p, settings) is None]
paused = self.pauses() if settings["fallback"]["enabled"] else {}
active = [p for p in ready if p not in paused]
return active or ready
def describe(self) -> dict:
cmd = self.command() if self.enabled else None
settings = self.ai.settings()
primary_skip = self._skip_reason(self.provider, settings) if self.enabled else None
return {"provider": self.provider, "model": self.model if self.enabled else None,
"analystModel": (self.analyst_model or self.model) if self.enabled else None,
"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()},
"pauses": [{"provider": p, "until": datetime.fromtimestamp(until, timezone.utc).isoformat(timespec="seconds"),
"reason": reason} for p, (until, reason) in sorted(self.pauses().items())]}
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]) -> dict:
"""1º juiz (ANALISTA): o que aconteceu, cruzando tela + fala + chat. Não decide nem escreve título."""
data = self.ask(ANALYST_SYSTEM, prompt, ANALYSIS_SCHEMA, images, model=self.analyst_model or self.model)
missing = [k for k in ANALYSIS_SCHEMA["required"] if k not in data]
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) -> Verdict:
data = self.ask(JUDGE_SYSTEM, prompt, VERDICT_SCHEMA, images or [])
# 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 scan(self, prompt: str, images: list[Path]) -> dict:
data = self.ask(SCAN_SYSTEM, prompt, SCAN_SCHEMA, images)
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)
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)
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)
def detect_cam(self, images: list[Path]) -> dict:
return self.ask(CAM_SYSTEM, "Analise os frames anexados (mesma live, instantes diferentes).", CAM_SCHEMA, images)
# ---------- execução
def ask(self, system: str, prompt: str, schema: dict, images: list[Path], *, search: bool = False,
timeout: int = TIMEOUT_S, model: str | None = None) -> dict:
"""Chama a IA escolhida; se ela falhar por indisponibilidade, a próxima da cadeia de reserva (com o modelo
padrão DELA) e a que falhou fica em pausa. Erro de conteúdo (JSON inválido, campos faltando) não troca."""
if not self.enabled:
raise JudgeError("IA desligada", unavailable=False)
chain = self.fallback_chain()
if not chain:
why = self._skip_reason(self.provider, self.ai.settings()) or "nenhuma IA pronta"
raise JudgeError(f"{PROVIDER_NAMES[self.provider]} indisponível: {why} (veja Configurações → IA)",
unavailable=True)
fallback_on = self.ai.settings()["fallback"]["enabled"]
attempts: list[str] = []
for provider in chain:
use_model = (model or self.model) if provider == self.provider else DEFAULT_MODELS[provider]
try:
data = self._call(provider, system, prompt, schema, images, search, timeout, use_model)
except JudgeError as exc:
text = str(exc)
unavailable = exc.unavailable if exc.unavailable is not None else is_availability_error(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._local.responder = f"{provider}:{use_model}"
if provider != self.provider:
log.info("respondido pela reserva %s:%s", provider, use_model)
return data
raise JudgeError("nenhuma IA respondeu — " + " · ".join(attempts)[:900], unavailable=True)
def _call(self, provider: str, system: str, prompt: str, schema: dict, images: list[Path], search: bool,
timeout: int, model: str) -> dict:
if provider == "codex":
return self._codex(system, prompt, schema, images, search, timeout, model)
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) -> 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
# `--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.
args = [*cmd, *(["--search"] if search else []), "exec", "--skip-git-repo-check", "--ephemeral",
"--sandbox", "read-only", "-c", 'model_reasoning_effort="low"', *lean, "-m", model, *image_args,
"--output-schema", str(schema_file), "-o", str(out), "-C", tmp, "-"]
self._run(args, stdin, Path(tmp), timeout, "codex")
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
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")
return parse_gemini_output(result.stdout.decode("utf-8", errors="replace"))
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) -> str:
"""Análise do 1º juiz no formato que o editor lê."""
return "Análise do ANALISTA (cruzou tela, fala e chat):\n" + json.dumps(analysis, ensure_ascii=False, indent=1)