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>
This commit is contained in:
+410
-71
@@ -9,8 +9,13 @@ Quatro usos, todos com saída JSON validada por schema:
|
||||
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`) ou `claude`
|
||||
(`claude -p --json-schema`; imagens pela ferramenta Read, web por WebSearch/WebFetch).
|
||||
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
|
||||
@@ -23,21 +28,32 @@ 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", "off")
|
||||
DEFAULT_MODELS = {"codex": "gpt-6-luna", "claude": "haiku"}
|
||||
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"])
|
||||
@@ -172,10 +188,22 @@ SCAN_SCHEMA = {
|
||||
"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"}},
|
||||
@@ -185,8 +213,11 @@ PROFILE_SCHEMA = {
|
||||
"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", "summary", "genre", "mechanics", "clip_worthy", "avoid", "jargon", "news", "hashtags", "sources"],
|
||||
"required": ["name", "aliases", "summary", "genre", "mechanics", "clip_worthy", "avoid", "jargon", "news", "hashtags",
|
||||
"sources", "missions", "end_triggers"],
|
||||
"additionalProperties": False,
|
||||
}
|
||||
CAM_SCHEMA = {
|
||||
@@ -242,37 +273,57 @@ moments=[] (é o normal na maior parte do tempo — não force). Não repita um
|
||||
- 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."""
|
||||
|
||||
PROFILE_SYSTEM = """Você pesquisa jogos para um editor de cortes de live em português do Brasil. Use a busca na
|
||||
web para confirmar o que é o jogo (nome da categoria da Twitch pode ser abreviado ou ambíguo). Seja factual e
|
||||
cite as fontes (URLs). Responda só com o JSON pedido, textos em português do Brasil.
|
||||
- summary: 2–3 frases do que é o jogo e como se joga.
|
||||
- mechanics: até 8 mecânicas/sistemas que aparecem em gameplay.
|
||||
- clip_worthy: até 10 situações que rendem corte NESTE jogo (específicas, não genéricas).
|
||||
- avoid: até 6 situações que parecem momento mas não rendem (menus, farm, fila...).
|
||||
- jargon: até 12 termos/gírias que streamer e chat usam (para entender a transcrição).
|
||||
- news: até 6 novidades recentes com mês/ano (lançamento, atualização, polêmica) que tornam informação valiosa.
|
||||
- hashtags: 3 a 6 hashtags que o público usa para ESTE jogo no TikTok, Shorts e Reels (Brasil): o nome do jogo sem
|
||||
espaço, abreviação conhecida, o modo/gênero quando for buscado (ex.: GTARP). A primeira é a principal do jogo.
|
||||
Escreva com "#", sem inventar tag que ninguém usa.
|
||||
- sources: até 5 URLs usadas.
|
||||
Se vierem "pedidos do usuário", eles valem mais que a pesquisa: inclua o que ele pediu para acrescentar e respeite
|
||||
o que ele mandou tirar ou corrigir (ele conhece o canal e o jogo)."""
|
||||
# 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 = """Você mantém o perfil de um jogo usado por um editor de cortes de live em português do Brasil.
|
||||
Recebe o perfil ATUAL (JSON) e um PEDIDO do usuário (acrescentar, corrigir, tirar ou detalhar algo). Devolva o
|
||||
perfil COMPLETO atualizado, no mesmo formato:
|
||||
- mantenha tudo o que o pedido não mexe, com o mesmo texto;
|
||||
- aplique o pedido no campo certo (situação que rende corte → clip_worthy; o que não rende → avoid; gíria → jargon;
|
||||
mecânica → mechanics; novidade → news com mês/ano; hashtag do jogo → hashtags, com "#", a principal primeiro),
|
||||
escrito no estilo dos itens que já estão lá;
|
||||
- os limites de tamanho das listas podem crescer até 15 itens quando o usuário pedir para acrescentar;
|
||||
- se precisar confirmar um fato, pode usar a busca na web e acrescentar a URL em sources;
|
||||
- o usuário conhece o canal e o jogo: o que ele afirma vale, mesmo que você não ache na web;
|
||||
- se vier uma SEÇÃO em foco, o pedido é sobre ela: mexa nela (outras só se o pedido disser);
|
||||
- pode transformar um pedido genérico em itens concretos e úteis para o editor (ex.: "reação do streamer conta"
|
||||
vira "Streamer grita, xinga ou ri alto logo depois de uma morte ou fuga");
|
||||
- reply: 1–2 frases para o usuário dizendo o que você mudou (ou, se o pedido for uma pergunta, a resposta).
|
||||
Textos em português do Brasil. Responda só com o JSON pedido."""
|
||||
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",
|
||||
@@ -281,8 +332,8 @@ REFINE_SCHEMA = {
|
||||
"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"}
|
||||
"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:
|
||||
@@ -305,10 +356,98 @@ class Verdict:
|
||||
|
||||
|
||||
class JudgeError(RuntimeError):
|
||||
pass
|
||||
"""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)'}"]
|
||||
@@ -327,6 +466,7 @@ def game_context(game: str, screen_game: str, profile: dict | None, live_title:
|
||||
("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)
|
||||
@@ -453,6 +593,34 @@ def find_claude() -> list[str] | None:
|
||||
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"
|
||||
@@ -469,12 +637,21 @@ def codex_models(cache: Path | None = None) -> list[dict]:
|
||||
|
||||
# ---------------------------------------------------------------- IA
|
||||
class Judge:
|
||||
def __init__(self, provider: str, model: str, workdir: Path, analyst_model: str = ""):
|
||||
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:
|
||||
@@ -486,19 +663,75 @@ class Judge:
|
||||
|
||||
@property
|
||||
def enabled(self) -> bool:
|
||||
return self.provider in ("codex", "claude")
|
||||
return self.provider in AI_ENABLED
|
||||
|
||||
def command(self) -> list[str] | None:
|
||||
return find_codex() if self.provider == "codex" else find_claude() if self.provider == "claude" else 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}
|
||||
"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, "defaults": DEFAULT_MODELS}
|
||||
return {"codex": codex_models(), "claude": CLAUDE_MODELS, "gemini": GEMINI_MODELS, "defaults": DEFAULT_MODELS}
|
||||
|
||||
# ---------- usos
|
||||
def analyze(self, prompt: str, images: list[Path]) -> dict:
|
||||
@@ -514,7 +747,8 @@ class Judge:
|
||||
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 [])
|
||||
return _clean(data, start_s, end_s, f"{self.provider}:{self.model}", lo, hi, min_s, max_s)
|
||||
# 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)
|
||||
@@ -523,57 +757,105 @@ class Judge:
|
||||
return data
|
||||
|
||||
def research_game(self, name: str, live_title: str = "", notes: list[str] | None = None) -> dict:
|
||||
prompt = f"Categoria/jogo da live: {name}\nTítulo da live (pista extra): {live_title or '(nenhum)'}\n"
|
||||
prompt = f"Stream category / game: {name}\nStream title (extra hint): {live_title or '(none)'}\n"
|
||||
if notes:
|
||||
prompt += "Pedidos do usuário (respeite):\n" + "\n".join(f"- {n}" for n in notes) + "\n"
|
||||
prompt += "Pesquise e devolva o perfil do jogo."
|
||||
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"Jogo: {name}\nPerfil ATUAL:\n{json.dumps(profile, ensure_ascii=False, indent=1)}\n\n"
|
||||
prompt = f"Game: {name}\nCURRENT profile:\n{json.dumps(profile, ensure_ascii=False, indent=1)}\n\n"
|
||||
if section in PROFILE_SECTIONS:
|
||||
prompt += f"SEÇÃO em foco: {section} ({PROFILE_SECTIONS[section]})\n"
|
||||
prompt += f"SECTION in focus: {section}\n"
|
||||
if history:
|
||||
prompt += "Conversa até aqui:\n" + "\n".join(
|
||||
f"{'Usuário' if h.get('role') == 'user' else 'IA'}: {str(h.get('text', ''))[:400]}" for h in history[-8:]) + "\n"
|
||||
prompt += f"PEDIDO do usuário:\n{instruction}\n\nDevolva o perfil completo atualizado e o reply."
|
||||
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:
|
||||
model = model or self.model
|
||||
if self.provider == "codex":
|
||||
return self._codex(system, prompt, schema, images, search, timeout, model)
|
||||
if self.provider == "claude":
|
||||
return self._claude(system, prompt, schema, images, search, timeout, model)
|
||||
raise JudgeError("IA desligada")
|
||||
"""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 _run(self, args: list[str], stdin: str, cwd: Path, timeout: int) -> subprocess.CompletedProcess:
|
||||
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)
|
||||
creationflags=NO_WINDOW, env=self.ai.provider_env(provider))
|
||||
except subprocess.TimeoutExpired as exc:
|
||||
raise JudgeError(f"a CLI passou de {timeout} s") from 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}") from exc
|
||||
raise JudgeError(f"não consegui rodar a CLI: {exc}", unavailable=True) from exc
|
||||
if result.returncode != 0:
|
||||
tail = result.stderr.decode("utf-8", errors="replace").strip().splitlines()[-2:]
|
||||
raise JudgeError(f"a CLI saiu com código {result.returncode}: {' | '.join(tail)[:300]}")
|
||||
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)")
|
||||
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"
|
||||
@@ -594,17 +876,17 @@ class Judge:
|
||||
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)
|
||||
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") from 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")
|
||||
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] = []
|
||||
@@ -619,21 +901,78 @@ class Judge:
|
||||
# --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)
|
||||
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") from 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") from 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ê."""
|
||||
|
||||
Reference in New Issue
Block a user