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:
@@ -0,0 +1,232 @@
|
||||
"""Configuração das IAs (Claude, Codex, Gemini) compartilhada com o painel — contrato em `doc/ia.md`.
|
||||
|
||||
O painel (Configurações → IA) escreve dois arquivos em `data/ai/`; o Clipador só LÊ:
|
||||
- `settings.json` (sem segredo): quais IAs estão ligadas, modo de login (`oauth`/`apiKey`), ordem da reserva e
|
||||
pausa depois de uma falha de indisponibilidade. Relido quando o `mtime` muda; ausente/inválido = padrão.
|
||||
- `vault.bin`: as chaves de API, JSON cifrado com a DPAPI do Windows (usuário atual, entropia própria).
|
||||
|
||||
Daqui sai o ambiente (`env`) de cada chamada de CLI: no modo chave, a variável da chave só vale para a chamada;
|
||||
no modo login, a variável é removida para a CLI usar a sessão já logada. O login global de cada CLI não muda.
|
||||
|
||||
Nos testes, a pasta e o cifrador são injetados (`AiConfig(folder, cipher=...)`); a DPAPI real só existe no Windows.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import copy
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import sys
|
||||
import threading
|
||||
from pathlib import Path
|
||||
from typing import Protocol
|
||||
|
||||
from .config import REPO_ROOT
|
||||
|
||||
log = logging.getLogger("cenaforge_clipper.ai_settings")
|
||||
|
||||
AI_PROVIDERS = ("claude", "codex", "gemini")
|
||||
# Pasta padrão dos arquivos do painel. Os testes trocam (conftest) para não ler o data/ai real.
|
||||
DEFAULT_AI_DIR = REPO_ROOT / "data" / "ai"
|
||||
AUTH_MODES = ("oauth", "apiKey")
|
||||
DEFAULT_COOLDOWN_MIN = 15.0
|
||||
DEFAULT_SETTINGS: dict = {
|
||||
"version": 1,
|
||||
"providers": {
|
||||
"claude": {"enabled": True, "authMode": "oauth"},
|
||||
"codex": {"enabled": True, "authMode": "oauth"},
|
||||
"gemini": {"enabled": False, "authMode": "apiKey"},
|
||||
},
|
||||
"order": ["claude", "codex", "gemini"],
|
||||
"fallback": {"enabled": True, "cooldownMin": DEFAULT_COOLDOWN_MIN},
|
||||
}
|
||||
# Variável de ambiente da chave de API de cada CLI (tabela "Ambiente de cada chamada" do doc/ia.md).
|
||||
API_KEY_ENV = {"claude": "ANTHROPIC_API_KEY", "codex": "CODEX_API_KEY", "gemini": "GEMINI_API_KEY"}
|
||||
GEMINI_OAUTH_ENV = "GOOGLE_GENAI_USE_GCA"
|
||||
|
||||
# Entropia do cofre de IA (a mesma que o painel usa ao cifrar). Não é senha: só separa este cofre dos outros.
|
||||
_VAULT_ENTROPY = b"CenaForge.AI.vault.v1"
|
||||
|
||||
|
||||
class AiVaultError(RuntimeError):
|
||||
"""O cofre de IA não abriu (outro usuário/máquina, corrompido, ou DPAPI indisponível)."""
|
||||
|
||||
|
||||
class Cipher(Protocol):
|
||||
def unprotect(self, data: bytes) -> bytes: ...
|
||||
|
||||
|
||||
class DpapiCipher:
|
||||
"""DPAPI via ctypes (crypt32.dll), só a decifragem — quem cifra é o painel. Mesmo padrão de
|
||||
`publisher/app/vault.py` (pacotes separados: o código é copiado, não importado)."""
|
||||
|
||||
CRYPTPROTECT_UI_FORBIDDEN = 0x01
|
||||
|
||||
def __init__(self, entropy: bytes = _VAULT_ENTROPY) -> None:
|
||||
if sys.platform != "win32":
|
||||
raise AiVaultError("O cofre de IA usa a DPAPI do Windows; este sistema não tem.")
|
||||
import ctypes
|
||||
from ctypes import wintypes
|
||||
|
||||
class DataBlob(ctypes.Structure):
|
||||
_fields_ = [("cbData", wintypes.DWORD), ("pbData", ctypes.POINTER(ctypes.c_char))]
|
||||
|
||||
self._entropy = entropy
|
||||
self._ctypes = ctypes
|
||||
self._blob = DataBlob
|
||||
self._crypt32 = ctypes.WinDLL("crypt32", use_last_error=True)
|
||||
self._kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
|
||||
self._kernel32.LocalFree.argtypes = [ctypes.c_void_p]
|
||||
self._kernel32.LocalFree.restype = ctypes.c_void_p
|
||||
fn = self._crypt32.CryptUnprotectData
|
||||
fn.argtypes = [ctypes.POINTER(DataBlob), ctypes.c_void_p, ctypes.POINTER(DataBlob), ctypes.c_void_p,
|
||||
ctypes.c_void_p, wintypes.DWORD, ctypes.POINTER(DataBlob)]
|
||||
fn.restype = wintypes.BOOL
|
||||
|
||||
def _to_blob(self, data: bytes):
|
||||
buffer = self._ctypes.create_string_buffer(data, len(data))
|
||||
blob = self._blob(len(data), self._ctypes.cast(buffer, self._ctypes.POINTER(self._ctypes.c_char)))
|
||||
return blob, buffer # o buffer precisa continuar vivo enquanto o blob for usado
|
||||
|
||||
def unprotect(self, data: bytes) -> bytes:
|
||||
ctypes = self._ctypes
|
||||
in_blob, _keep_in = self._to_blob(data)
|
||||
entropy, _keep_entropy = self._to_blob(self._entropy)
|
||||
out_blob = self._blob()
|
||||
ok = self._crypt32.CryptUnprotectData(ctypes.byref(in_blob), None, ctypes.byref(entropy), None, None,
|
||||
self.CRYPTPROTECT_UI_FORBIDDEN, ctypes.byref(out_blob))
|
||||
if not ok:
|
||||
raise AiVaultError(f"A DPAPI do Windows não conseguiu abrir o cofre de IA (erro {ctypes.get_last_error()}). "
|
||||
"O arquivo pode ser de outro usuário ou de outro computador.")
|
||||
try:
|
||||
return ctypes.string_at(out_blob.pbData, out_blob.cbData)
|
||||
finally:
|
||||
self._kernel32.LocalFree(out_blob.pbData)
|
||||
|
||||
|
||||
def normalize_settings(raw: object) -> dict:
|
||||
"""Valida o settings.json do painel campo a campo. O que faltar ou vier errado fica no padrão do doc."""
|
||||
settings = copy.deepcopy(DEFAULT_SETTINGS)
|
||||
if not isinstance(raw, dict):
|
||||
return settings
|
||||
providers = raw.get("providers")
|
||||
if isinstance(providers, dict):
|
||||
for name in AI_PROVIDERS:
|
||||
item = providers.get(name)
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
if isinstance(item.get("enabled"), bool):
|
||||
settings["providers"][name]["enabled"] = item["enabled"]
|
||||
if item.get("authMode") in AUTH_MODES:
|
||||
settings["providers"][name]["authMode"] = item["authMode"]
|
||||
order = raw.get("order")
|
||||
if isinstance(order, list):
|
||||
known = [p for p in dict.fromkeys(order) if p in AI_PROVIDERS]
|
||||
# Quem ficou de fora da lista vai para o fim, na ordem padrão (a lista sempre tem as três).
|
||||
settings["order"] = known + [p for p in AI_PROVIDERS if p not in known]
|
||||
fallback = raw.get("fallback")
|
||||
if isinstance(fallback, dict):
|
||||
if isinstance(fallback.get("enabled"), bool):
|
||||
settings["fallback"]["enabled"] = fallback["enabled"]
|
||||
cooldown = fallback.get("cooldownMin")
|
||||
if isinstance(cooldown, (int, float)) and not isinstance(cooldown, bool) and cooldown >= 0:
|
||||
settings["fallback"]["cooldownMin"] = float(cooldown)
|
||||
return settings
|
||||
|
||||
|
||||
def _mtime(path: Path) -> int | None:
|
||||
try:
|
||||
return path.stat().st_mtime_ns
|
||||
except OSError:
|
||||
return None
|
||||
|
||||
|
||||
class AiConfig:
|
||||
"""Leitura (com cache por mtime) do settings.json e do vault.bin do painel."""
|
||||
|
||||
def __init__(self, folder: Path | None = None, cipher: Cipher | None = None,
|
||||
environ: dict[str, str] | None = None):
|
||||
self.folder = Path(folder) if folder is not None else DEFAULT_AI_DIR
|
||||
self._cipher = cipher
|
||||
self._environ = environ # None = os.environ do momento da chamada
|
||||
self._lock = threading.RLock()
|
||||
self._settings_cache: tuple[int | None, dict] | None = None
|
||||
self._keys_cache: tuple[int | None, dict[str, str]] | None = None
|
||||
self.vault_error: str | None = None
|
||||
|
||||
@property
|
||||
def settings_path(self) -> Path:
|
||||
return self.folder / "settings.json"
|
||||
|
||||
@property
|
||||
def vault_path(self) -> Path:
|
||||
return self.folder / "vault.bin"
|
||||
|
||||
def settings(self) -> dict:
|
||||
"""Configuração atual (cópia). Relê o arquivo só quando o mtime muda."""
|
||||
with self._lock:
|
||||
stamp = _mtime(self.settings_path)
|
||||
if self._settings_cache is None or self._settings_cache[0] != stamp:
|
||||
raw: object = None
|
||||
if stamp is not None:
|
||||
try:
|
||||
raw = json.loads(self.settings_path.read_text(encoding="utf-8"))
|
||||
except (OSError, ValueError) as exc:
|
||||
log.warning("data/ai/settings.json inválido (%s); usando o padrão", exc)
|
||||
self._settings_cache = (stamp, normalize_settings(raw))
|
||||
return copy.deepcopy(self._settings_cache[1])
|
||||
|
||||
def provider(self, name: str) -> dict:
|
||||
return self.settings()["providers"].get(name, {"enabled": False, "authMode": "oauth"})
|
||||
|
||||
def api_keys(self) -> dict[str, str]:
|
||||
"""Chaves do cofre (só as que existem). Cofre ausente = {}; cofre que não abre = {} e `vault_error`."""
|
||||
with self._lock:
|
||||
stamp = _mtime(self.vault_path)
|
||||
if self._keys_cache is None or self._keys_cache[0] != stamp:
|
||||
self._keys_cache = (stamp, self._read_vault() if stamp is not None else {})
|
||||
if stamp is None:
|
||||
self.vault_error = None
|
||||
return dict(self._keys_cache[1])
|
||||
|
||||
def _read_vault(self) -> dict[str, str]:
|
||||
try:
|
||||
raw = self.vault_path.read_bytes()
|
||||
if not raw:
|
||||
self.vault_error = None
|
||||
return {}
|
||||
cipher = self._cipher or DpapiCipher()
|
||||
data = json.loads(cipher.unprotect(raw).decode("utf-8"))
|
||||
except Exception as exc: # noqa: BLE001 - cofre ilegível não derruba o juiz: segue sem chaves
|
||||
self.vault_error = str(exc)[:200] or "cofre de IA ilegível"
|
||||
log.warning("não abri data/ai/vault.bin: %s", self.vault_error)
|
||||
return {}
|
||||
self.vault_error = None
|
||||
if not isinstance(data, dict):
|
||||
return {}
|
||||
return {k: v.strip() for k, v in data.items() if k in AI_PROVIDERS and isinstance(v, str) and v.strip()}
|
||||
|
||||
def has_key(self, provider: str) -> bool:
|
||||
return bool(self.api_keys().get(provider))
|
||||
|
||||
def provider_env(self, provider: str) -> dict[str, str]:
|
||||
"""Ambiente da chamada da CLI de `provider`, conforme o modo de login (tabela do doc/ia.md)."""
|
||||
env = dict(os.environ if self._environ is None else self._environ)
|
||||
key_var = API_KEY_ENV.get(provider)
|
||||
if not key_var:
|
||||
return env
|
||||
mode = self.provider(provider).get("authMode", "oauth")
|
||||
if mode == "apiKey":
|
||||
key = self.api_keys().get(provider)
|
||||
if key:
|
||||
env[key_var] = key
|
||||
else:
|
||||
env.pop(key_var, None)
|
||||
if provider == "gemini":
|
||||
env.pop(GEMINI_OAUTH_ENV, None)
|
||||
else:
|
||||
env.pop(key_var, None)
|
||||
if provider == "gemini":
|
||||
env[GEMINI_OAUTH_ENV] = "true"
|
||||
return env
|
||||
@@ -119,8 +119,8 @@ class Settings:
|
||||
judge_model=env.get("CLIPPER_JUDGE_MODEL", ""),
|
||||
judge_min_score=num("CLIPPER_JUDGE_MIN_SCORE", 6, 0),
|
||||
)
|
||||
if settings.judge_provider not in ("codex", "claude", "off"):
|
||||
raise ConfigError("CLIPPER_JUDGE_PROVIDER precisa ser codex, claude ou off")
|
||||
if settings.judge_provider not in ("codex", "claude", "gemini", "off"):
|
||||
raise ConfigError("CLIPPER_JUDGE_PROVIDER precisa ser codex, claude, gemini ou off")
|
||||
if settings.encoder not in ("auto", "libx264", "h264_nvenc"):
|
||||
raise ConfigError("CLIPPER_ENCODER precisa ser auto, libx264 ou h264_nvenc")
|
||||
if overrides:
|
||||
|
||||
@@ -190,6 +190,23 @@ SCHEMA = [
|
||||
);
|
||||
CREATE INDEX deleted_clips_session ON deleted_clips (session_id);
|
||||
""",
|
||||
# v11: (a) parar uma sessão à mão pausa o monitor da fonte (`monitor_paused_at` + a sessão que motivou): o monitor
|
||||
# não abre sessão nova enquanto a pausa existir; religar (PATCH monitor=true, gravar pelo link ou retomar) limpa.
|
||||
# (b) idioma falado na live, por fonte e por sessão ('' = CLIPPER_LANGUAGE): transcrição e textos da IA.
|
||||
"""
|
||||
ALTER TABLE channels ADD COLUMN monitor_paused_at TEXT;
|
||||
ALTER TABLE channels ADD COLUMN monitor_paused_session INTEGER;
|
||||
ALTER TABLE channels ADD COLUMN language TEXT NOT NULL DEFAULT '';
|
||||
ALTER TABLE sessions ADD COLUMN language TEXT NOT NULL DEFAULT '';
|
||||
""",
|
||||
# v12: perfil do jogo em dois idiomas (doc/clipador/JOGOS.md). `profile_json` continua sendo o português (o que o
|
||||
# painel mostra); `profile_ai_json` é o inglês, que vai nos prompts; `translated_at` = quando uma versão foi gerada
|
||||
# da outra; `aliases_json` = outros nomes do jogo (categoria "Grand Theft Auto VI" e tela "GTA 6" → mesmo perfil).
|
||||
"""
|
||||
ALTER TABLE games ADD COLUMN profile_ai_json TEXT;
|
||||
ALTER TABLE games ADD COLUMN translated_at TEXT;
|
||||
ALTER TABLE games ADD COLUMN aliases_json TEXT NOT NULL DEFAULT '[]';
|
||||
""",
|
||||
]
|
||||
|
||||
|
||||
|
||||
+226
-40
@@ -23,7 +23,7 @@ from .db import loads, now
|
||||
from .emotes import EmoteCatalog, extract, learn_delta, message_bonus
|
||||
from .face import FaceError, FaceUnavailable
|
||||
from .hashtags import fold, to_tag
|
||||
from .judge import JudgeError, build_scan_prompt, game_context
|
||||
from .judge import JudgeError, build_scan_prompt, game_context, output_language_note
|
||||
from .scoring import fit_window
|
||||
from .sources import parse_source
|
||||
|
||||
@@ -52,31 +52,79 @@ def game_id(name: str) -> str:
|
||||
return re.sub(r"[^a-z0-9]+", "-", name.lower()).strip("-")[:60] or "desconhecido"
|
||||
|
||||
|
||||
PROFILE_LISTS = ("mechanics", "clip_worthy", "avoid", "jargon", "news", "hashtags", "sources")
|
||||
PROFILE_LISTS = ("mechanics", "clip_worthy", "avoid", "jargon", "news", "hashtags", "sources", "aliases", "end_triggers")
|
||||
# Teto de cada lista (o resto: 20). Missões ficam à parte (objetos, até 120).
|
||||
LIST_LIMITS = {"aliases": 10, "end_triggers": 12}
|
||||
MAX_MISSIONS = 120
|
||||
MAX_MISSION_TRIGGERS = 8
|
||||
|
||||
# Sementes: perfis prontos que vêm com o repositório (ex.: GTA VI). Importados na subida só se o jogo não existe.
|
||||
SEEDS_DIR = Path(__file__).resolve().parent / "seeds" / "games"
|
||||
|
||||
|
||||
def _clean_text_list(values, limit: int, item_chars: int = 300) -> list[str]:
|
||||
items, seen = [], set()
|
||||
for item in values or []:
|
||||
text = str(item or "").strip()[:item_chars]
|
||||
if text and text.lower() not in seen:
|
||||
seen.add(text.lower())
|
||||
items.append(text)
|
||||
return items[:limit]
|
||||
|
||||
|
||||
def clean_missions(values) -> list[dict]:
|
||||
"""Missões: nome obrigatório (sem repetir), capítulo, resumo e até 8 gatilhos de fim (até 200 caracteres cada)."""
|
||||
out, seen = [], set()
|
||||
for raw in values or []:
|
||||
if not isinstance(raw, dict):
|
||||
continue
|
||||
name = str(raw.get("name") or "").strip()[:160]
|
||||
if not name or name.lower() in seen:
|
||||
continue
|
||||
seen.add(name.lower())
|
||||
out.append({
|
||||
"name": name,
|
||||
"chapter": str(raw.get("chapter") or "").strip()[:120],
|
||||
"summary": str(raw.get("summary") or "").strip()[:500],
|
||||
"completion_triggers": _clean_text_list(raw.get("completion_triggers"), MAX_MISSION_TRIGGERS, 200),
|
||||
})
|
||||
if len(out) >= MAX_MISSIONS:
|
||||
break
|
||||
return out
|
||||
|
||||
|
||||
def clean_profile(raw: dict) -> dict:
|
||||
"""Normaliza um perfil de jogo (vindo da IA ou da edição à mão): textos aparados, listas sem vazios/duplicados.
|
||||
Hashtags viram tag de verdade ("rob run" → "#RobRun"; sem letra some), comparadas sem acento/maiúscula."""
|
||||
"""Normaliza um perfil de jogo (vindo da IA, da tradução ou da edição à mão): textos aparados, listas sem
|
||||
vazios/duplicados, missões validadas. Hashtags viram tag de verdade ("rob run" → "#RobRun"; sem letra some),
|
||||
comparadas sem acento/maiúscula."""
|
||||
raw = raw if isinstance(raw, dict) else {}
|
||||
out: dict = {k: str(raw.get(k) or "").strip()[:limit] for k, limit in (("name", 120), ("summary", 1500), ("genre", 120))}
|
||||
for key in PROFILE_LISTS:
|
||||
items, seen = [], set()
|
||||
for item in raw.get(key) or []:
|
||||
text = str(item or "").strip()[:300]
|
||||
if key == "hashtags":
|
||||
text = to_tag(text) or ""
|
||||
if key == "hashtags":
|
||||
items, seen = [], set()
|
||||
for item in raw.get(key) or []:
|
||||
text = to_tag(str(item or "").strip()[:300]) or ""
|
||||
if text and fold(text) not in seen:
|
||||
seen.add(fold(text))
|
||||
items.append(text)
|
||||
continue
|
||||
if text and text.lower() not in seen:
|
||||
seen.add(text.lower())
|
||||
items.append(text)
|
||||
out[key] = items[:20]
|
||||
out[key] = items[:20]
|
||||
else:
|
||||
out[key] = _clean_text_list(raw.get(key), LIST_LIMITS.get(key, 20))
|
||||
out["missions"] = clean_missions(raw.get("missions"))
|
||||
return out
|
||||
|
||||
|
||||
def alias_ids(*profiles: dict | None) -> list[str]:
|
||||
"""Ids normalizados dos outros nomes do jogo (das duas versões do perfil), sem repetir."""
|
||||
ids: list[str] = []
|
||||
for profile in profiles:
|
||||
for alias in (profile or {}).get("aliases") or []:
|
||||
gid = game_id(str(alias))
|
||||
if gid != "desconhecido" and gid not in ids:
|
||||
ids.append(gid)
|
||||
return ids
|
||||
|
||||
|
||||
class Intel:
|
||||
def __init__(self, engine: "Engine"):
|
||||
self.e = engine
|
||||
@@ -91,6 +139,37 @@ class Intel:
|
||||
for key in OPTION_DEFAULTS:
|
||||
if f"opt_{key}" in saved:
|
||||
self.opts[key] = json.loads(saved[f"opt_{key}"])
|
||||
self.import_seeds()
|
||||
|
||||
# ---------------------------------------------------------------- sementes de jogos
|
||||
def import_seeds(self, folder: Path | None = None) -> list[str]:
|
||||
"""Importa os perfis de `seeds/games/*.json` ({name, aliases, researchedAt, sources, profileAi, profile}) que
|
||||
ainda não existem no banco (por id ou alias). Nunca sobrescreve: o que você editou fica. Devolve os ids novos."""
|
||||
added: list[str] = []
|
||||
for path in sorted((folder or SEEDS_DIR).glob("*.json")):
|
||||
try:
|
||||
seed = json.loads(path.read_text(encoding="utf-8"))
|
||||
name = str(seed.get("name") or "").strip()
|
||||
if not name:
|
||||
continue
|
||||
ai = clean_profile({**(seed.get("profileAi") or {}), "name": name})
|
||||
pt = clean_profile({**(seed.get("profile") or seed.get("profileAi") or {}), "name": name})
|
||||
for profile in (ai, pt):
|
||||
profile["aliases"] = profile["aliases"] or list(seed.get("aliases") or [])
|
||||
profile["sources"] = profile["sources"] or list(seed.get("sources") or [])
|
||||
gid = game_id(name)
|
||||
if self.find_game(name) or any(self.find_game(a) for a in ai["aliases"]):
|
||||
continue
|
||||
self.e.db.run(
|
||||
"INSERT INTO games (id, name, status, profile_json, profile_ai_json, aliases_json, model, researched_at,"
|
||||
" translated_at) VALUES (?, ?, 'ready', ?, ?, ?, 'seed', ?, ?)",
|
||||
gid, name[:120], json.dumps(pt, ensure_ascii=False), json.dumps(ai, ensure_ascii=False),
|
||||
json.dumps(alias_ids(ai, pt)), seed.get("researchedAt") or now(), seed.get("researchedAt") or now())
|
||||
added.append(gid)
|
||||
log.info("jogo importado da semente %s: %s", path.name, name)
|
||||
except (OSError, ValueError) as exc:
|
||||
log.warning("semente de jogo %s inválida: %s", path.name, exc)
|
||||
return added
|
||||
|
||||
# ---------------------------------------------------------------- opções (painel)
|
||||
def set_options(self, values: dict) -> dict:
|
||||
@@ -202,7 +281,7 @@ class Intel:
|
||||
self.e.db.run("UPDATE sessions SET game = ?, game_source = ?, games_json = ? WHERE id = ?",
|
||||
name[:120], source, json.dumps(history[-20:], ensure_ascii=False), session_id)
|
||||
gid = game_id(name)
|
||||
if not self.e.db.get("SELECT 1 FROM games WHERE id = ?", gid):
|
||||
if not self.find_game(name):
|
||||
self.e.db.run("INSERT INTO games (id, name, status) VALUES (?, ?, 'pending')", gid, name[:120])
|
||||
|
||||
def research_pending(self) -> None:
|
||||
@@ -212,53 +291,142 @@ class Intel:
|
||||
self.research(game["id"])
|
||||
|
||||
def research(self, gid: str) -> dict:
|
||||
"""Pesquisa na web EM INGLÊS (missões e gatilhos inclusos) → versão da IA; depois traduz para português (a que
|
||||
o painel mostra). Tradução falhou: as duas ficam em inglês e `error` explica (o jogo continua utilizável)."""
|
||||
game = self.e.db.get("SELECT * FROM games WHERE id = ?", gid)
|
||||
if not game:
|
||||
raise JudgeError("jogo não encontrado")
|
||||
if not self.e.judge.enabled:
|
||||
raise JudgeError("IA desligada: ligue o Codex ou o Claude para pesquisar o jogo")
|
||||
raise JudgeError("IA desligada: escolha uma IA (Codex, Claude ou Gemini) para pesquisar o jogo")
|
||||
title = (self.e.db.get("SELECT title FROM sessions WHERE game = ? ORDER BY id DESC LIMIT 1", game["name"]) or {}).get("title", "")
|
||||
notes = [n.get("text", "") for n in loads(game.get("notes_json"), []) if n.get("text")]
|
||||
try:
|
||||
profile = self.e.judge.research_game(game["name"], title, notes)
|
||||
ai = clean_profile(self.e.judge.research_game(game["name"], title, notes))
|
||||
model = self.e.judge.responder() # quem DE FATO respondeu (pode ter sido a IA reserva)
|
||||
except (JudgeError, json.JSONDecodeError) as exc:
|
||||
self.e.db.run("UPDATE games SET status = 'error', error = ? WHERE id = ?", str(exc)[:300], gid)
|
||||
raise JudgeError(str(exc)) from exc
|
||||
self.e.db.run("UPDATE games SET status = 'ready', profile_json = ?, error = NULL, model = ?, researched_at = ? WHERE id = ?",
|
||||
json.dumps(profile, ensure_ascii=False), f"{self.e.judge.provider}:{self.e.judge.model}", now(), gid)
|
||||
return profile
|
||||
self.e.db.run("UPDATE games SET profile_ai_json = ?, model = ?, researched_at = ? WHERE id = ?",
|
||||
json.dumps(ai, ensure_ascii=False), model, now(), gid)
|
||||
pt, error = self._translated(ai, "pt-BR")
|
||||
self._store(gid, pt=pt, ai=ai, translated=error is None, error=error)
|
||||
return ai
|
||||
|
||||
def save_profile(self, gid: str, profile: dict) -> dict:
|
||||
"""Grava o perfil editado à mão no painel. Vale na hora para a IA (status 'ready')."""
|
||||
def _translated(self, profile: dict, target: str) -> tuple[dict, str | None]:
|
||||
"""(perfil traduzido, None) ou (o próprio perfil, motivo) se a IA está desligada ou a tradução falhou."""
|
||||
if not self.e.judge.enabled:
|
||||
return profile, "IA desligada: a outra versão do perfil não foi atualizada"
|
||||
try:
|
||||
out = clean_profile(self.e.judge.translate_game(profile, target))
|
||||
except (JudgeError, json.JSONDecodeError) as exc:
|
||||
return profile, f"tradução falhou: {exc}"[:300]
|
||||
# A tradução nunca mexe em nome, hashtags, fontes e outros nomes (a IA às vezes "traduz" o que não devia).
|
||||
for key in ("name", "hashtags", "sources", "aliases"):
|
||||
out[key] = profile.get(key) or out.get(key)
|
||||
if len(out.get("missions") or []) != len(profile.get("missions") or []):
|
||||
return profile, "tradução perdeu missões: a outra versão ficou igual à original"
|
||||
return out, None
|
||||
|
||||
def _store(self, gid: str, *, pt: dict | None = None, ai: dict | None = None, translated: bool = False,
|
||||
error: str | None = None, edited: bool = False, extra_sql: str = "", extra: tuple = ()) -> None:
|
||||
"""Grava as versões que vieram (None = não mexe), os outros nomes (união das duas) e o estado."""
|
||||
game = self.e.db.get("SELECT profile_json, profile_ai_json FROM games WHERE id = ?", gid) or {}
|
||||
pt_now = pt if pt is not None else loads(game.get("profile_json"), None)
|
||||
ai_now = ai if ai is not None else loads(game.get("profile_ai_json"), None)
|
||||
self.e.db.run(
|
||||
"UPDATE games SET status = 'ready', profile_json = ?, profile_ai_json = ?, aliases_json = ?, error = ?,"
|
||||
" translated_at = CASE WHEN ? THEN ? ELSE translated_at END,"
|
||||
" edited_at = CASE WHEN ? THEN ? ELSE edited_at END" + extra_sql + " WHERE id = ?",
|
||||
json.dumps(pt_now, ensure_ascii=False) if pt_now is not None else None,
|
||||
json.dumps(ai_now, ensure_ascii=False) if ai_now is not None else None,
|
||||
json.dumps(alias_ids(ai_now, pt_now)), error, int(translated), now(), int(edited), now(), *extra, gid)
|
||||
|
||||
def save_profile(self, gid: str, profile: dict, lang: str = "pt") -> dict:
|
||||
"""Grava a edição à mão na versão `lang` ("pt" = a que você lê; "en" = a da IA) e traduz para a outra. Com a IA
|
||||
desligada, grava só essa e a outra fica como estava (`translatedAt` não muda: o painel avisa que está velha)."""
|
||||
if not self.e.db.get("SELECT 1 FROM games WHERE id = ?", gid):
|
||||
raise JudgeError("jogo não encontrado")
|
||||
clean = clean_profile(profile)
|
||||
self.e.db.run("UPDATE games SET status = 'ready', profile_json = ?, error = NULL, edited_at = ? WHERE id = ?",
|
||||
json.dumps(clean, ensure_ascii=False), now(), gid)
|
||||
target = "en-US" if lang == "pt" else "pt-BR"
|
||||
other, error = self._translated(clean, target)
|
||||
translated = error is None
|
||||
if lang == "pt":
|
||||
self._store(gid, pt=clean, ai=other if translated else None, translated=translated, error=error, edited=True)
|
||||
else:
|
||||
self._store(gid, ai=clean, pt=other if translated else None, translated=translated, error=error, edited=True)
|
||||
return clean
|
||||
|
||||
def refine(self, gid: str, instruction: str, search: bool = True, section: str = "",
|
||||
history: list[dict] | None = None) -> tuple[dict, str]:
|
||||
"""Pede à IA para acrescentar/corrigir algo no perfil (opcionalmente numa seção). O pedido fica guardado e
|
||||
volta em toda pesquisa. Devolve (perfil, resposta curta da IA)."""
|
||||
def translate(self, gid: str) -> dict:
|
||||
"""Gera a versão da IA (inglês) a partir da portuguesa — para jogos de antes da v12."""
|
||||
game = self.e.db.get("SELECT * FROM games WHERE id = ?", gid)
|
||||
if not game:
|
||||
raise JudgeError("jogo não encontrado")
|
||||
if not self.e.judge.enabled:
|
||||
raise JudgeError("IA desligada: ligue o Codex ou o Claude para editar o perfil pela IA")
|
||||
current = loads(game["profile_json"], None) or clean_profile({"name": game["name"]})
|
||||
raise JudgeError("IA desligada: escolha uma IA (Codex, Claude ou Gemini) para traduzir o perfil")
|
||||
pt = loads(game["profile_json"], None)
|
||||
if not pt:
|
||||
raise JudgeError("o jogo ainda não tem perfil para traduzir")
|
||||
ai, error = self._translated(clean_profile(pt), "en-US")
|
||||
if error:
|
||||
raise JudgeError(error)
|
||||
self._store(gid, ai=ai, translated=True)
|
||||
return ai
|
||||
|
||||
def refine(self, gid: str, instruction: str, search: bool = True, section: str = "",
|
||||
history: list[dict] | None = None) -> tuple[dict, str]:
|
||||
"""Pede à IA para acrescentar/corrigir algo no perfil (opcionalmente numa seção). Aplica na versão em inglês
|
||||
(a da IA; jogo antigo sem ela: na portuguesa) e traduz para português. O pedido fica guardado e volta em toda
|
||||
pesquisa. Devolve (perfil em português, resposta curta da IA em português)."""
|
||||
game = self.e.db.get("SELECT * FROM games WHERE id = ?", gid)
|
||||
if not game:
|
||||
raise JudgeError("jogo não encontrado")
|
||||
if not self.e.judge.enabled:
|
||||
raise JudgeError("IA desligada: escolha uma IA (Codex, Claude ou Gemini) para editar o perfil pela IA")
|
||||
current = (loads(game.get("profile_ai_json"), None) or loads(game["profile_json"], None)
|
||||
or clean_profile({"name": game["name"]}))
|
||||
try:
|
||||
data = self.e.judge.refine_game(game["name"], current, instruction, search, section, history)
|
||||
model = self.e.judge.responder() # antes da tradução, que também passa pelo juiz
|
||||
except json.JSONDecodeError as exc:
|
||||
raise JudgeError(f"a IA devolveu um perfil inválido: {exc}") from exc
|
||||
reply = str(data.get("reply") or "").strip()[:600]
|
||||
profile = clean_profile(data)
|
||||
ai = clean_profile(data)
|
||||
pt, error = self._translated(ai, "pt-BR")
|
||||
notes = loads(game.get("notes_json"), [])
|
||||
notes.append({"text": instruction, "at": now(), **({"section": section} if section else {})})
|
||||
self.e.db.run("UPDATE games SET status = 'ready', profile_json = ?, error = NULL, notes_json = ?, edited_at = ?,"
|
||||
" model = ? WHERE id = ?", json.dumps(profile, ensure_ascii=False),
|
||||
json.dumps(notes[-30:], ensure_ascii=False), now(), f"{self.e.judge.provider}:{self.e.judge.model}", gid)
|
||||
return profile, reply
|
||||
self._store(gid, ai=ai, pt=pt, translated=error is None, error=error, edited=True,
|
||||
extra_sql=", notes_json = ?, model = ?",
|
||||
extra=(json.dumps(notes[-30:], ensure_ascii=False), model))
|
||||
return pt, reply
|
||||
|
||||
def add_game(self, name: str, notes: str = "") -> str:
|
||||
"""Cadastra um jogo pelo painel (antes só nascia da categoria da live) e pesquisa em segundo plano.
|
||||
Já existe (pelo id ou por outro nome dele) → UserError 409."""
|
||||
name = name.strip()[:120]
|
||||
if not name:
|
||||
raise ValueError("Diga o nome do jogo.")
|
||||
existing = self.find_game(name)
|
||||
if existing:
|
||||
raise LookupError(f"“{existing['name']}” já está na lista.")
|
||||
gid = game_id(name)
|
||||
note_list = [{"text": notes.strip()[:1500], "at": now()}] if notes.strip() else []
|
||||
self.e.db.run("INSERT INTO games (id, name, status, notes_json) VALUES (?, ?, 'pending', ?)",
|
||||
gid, name, json.dumps(note_list, ensure_ascii=False))
|
||||
if self.e.judge.enabled:
|
||||
threading.Thread(target=self._research_quietly, args=(gid,), name=f"game-{gid}", daemon=True).start()
|
||||
return gid
|
||||
|
||||
def _research_quietly(self, gid: str) -> None:
|
||||
try:
|
||||
self.research(gid)
|
||||
except JudgeError as exc:
|
||||
log.warning("pesquisa do jogo %s falhou: %s", gid, exc)
|
||||
|
||||
def delete_game(self, gid: str) -> None:
|
||||
"""Apaga o jogo. Sessões não mudam; se o jogo voltar numa live, nasce de novo e é pesquisado."""
|
||||
if not self.e.db.get("SELECT 1 FROM games WHERE id = ?", gid):
|
||||
raise JudgeError("jogo não encontrado")
|
||||
self.e.db.run("DELETE FROM games WHERE id = ?", gid)
|
||||
|
||||
def delete_note(self, gid: str, index: int) -> None:
|
||||
"""Esquece um pedido (ele deixa de voltar nas próximas pesquisas; o perfil atual não muda)."""
|
||||
@@ -270,11 +438,26 @@ class Intel:
|
||||
notes.pop(index)
|
||||
self.e.db.run("UPDATE games SET notes_json = ? WHERE id = ?", json.dumps(notes, ensure_ascii=False), gid)
|
||||
|
||||
def profile(self, name: str) -> dict | None:
|
||||
if not name:
|
||||
def find_game(self, name: str) -> dict | None:
|
||||
"""Linha do jogo pelo nome: id normalizado ou, se não achar, um jogo que tem esse nome entre os outros nomes."""
|
||||
gid = game_id(name or "")
|
||||
if not name or gid == "desconhecido":
|
||||
return None
|
||||
row = self.e.db.get("SELECT profile_json FROM games WHERE id = ? AND status = 'ready'", game_id(name))
|
||||
return loads(row["profile_json"], None) if row else None
|
||||
row = self.e.db.get("SELECT * FROM games WHERE id = ?", gid)
|
||||
if row:
|
||||
return row
|
||||
# aliases_json é uma lista JSON de ids: procura o id entre aspas (LIKE barato, confere no Python).
|
||||
for row in self.e.db.all("SELECT * FROM games WHERE aliases_json LIKE ?", f'%"{gid}"%'):
|
||||
if gid in loads(row.get("aliases_json"), []):
|
||||
return row
|
||||
return None
|
||||
|
||||
def profile(self, name: str) -> dict | None:
|
||||
"""Perfil que vai para a IA: a versão em inglês; jogo antigo, sem ela, usa a portuguesa."""
|
||||
row = self.find_game(name)
|
||||
if not row or row["status"] != "ready":
|
||||
return None
|
||||
return loads(row.get("profile_ai_json"), None) or loads(row["profile_json"], None)
|
||||
|
||||
def session_game(self, session: dict) -> tuple[str, dict | None]:
|
||||
"""(nome do jogo, perfil) da sessão — o mesmo critério do contexto: jogo confirmado por você vale sozinho;
|
||||
@@ -291,8 +474,11 @@ class Intel:
|
||||
memory = loads(session.get("memory_json"), [])
|
||||
confirmed = session.get("game_source") == "user" and bool(session.get("game"))
|
||||
profile = self.profile(session.get("game", "")) or (None if confirmed else self.profile(session.get("screen_game", "")))
|
||||
return game_context(session.get("game", ""), session.get("screen_game", ""), profile, session.get("title", ""),
|
||||
text = game_context(session.get("game", ""), session.get("screen_game", ""), profile, session.get("title", ""),
|
||||
" | ".join(m["summary"] for m in memory[-3:] if m.get("summary")), confirmed=confirmed)
|
||||
# Sessão em outro idioma (fonte gringa): o editor e a varredura escrevem título/legenda nesse idioma.
|
||||
note = output_language_note(session.get("language") or self.e.settings.language)
|
||||
return f"{text}\n{note}" if note else text
|
||||
|
||||
# ---------------------------------------------------------------- frames
|
||||
def frames(self, session: dict, times: list[float], tag: str) -> list[tuple[float, Path]]:
|
||||
|
||||
+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ê."""
|
||||
|
||||
+116
-28
@@ -19,7 +19,7 @@ from pathlib import Path
|
||||
from . import capture, layout, media
|
||||
from .config import REPO_ROOT
|
||||
from .db import Database, loads, now
|
||||
from .judge import JudgeError
|
||||
from .judge import LANGUAGE_NAMES, JudgeError
|
||||
from .scoring import timeline as timeline_series
|
||||
from .scoring import Word
|
||||
from .sources import SourceError, parse_source
|
||||
@@ -37,21 +37,43 @@ class UserError(Exception):
|
||||
self.message, self.status = message, status
|
||||
|
||||
|
||||
# Idiomas aceitos em `language` (fonte e sessão). '' = padrão do serviço (CLIPPER_LANGUAGE). O painel oferece os mesmos.
|
||||
LANGUAGES = tuple(LANGUAGE_NAMES)
|
||||
|
||||
|
||||
def check_language(value: str | None) -> str | None:
|
||||
"""None = não mexer; '' = voltar ao padrão; código válido = usar. Outra coisa é erro legível."""
|
||||
if value is None:
|
||||
return None
|
||||
code = value.strip()
|
||||
if code and code not in LANGUAGES:
|
||||
raise UserError(f"Idioma inválido: use {', '.join(LANGUAGES)} (ou vazio para o padrão).")
|
||||
return code
|
||||
|
||||
|
||||
class ChannelIn(BaseModel):
|
||||
url: str = Field(min_length=3, max_length=300)
|
||||
displayName: str | None = Field(default=None, max_length=60)
|
||||
monitor: bool = True
|
||||
authorized: bool = False
|
||||
language: str | None = Field(default=None, max_length=12)
|
||||
|
||||
|
||||
class ChannelPatch(BaseModel):
|
||||
displayName: str | None = Field(default=None, max_length=60)
|
||||
monitor: bool | None = None
|
||||
authorized: bool | None = None
|
||||
language: str | None = Field(default=None, max_length=12)
|
||||
|
||||
|
||||
class SessionIn(BaseModel):
|
||||
url: str = Field(min_length=3, max_length=300)
|
||||
language: str | None = Field(default=None, max_length=12)
|
||||
|
||||
|
||||
class StopIn(BaseModel):
|
||||
"""Parar à mão: `pauseMonitor` (padrão) deixa a fonte com o monitor pausado até você religar."""
|
||||
pauseMonitor: bool = True
|
||||
|
||||
|
||||
class ManualClipIn(BaseModel):
|
||||
@@ -62,7 +84,7 @@ class ManualClipIn(BaseModel):
|
||||
|
||||
|
||||
class JudgeIn(BaseModel):
|
||||
provider: Literal["codex", "claude", "off"]
|
||||
provider: Literal["codex", "claude", "gemini", "off"]
|
||||
model: str = Field(default="", max_length=80, pattern=r"^[A-Za-z0-9._:-]*$")
|
||||
minScore: float = Field(default=6, ge=0, le=10)
|
||||
# Modelo do ANALISTA (1º juiz, vê os frames); vazio = o mesmo do editor. None = não mexer.
|
||||
@@ -80,9 +102,17 @@ class GameIn(BaseModel):
|
||||
name: str = Field(min_length=1, max_length=120)
|
||||
|
||||
|
||||
class MissionIn(BaseModel):
|
||||
name: str = Field(min_length=1, max_length=160)
|
||||
chapter: str = Field(default="", max_length=120)
|
||||
summary: str = Field(default="", max_length=500)
|
||||
completion_triggers: list[str] = Field(default_factory=list, max_length=8)
|
||||
|
||||
|
||||
class GameProfileIn(BaseModel):
|
||||
"""Perfil do jogo editado à mão no painel (mesmos campos que a IA devolve)."""
|
||||
"""Perfil do jogo editado à mão no painel (mesmos campos que a IA devolve), em um dos dois idiomas."""
|
||||
name: str = Field(default="", max_length=120)
|
||||
aliases: list[str] = Field(default_factory=list, max_length=10) # outros nomes (categoria, abreviação)
|
||||
summary: str = Field(default="", max_length=1500)
|
||||
genre: str = Field(default="", max_length=120)
|
||||
mechanics: list[str] = Field(default_factory=list, max_length=30)
|
||||
@@ -92,6 +122,14 @@ class GameProfileIn(BaseModel):
|
||||
news: list[str] = Field(default_factory=list, max_length=30)
|
||||
hashtags: list[str] = Field(default_factory=list, max_length=20) # do jogo, a principal primeiro (app/hashtags.py)
|
||||
sources: list[str] = Field(default_factory=list, max_length=20)
|
||||
missions: list[MissionIn] = Field(default_factory=list, max_length=120)
|
||||
end_triggers: list[str] = Field(default_factory=list, max_length=12) # sinais gerais de fim de missão
|
||||
|
||||
|
||||
class GameIn(BaseModel):
|
||||
"""Jogo cadastrado pelo painel; `notes` = pista para a pesquisa (vira o 1º pedido guardado)."""
|
||||
name: str = Field(min_length=2, max_length=120)
|
||||
notes: str = Field(default="", max_length=1500)
|
||||
|
||||
|
||||
class ChatTurnIn(BaseModel):
|
||||
@@ -102,7 +140,8 @@ class ChatTurnIn(BaseModel):
|
||||
class GameRefineIn(BaseModel):
|
||||
instruction: str = Field(min_length=3, max_length=1500)
|
||||
search: bool = True # deixa a IA confirmar na web (mais lento); sem busca é quase instantâneo
|
||||
section: Literal["", "summary", "clip_worthy", "avoid", "mechanics", "news", "jargon", "hashtags", "sources"] = ""
|
||||
section: Literal["", "summary", "clip_worthy", "avoid", "mechanics", "news", "jargon", "hashtags", "sources",
|
||||
"missions", "end_triggers", "aliases"] = ""
|
||||
history: list[ChatTurnIn] = Field(default_factory=list, max_length=20) # conversa do chat da seção
|
||||
|
||||
|
||||
@@ -143,6 +182,8 @@ def clip_view(row: dict) -> dict:
|
||||
"aspect": row.get("aspect") or "vertical",
|
||||
"createdAt": row["created_at"], "updatedAt": row["updated_at"],
|
||||
"channelId": row.get("channel_id"), "platform": row.get("platform"), "sessionUrl": row.get("url"),
|
||||
# Idioma da sessão (resolvido no SELECT: o da sessão ou o padrão do serviço). Ausente só em consultas antigas.
|
||||
"language": row.get("language"),
|
||||
# Editor de cortes: existe projeto de edição? (o export renderiza por ele; capa gerada no export)
|
||||
"edit": ({"updatedAt": row["edit_updated_at"], "exportedAt": row.get("edit_exported_at"), "cover": row.get("edit_cover"),
|
||||
"origin": row.get("edit_origin")}
|
||||
@@ -174,14 +215,19 @@ def session_view(row: dict, engine: Engine) -> dict:
|
||||
# O que a captura gravou de fato (1º bloco de cada execução): qualidade pedida, largura, altura, qps, codec,
|
||||
# kbps, GB/h e `mixed` (retomada em outra resolução). None = sessão antiga ou ainda sem bloco.
|
||||
"capture": loads(row.get("capture_json"), None),
|
||||
# Idioma falado na live (resolvido: o da sessão, senão o padrão do serviço).
|
||||
"language": row.get("language") or engine.settings.language,
|
||||
}
|
||||
|
||||
|
||||
def channel_view(row: dict) -> dict:
|
||||
def channel_view(row: dict, default_language: str = "") -> dict:
|
||||
return {
|
||||
"id": row["id"], "platform": row["platform"], "channel": row["channel"], "url": row["url"],
|
||||
"displayName": row["display_name"], "monitor": bool(row["monitor"]), "authorized": bool(row["authorized"]),
|
||||
"lastCheckAt": row["last_check_at"], "lastStatus": row["last_status"], "createdAt": row["created_at"],
|
||||
# Monitor pausado porque você parou uma sessão à mão (não grava de novo até religar).
|
||||
"monitorPausedAt": row.get("monitor_paused_at"), "monitorPausedBySession": row.get("monitor_paused_session"),
|
||||
"language": row.get("language") or default_language,
|
||||
}
|
||||
|
||||
|
||||
@@ -386,27 +432,62 @@ def create_app(settings: Settings | None = None, engine: Engine | None = None, s
|
||||
engine.intel.set_game(session_id, body.name.strip(), "user")
|
||||
return session_view(_session(session_id), engine)
|
||||
|
||||
def game_view(g: dict) -> dict:
|
||||
# `profile` = português (o painel mostra); `profileAi` = inglês (vai nos prompts; null = jogo antigo, a IA
|
||||
# usa `profile`). Contrato em doc/clipador/JOGOS.md.
|
||||
return {"id": g["id"], "name": g["name"], "status": g["status"], "error": g["error"],
|
||||
"model": g["model"], "researchedAt": g["researched_at"], "editedAt": g.get("edited_at"),
|
||||
"notes": loads(g.get("notes_json"), []), "profile": loads(g["profile_json"], None),
|
||||
"profileAi": loads(g.get("profile_ai_json"), None), "aiLanguage": "en-US",
|
||||
"translatedAt": g.get("translated_at"), "aliases": loads(g.get("aliases_json"), [])}
|
||||
|
||||
@app.get("/v1/games")
|
||||
def list_games():
|
||||
return {"games": [{"id": g["id"], "name": g["name"], "status": g["status"], "error": g["error"],
|
||||
"model": g["model"], "researchedAt": g["researched_at"], "editedAt": g.get("edited_at"),
|
||||
"notes": loads(g.get("notes_json"), []), "profile": loads(g["profile_json"], None)}
|
||||
for g in db.all("SELECT * FROM games ORDER BY name")]}
|
||||
return {"games": [game_view(g) for g in db.all("SELECT * FROM games ORDER BY name")]}
|
||||
|
||||
@app.post("/v1/games", status_code=201)
|
||||
def add_game(body: GameIn):
|
||||
"""Cadastra um jogo e pesquisa em segundo plano (o jogo aparece `pending` até a pesquisa terminar)."""
|
||||
try:
|
||||
gid = engine.intel.add_game(body.name, body.notes)
|
||||
except LookupError as exc:
|
||||
raise UserError(str(exc), 409) from exc
|
||||
except ValueError as exc:
|
||||
raise UserError(str(exc)) from exc
|
||||
return {**list_games(), "id": gid}
|
||||
|
||||
@app.delete("/v1/games/{game_id}")
|
||||
def delete_game(game_id: str):
|
||||
try:
|
||||
engine.intel.delete_game(game_id)
|
||||
except JudgeError as exc:
|
||||
raise UserError(str(exc), 404) from exc
|
||||
return list_games()
|
||||
|
||||
@app.post("/v1/games/{game_id}/research")
|
||||
def research_game(game_id: str):
|
||||
"""Pesquisa (de novo) o jogo na web pela IA. Leva de 15 s a alguns minutos. Os pedidos guardados entram junto."""
|
||||
"""Pesquisa (de novo) o jogo na web pela IA, em inglês, e traduz para português. Leva de 15 s a alguns minutos.
|
||||
Os pedidos guardados entram junto."""
|
||||
try:
|
||||
engine.intel.research(game_id)
|
||||
except JudgeError as exc:
|
||||
raise UserError(str(exc)) from exc
|
||||
return list_games()
|
||||
|
||||
@app.put("/v1/games/{game_id}")
|
||||
def put_game_profile(game_id: str, body: GameProfileIn):
|
||||
"""Grava o perfil editado à mão. A IA passa a usar na hora."""
|
||||
@app.post("/v1/games/{game_id}/translate")
|
||||
def translate_game(game_id: str):
|
||||
"""Gera a versão da IA (inglês) a partir da portuguesa (jogos de antes dos perfis bilíngues)."""
|
||||
try:
|
||||
engine.intel.save_profile(game_id, body.model_dump())
|
||||
engine.intel.translate(game_id)
|
||||
except JudgeError as exc:
|
||||
raise UserError(str(exc)) from exc
|
||||
return list_games()
|
||||
|
||||
@app.put("/v1/games/{game_id}")
|
||||
def put_game_profile(game_id: str, body: GameProfileIn, lang: Literal["pt", "en"] = "pt"):
|
||||
"""Grava o perfil editado à mão no idioma `lang` e traduz para o outro. A IA passa a usar na hora."""
|
||||
try:
|
||||
engine.intel.save_profile(game_id, body.model_dump(), lang)
|
||||
except JudgeError as exc:
|
||||
raise UserError(str(exc), 404) from exc
|
||||
return list_games()
|
||||
@@ -440,7 +521,7 @@ def create_app(settings: Settings | None = None, engine: Engine | None = None, s
|
||||
# ---------- canais
|
||||
@app.get("/v1/channels")
|
||||
def list_channels():
|
||||
return {"channels": [channel_view(r) for r in db.all("SELECT * FROM channels ORDER BY display_name")]}
|
||||
return {"channels": [channel_view(r, settings.language) for r in db.all("SELECT * FROM channels ORDER BY display_name")]}
|
||||
|
||||
@app.post("/v1/channels", status_code=201)
|
||||
def create_channel(body: ChannelIn):
|
||||
@@ -449,22 +530,27 @@ def create_app(settings: Settings | None = None, engine: Engine | None = None, s
|
||||
raise UserError("Para monitorar, use o link do canal (ex.: twitch.tv/alanzoka), não de um vídeo.")
|
||||
if db.get("SELECT 1 FROM channels WHERE id = ?", source.channel_id):
|
||||
raise UserError("Esse canal já está na lista.", 409)
|
||||
db.run("INSERT INTO channels (id, platform, channel, url, display_name, monitor, authorized, created_at)"
|
||||
" VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
|
||||
language = check_language(body.language) or ""
|
||||
db.run("INSERT INTO channels (id, platform, channel, url, display_name, monitor, authorized, created_at, language)"
|
||||
" VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
|
||||
source.channel_id, source.platform, source.channel, source.url,
|
||||
(body.displayName or source.channel.lstrip("@")).strip(), int(body.monitor), int(body.authorized), now())
|
||||
return channel_view(db.get("SELECT * FROM channels WHERE id = ?", source.channel_id))
|
||||
(body.displayName or source.channel.lstrip("@")).strip(), int(body.monitor), int(body.authorized), now(), language)
|
||||
return channel_view(db.get("SELECT * FROM channels WHERE id = ?", source.channel_id), settings.language)
|
||||
|
||||
@app.patch("/v1/channels/{channel_id}")
|
||||
def update_channel(channel_id: str, body: ChannelPatch):
|
||||
row = db.get("SELECT * FROM channels WHERE id = ?", channel_id)
|
||||
if not row:
|
||||
raise UserError("Canal não encontrado.", 404)
|
||||
db.run("UPDATE channels SET display_name = ?, monitor = ?, authorized = ? WHERE id = ?",
|
||||
language = check_language(body.language)
|
||||
db.run("UPDATE channels SET display_name = ?, monitor = ?, authorized = ?, language = ? WHERE id = ?",
|
||||
(body.displayName or row["display_name"]).strip(),
|
||||
int(body.monitor if body.monitor is not None else row["monitor"]),
|
||||
int(body.authorized if body.authorized is not None else row["authorized"]), channel_id)
|
||||
return channel_view(db.get("SELECT * FROM channels WHERE id = ?", channel_id))
|
||||
int(body.authorized if body.authorized is not None else row["authorized"]),
|
||||
language if language is not None else row.get("language") or "", channel_id)
|
||||
if body.monitor is True:
|
||||
engine.clear_monitor_pause(channel_id) # "Religar" no painel
|
||||
return channel_view(db.get("SELECT * FROM channels WHERE id = ?", channel_id), settings.language)
|
||||
|
||||
@app.delete("/v1/channels/{channel_id}", status_code=204)
|
||||
def delete_channel(channel_id: str):
|
||||
@@ -491,8 +577,9 @@ def create_app(settings: Settings | None = None, engine: Engine | None = None, s
|
||||
def create_session(body: SessionIn):
|
||||
source = parse_source(body.url)
|
||||
channel = db.get("SELECT id FROM channels WHERE id = ?", source.channel_id) if source.channel else None
|
||||
language = check_language(body.language)
|
||||
try:
|
||||
session_id = engine.start_session(body.url, channel["id"] if channel else None)
|
||||
session_id = engine.start_session(body.url, channel["id"] if channel else None, language=language)
|
||||
except RuntimeError as exc:
|
||||
raise UserError(str(exc)) from exc
|
||||
return session_view(db.get("SELECT * FROM sessions WHERE id = ?", session_id), engine)
|
||||
@@ -533,8 +620,9 @@ def create_app(settings: Settings | None = None, engine: Engine | None = None, s
|
||||
return clip_view(_clip(int(cur.lastrowid)))
|
||||
|
||||
@app.post("/v1/sessions/{session_id}/stop")
|
||||
def stop_session(session_id: int):
|
||||
engine.stop_session(session_id)
|
||||
def stop_session(session_id: int, body: StopIn | None = None):
|
||||
"""Para a gravação à mão. Sem corpo (ou `pauseMonitor: true`): a fonte fica com o monitor pausado até religar."""
|
||||
engine.stop_session(session_id, pause_monitor=body.pauseMonitor if body else True)
|
||||
return {"ok": True}
|
||||
|
||||
@app.post("/v1/sessions/{session_id}/resume")
|
||||
@@ -566,8 +654,8 @@ def create_app(settings: Settings | None = None, engine: Engine | None = None, s
|
||||
channel: str | None = None, ids: str | None = None):
|
||||
"""Filtros opcionais (todos separados por vírgula): `status`, `channel` (fontes, ex.: twitch-alanzoka) e `ids`.
|
||||
O despachante de publicação do painel usa `channel` + `status=ready,approved` e `ids` para conferir a fila."""
|
||||
sql = "SELECT c.*, s.channel_id, s.platform, s.url, e.updated_at AS edit_updated_at, e.exported_at AS edit_exported_at, e.cover AS edit_cover, e.origin AS edit_origin FROM clips c JOIN sessions s ON s.id = c.session_id LEFT JOIN edits e ON e.clip_id = c.id WHERE 1 = 1"
|
||||
params: list = []
|
||||
sql = "SELECT c.*, s.channel_id, s.platform, s.url, COALESCE(NULLIF(s.language, ''), ?) AS language, e.updated_at AS edit_updated_at, e.exported_at AS edit_exported_at, e.cover AS edit_cover, e.origin AS edit_origin FROM clips c JOIN sessions s ON s.id = c.session_id LEFT JOIN edits e ON e.clip_id = c.id WHERE 1 = 1"
|
||||
params: list = [settings.language]
|
||||
if status:
|
||||
sql += " AND c.status IN (" + ",".join("?" * len(status.split(","))) + ")"
|
||||
params += status.split(",")
|
||||
@@ -590,7 +678,7 @@ def create_app(settings: Settings | None = None, engine: Engine | None = None, s
|
||||
return {"clips": [clip_view(r) for r in db.all(sql, *params)]}
|
||||
|
||||
def _clip(clip_id: int) -> dict:
|
||||
row = db.get("SELECT c.*, s.channel_id, s.platform, s.url, e.updated_at AS edit_updated_at, e.exported_at AS edit_exported_at, e.cover AS edit_cover, e.origin AS edit_origin FROM clips c JOIN sessions s ON s.id = c.session_id LEFT JOIN edits e ON e.clip_id = c.id WHERE c.id = ?", clip_id)
|
||||
row = db.get("SELECT c.*, s.channel_id, s.platform, s.url, COALESCE(NULLIF(s.language, ''), ?) AS language, e.updated_at AS edit_updated_at, e.exported_at AS edit_exported_at, e.cover AS edit_cover, e.origin AS edit_origin FROM clips c JOIN sessions s ON s.id = c.session_id LEFT JOIN edits e ON e.clip_id = c.id WHERE c.id = ?", settings.language, clip_id)
|
||||
if not row:
|
||||
raise UserError("Corte não encontrado.", 404)
|
||||
return row
|
||||
|
||||
@@ -0,0 +1,217 @@
|
||||
{
|
||||
"name": "Grand Theft Auto VI",
|
||||
"aliases": ["GTA 6", "GTA VI", "GTA6", "GTAVI", "Grand Theft Auto 6"],
|
||||
"researchedAt": "2026-11-18T12:00:00Z",
|
||||
"sources": [
|
||||
"https://www.rockstargames.com/VI",
|
||||
"https://www.forbes.com/sites/erikkain/2026/11/16/gta-6-release-date-time-ps5-xbox-series-x-download-size-day-one-update/",
|
||||
"https://hothardware.com/news/gta-6-extended-look-reveals-story-missions-and-massive-map-details",
|
||||
"https://lfcarry.com/guides/gta-6-chapter-list-walkthrough",
|
||||
"https://www.gtabase.com/articles/gta-6/gta-6-previews-recap-all-new-gameplay-features-revealed",
|
||||
"https://allthings.how/gta-6-wanted-system-explained-how-heat-builds-and-how-you-lose-it/",
|
||||
"https://www.redbull.com/int-en/gta-6-gameplay-details",
|
||||
"https://www.gfinityesports.com/article/gta-6-map-guide-every-confirmed-location-in-leonida"
|
||||
],
|
||||
"profileAi": {
|
||||
"name": "Grand Theft Auto VI",
|
||||
"aliases": ["GTA 6", "GTA VI", "GTA6", "GTAVI", "Grand Theft Auto 6"],
|
||||
"genre": "Open-world action-adventure / crime",
|
||||
"summary": "Rockstar's open-world crime game set in the state of Leonida (a Florida parody), centered on Vice City. You play as Jason Duval and Lucia Caminos, a criminal couple who start with small robberies and work up to bigger jobs, switching between them (even mid-action). Released November 19, 2026 on PS5 and Xbox Series X|S.",
|
||||
"mechanics": [
|
||||
"Two playable protagonists (Jason and Lucia), switchable at any time, including mid-chase",
|
||||
"Robberies of stores, diners and gas stations early on; bigger heists later (bank job at Sinfrontera National Bank shown in trailers)",
|
||||
"Wanted level with up to six stars plus a Heat system: police only react to reported crimes (witness or alarm); the HUD shows what cops know (vehicle, outfit, face, weapons, CCTV)",
|
||||
"Losing the cops: break line of sight, change outfit or vehicle, split Jason and Lucia up, wear masks before crimes",
|
||||
"Carjacking with a slim jim instead of breaking windows; low-end cars and basic locks at the start",
|
||||
"Phone and in-game social media (calls, texts, feeds); the couple can meet up for crimes or dates in free roam",
|
||||
"Huge map: Vice City, Leonida Keys, Grassrivers, Port Gellhorn, Ambrosia, Mount Kalaga; wildlife including alligators",
|
||||
"Activities: hunting and fishing, nightlife, gym, side jobs and strangers"
|
||||
],
|
||||
"clip_worthy": [
|
||||
"Heist or store robbery going wrong: alarm, hostage, partner panics, cops arrive early",
|
||||
"Wild police chase escalating to 5-6 stars, ending in a crash or a lucky escape",
|
||||
"Switching between Jason and Lucia at the perfect moment in a chase or shootout",
|
||||
"Alligator, wildlife or 'Florida Man' NPC chaos (bizarre locals, viral-style street scenes)",
|
||||
"Physics and ragdoll fails: car flips, boat or jet ski crashes, falling off buildings",
|
||||
"Streamer's first reaction to a big reveal: Vice City skyline, a story twist, a famous character",
|
||||
"Mission climax: last-second escape, the payout being counted, or a dramatic WASTED/BUSTED right at the end",
|
||||
"Funny dialogue between Jason and Lucia or with NPCs (Cal, Boobie Ike, Raul)",
|
||||
"Graphics and realism 'wow' moments the chat spams about (crowds, weather, beach)",
|
||||
"Launch-day glitches and bugs (cars in walls, T-poses, NPC weirdness)"
|
||||
],
|
||||
"avoid": [
|
||||
"Menus, map browsing, wardrobe and shopping screens",
|
||||
"Long cutscenes with no reaction from the streamer (also copyright-heavy)",
|
||||
"Driving across the map with nothing happening",
|
||||
"Loading screens, settings and install or update talk",
|
||||
"Repetitive gunfights with no fail, escape or joke"
|
||||
],
|
||||
"jargon": [
|
||||
"Leonida (the state), Vice City / VC, the Keys",
|
||||
"Jason, Lucia (Lu), Cal, Boobie Ike, Raul Bautista, Brian, Dre'Quan, Real Dimez",
|
||||
"estrelas / stars / procurado / wanted, heat, '6 estrelas'",
|
||||
"WASTED / BUSTED",
|
||||
"assalto / roubo / golpe / heist",
|
||||
"boca / stash house",
|
||||
"Florida Man",
|
||||
"chave micha / slim jim",
|
||||
"trocar de personagem / switch",
|
||||
"GTA Online / GTAO (when online launches)"
|
||||
],
|
||||
"news": [
|
||||
"Nov 2026: launch on November 19, 2026 (midnight local time, rolling by region), PS5 and Xbox Series X|S only; no PC version announced",
|
||||
"Nov 2026: download of up to ~212 GB with a day-one update",
|
||||
"Nov 2025: release moved from May 26, 2026 to November 19, 2026",
|
||||
"2026: the 'An Extended Look' gameplay video showed story mission openings, robberies and the wanted/Heat HUD",
|
||||
"May 2025: Trailer 2 introduced Jason, Lucia and the supporting cast"
|
||||
],
|
||||
"hashtags": ["#GTA6", "#GTAVI", "#GrandTheftAutoVI", "#ViceCity", "#GTA6Brasil", "#Rockstar"],
|
||||
"sources": [
|
||||
"https://www.rockstargames.com/VI",
|
||||
"https://www.forbes.com/sites/erikkain/2026/11/16/gta-6-release-date-time-ps5-xbox-series-x-download-size-day-one-update/",
|
||||
"https://hothardware.com/news/gta-6-extended-look-reveals-story-missions-and-massive-map-details",
|
||||
"https://lfcarry.com/guides/gta-6-chapter-list-walkthrough",
|
||||
"https://www.gtabase.com/articles/gta-6/gta-6-previews-recap-all-new-gameplay-features-revealed",
|
||||
"https://allthings.how/gta-6-wanted-system-explained-how-heat-builds-and-how-you-lose-it/",
|
||||
"https://www.redbull.com/int-en/gta-6-gameplay-details",
|
||||
"https://www.gfinityesports.com/article/gta-6-map-guide-every-confirmed-location-in-leonida"
|
||||
],
|
||||
"missions": [
|
||||
{
|
||||
"name": "Boobie Ike stash pickup (descriptive name, not official)",
|
||||
"chapter": "Shown in 'An Extended Look' (pre-launch)",
|
||||
"summary": "A drug pickup for Boobie Ike that turns into a police raid.",
|
||||
"completion_triggers": ["Escaping the raid and losing the wanted stars", "Dropping the package at Boobie's spot or the end-of-mission cutscene", "Mission complete banner or results screen"]
|
||||
},
|
||||
{
|
||||
"name": "Raul Bautista getaway (descriptive name, not official)",
|
||||
"chapter": "Shown in 'An Extended Look' (pre-launch)",
|
||||
"summary": "A getaway job for the professional robber Raul Bautista.",
|
||||
"completion_triggers": ["Reaching the drop-off or safe point with the police lost", "Payout or split shown on screen", "Mission complete banner or results screen"]
|
||||
},
|
||||
{
|
||||
"name": "Skyscraper security job (descriptive name, not official)",
|
||||
"chapter": "Shown in 'An Extended Look' (pre-launch)",
|
||||
"summary": "A security job that turns into a hostage situation inside a skyscraper.",
|
||||
"completion_triggers": ["Hostage standoff resolved (shootout ends or a deal is made)", "Leaving the building or the escape cutscene", "Mission complete banner or results screen"]
|
||||
},
|
||||
{
|
||||
"name": "Rooftop party with a wealthy employer (descriptive name, not official)",
|
||||
"chapter": "Shown in 'An Extended Look' (pre-launch)",
|
||||
"summary": "Jason and Lucia meet a very wealthy, dubious employer at a rooftop party.",
|
||||
"completion_triggers": ["The conversation or cutscene with the employer ends", "A new contact appears on the phone", "Mission complete banner"]
|
||||
}
|
||||
],
|
||||
"end_triggers": [
|
||||
"Mission complete/passed banner or a results screen with time, accuracy or payout",
|
||||
"Robbery payout or money split counted on screen",
|
||||
"Wanted stars disappear (cops lost) right after the getaway",
|
||||
"Arriving at the drop-off, hideout or safehouse marker and the car stops",
|
||||
"Ending cutscene starts (camera leaves gameplay, letterbox bars)",
|
||||
"Failure: WASTED or BUSTED screen, or 'mission failed' with a retry prompt",
|
||||
"Phone call or text from the contact wrapping up the job",
|
||||
"Streamer says 'passou', 'consegui', 'acabou a missão' or celebrates; chat spams GG/W"
|
||||
]
|
||||
},
|
||||
"profile": {
|
||||
"name": "Grand Theft Auto VI",
|
||||
"aliases": ["GTA 6", "GTA VI", "GTA6", "GTAVI", "Grand Theft Auto 6"],
|
||||
"genre": "Ação e aventura em mundo aberto / crime",
|
||||
"summary": "Jogo de crime em mundo aberto da Rockstar no estado de Leonida (paródia da Flórida), com Vice City no centro. Você joga com Jason Duval e Lucia Caminos, um casal de criminosos que começa com roubos pequenos e sobe para trabalhos maiores, trocando entre os dois (até no meio da ação). Lançado em 19 de novembro de 2026 para PS5 e Xbox Series X|S.",
|
||||
"mechanics": [
|
||||
"Dois protagonistas jogáveis (Jason e Lucia), com troca a qualquer hora, inclusive no meio de uma perseguição",
|
||||
"Roubos de lojas, lanchonetes e postos no começo; golpes maiores depois (assalto ao Sinfrontera National Bank nos trailers)",
|
||||
"Procurado com até seis estrelas mais o sistema de Heat: a polícia só reage a crime denunciado (testemunha ou alarme); o HUD mostra o que a polícia sabe (carro, roupa, rosto, armas, câmeras)",
|
||||
"Despistar a polícia: sair do campo de visão, trocar roupa ou carro, separar Jason e Lucia, usar máscara antes do crime",
|
||||
"Roubo de carro com chave micha (slim jim) em vez de quebrar o vidro; carros fracos e trancas simples no início",
|
||||
"Celular e redes sociais do jogo (ligações, mensagens, feeds); o casal pode se encontrar para crimes ou encontros no mundo aberto",
|
||||
"Mapa enorme: Vice City, Leonida Keys, Grassrivers, Port Gellhorn, Ambrosia, Mount Kalaga; fauna com jacarés",
|
||||
"Atividades: caça e pesca, vida noturna, academia, trabalhos paralelos e personagens aleatórios"
|
||||
],
|
||||
"clip_worthy": [
|
||||
"Assalto ou roubo de loja dando errado: alarme, refém, parceiro em pânico, polícia chegando antes",
|
||||
"Perseguição policial que escala para 5-6 estrelas e termina em batida ou fuga na sorte",
|
||||
"Troca entre Jason e Lucia no momento perfeito de uma perseguição ou tiroteio",
|
||||
"Caos com jacaré, bichos ou NPC 'Florida Man' (moradores bizarros, cenas de rua tipo viral)",
|
||||
"Falhas de física: carro capotando, lancha ou jet ski batendo, queda de prédio",
|
||||
"Primeira reação do streamer a algo grande: horizonte de Vice City, reviravolta da história, personagem famoso",
|
||||
"Clímax de missão: fuga no último segundo, o dinheiro sendo contado, ou um WASTED/BUSTED bem no final",
|
||||
"Diálogo engraçado entre Jason e Lucia ou com NPCs (Cal, Boobie Ike, Raul)",
|
||||
"Momentos de 'olha esse gráfico' que o chat comenta (multidão, clima, praia)",
|
||||
"Bugs e glitches de lançamento (carro na parede, T-pose, NPC estranho)"
|
||||
],
|
||||
"avoid": [
|
||||
"Menus, mapa, guarda-roupa e telas de compra",
|
||||
"Cutscenes longas sem reação do streamer (e com risco de direitos autorais)",
|
||||
"Dirigir pelo mapa sem acontecer nada",
|
||||
"Telas de carregamento, configurações e papo de instalação ou atualização",
|
||||
"Tiroteio repetitivo sem falha, fuga ou piada"
|
||||
],
|
||||
"jargon": [
|
||||
"Leonida (o estado), Vice City / VC, the Keys",
|
||||
"Jason, Lucia (Lu), Cal, Boobie Ike, Raul Bautista, Brian, Dre'Quan, Real Dimez",
|
||||
"estrelas / stars / procurado / wanted, heat, '6 estrelas'",
|
||||
"WASTED / BUSTED",
|
||||
"assalto / roubo / golpe / heist",
|
||||
"boca / stash house",
|
||||
"Florida Man",
|
||||
"chave micha / slim jim",
|
||||
"trocar de personagem / switch",
|
||||
"GTA Online / GTAO (quando o online sair)"
|
||||
],
|
||||
"news": [
|
||||
"nov/2026: lançamento em 19 de novembro de 2026 (meia-noite no horário local, por região), só PS5 e Xbox Series X|S; sem versão de PC anunciada",
|
||||
"nov/2026: download de até ~212 GB com atualização do primeiro dia",
|
||||
"nov/2025: lançamento adiado de 26 de maio de 2026 para 19 de novembro de 2026",
|
||||
"2026: o vídeo 'An Extended Look' mostrou o início de missões da história, roubos e o HUD de procurado/Heat",
|
||||
"mai/2025: o Trailer 2 apresentou Jason, Lucia e o elenco de apoio"
|
||||
],
|
||||
"hashtags": ["#GTA6", "#GTAVI", "#GrandTheftAutoVI", "#ViceCity", "#GTA6Brasil", "#Rockstar"],
|
||||
"sources": [
|
||||
"https://www.rockstargames.com/VI",
|
||||
"https://www.forbes.com/sites/erikkain/2026/11/16/gta-6-release-date-time-ps5-xbox-series-x-download-size-day-one-update/",
|
||||
"https://hothardware.com/news/gta-6-extended-look-reveals-story-missions-and-massive-map-details",
|
||||
"https://lfcarry.com/guides/gta-6-chapter-list-walkthrough",
|
||||
"https://www.gtabase.com/articles/gta-6/gta-6-previews-recap-all-new-gameplay-features-revealed",
|
||||
"https://allthings.how/gta-6-wanted-system-explained-how-heat-builds-and-how-you-lose-it/",
|
||||
"https://www.redbull.com/int-en/gta-6-gameplay-details",
|
||||
"https://www.gfinityesports.com/article/gta-6-map-guide-every-confirmed-location-in-leonida"
|
||||
],
|
||||
"missions": [
|
||||
{
|
||||
"name": "Boobie Ike stash pickup (nome descritivo, não oficial)",
|
||||
"chapter": "Mostrada em 'An Extended Look' (antes do lançamento)",
|
||||
"summary": "Uma coleta de droga para o Boobie Ike que vira uma batida policial.",
|
||||
"completion_triggers": ["Fugir da batida e perder as estrelas", "Entregar a carga no ponto do Boobie ou a cutscene de fim", "Banner de missão concluída ou tela de resultado"]
|
||||
},
|
||||
{
|
||||
"name": "Raul Bautista getaway (nome descritivo, não oficial)",
|
||||
"chapter": "Mostrada em 'An Extended Look' (antes do lançamento)",
|
||||
"summary": "Uma fuga para o assaltante profissional Raul Bautista.",
|
||||
"completion_triggers": ["Chegar ao ponto de entrega com a polícia despistada", "Dinheiro ou divisão aparecendo na tela", "Banner de missão concluída ou tela de resultado"]
|
||||
},
|
||||
{
|
||||
"name": "Skyscraper security job (nome descritivo, não oficial)",
|
||||
"chapter": "Mostrada em 'An Extended Look' (antes do lançamento)",
|
||||
"summary": "Um trabalho de segurança que vira uma situação com reféns num arranha-céu.",
|
||||
"completion_triggers": ["Impasse com reféns resolvido (fim do tiroteio ou acordo)", "Saída do prédio ou cutscene de fuga", "Banner de missão concluída ou tela de resultado"]
|
||||
},
|
||||
{
|
||||
"name": "Rooftop party with a wealthy employer (nome descritivo, não oficial)",
|
||||
"chapter": "Mostrada em 'An Extended Look' (antes do lançamento)",
|
||||
"summary": "Jason e Lucia conhecem um patrão muito rico e suspeito numa festa na cobertura.",
|
||||
"completion_triggers": ["A conversa ou cutscene com o patrão termina", "Um contato novo aparece no celular", "Banner de missão concluída"]
|
||||
}
|
||||
],
|
||||
"end_triggers": [
|
||||
"Banner de missão concluída ou tela de resultado com tempo, precisão ou pagamento",
|
||||
"Dinheiro do roubo ou a divisão sendo contados na tela",
|
||||
"As estrelas de procurado somem (polícia despistada) logo depois da fuga",
|
||||
"Chegada ao marcador de entrega, esconderijo ou casa e o carro para",
|
||||
"Começa a cutscene final (a câmera sai do gameplay, faixas pretas)",
|
||||
"Falha: tela WASTED ou BUSTED, ou 'missão falhou' com opção de tentar de novo",
|
||||
"Ligação ou mensagem do contato encerrando o trabalho",
|
||||
"Streamer fala 'passou', 'consegui', 'acabou a missão' ou comemora; chat enche de GG/W"
|
||||
]
|
||||
}
|
||||
}
|
||||
+63
-24
@@ -67,11 +67,12 @@ class VoiceClient:
|
||||
except httpx.HTTPError:
|
||||
return False
|
||||
|
||||
def transcribe(self, wav: bytes, idempotency_key: str) -> list[Word]:
|
||||
def transcribe(self, wav: bytes, idempotency_key: str, language: str | None = None) -> list[Word]:
|
||||
"""`language` = idioma da sessão (fonte gringa); vazio/None = o padrão do serviço (CLIPPER_LANGUAGE)."""
|
||||
if not self.configured:
|
||||
raise RuntimeError("serviço de voz não instalado")
|
||||
headers = {
|
||||
"X-Service-Key": self.key or "", "Content-Type": "audio/wav", "X-Language": self.language,
|
||||
"X-Service-Key": self.key or "", "Content-Type": "audio/wav", "X-Language": language or self.language,
|
||||
"X-Detail": "words", "X-Idempotency-Key": idempotency_key,
|
||||
}
|
||||
response = httpx.post(f"{self.url}/v1/transcribe", content=wav, headers=headers, timeout=180)
|
||||
@@ -462,6 +463,9 @@ class Engine:
|
||||
self.db.run("UPDATE sessions SET status = 'starting', ended_at = NULL, error = NULL WHERE id = ?", session_id)
|
||||
capture = Capture(self, session_id, source, REPO_ROOT / session["dir"], start_idx=(last + 1) if last is not None else 0)
|
||||
self.captures[session_id] = capture
|
||||
if session["channel_id"] and not only_if_status:
|
||||
# Você retomou pelo painel: a fonte volta a ser monitorada (a retomada automática não mexe na pausa).
|
||||
self.clear_monitor_pause(session["channel_id"])
|
||||
capture.start()
|
||||
return True
|
||||
|
||||
@@ -513,7 +517,9 @@ class Engine:
|
||||
return self.judge_config()
|
||||
|
||||
# ---------- sessões
|
||||
def start_session(self, url: str, channel_id: str | None = None) -> int:
|
||||
def start_session(self, url: str, channel_id: str | None = None, language: str | None = None) -> int:
|
||||
"""Começa a gravar (live) ou baixar (VOD). `language` = idioma falado; vazio herda o da fonte ('' = padrão).
|
||||
Gravar à mão uma fonte com o monitor pausado religa o monitor (você ligou de propósito)."""
|
||||
source = parse_source(url)
|
||||
if not self.settings.streamlink or not self.settings.ffmpeg:
|
||||
raise RuntimeError("Streamlink ou FFmpeg não encontrados: rode o setup.bat.")
|
||||
@@ -521,10 +527,14 @@ class Engine:
|
||||
active = self.db.get("SELECT id FROM sessions WHERE url = ? AND status IN ('starting', 'recording')", source.url)
|
||||
if active:
|
||||
return active["id"]
|
||||
channel = self.db.get("SELECT language FROM channels WHERE id = ?", channel_id) if channel_id else None
|
||||
cur = self.db.run(
|
||||
"INSERT INTO sessions (channel_id, platform, kind, url, status, dir, started_at) VALUES (?, ?, ?, ?, 'starting', '', ?)",
|
||||
channel_id, source.platform, source.kind, source.url, now())
|
||||
"INSERT INTO sessions (channel_id, platform, kind, url, status, dir, started_at, language)"
|
||||
" VALUES (?, ?, ?, ?, 'starting', '', ?, ?)",
|
||||
channel_id, source.platform, source.kind, source.url, now(), (language or (channel or {}).get("language") or "").strip())
|
||||
session_id = int(cur.lastrowid)
|
||||
if channel_id:
|
||||
self.clear_monitor_pause(channel_id)
|
||||
workdir = self.settings.data_dir / "sessions" / str(session_id)
|
||||
self.db.run("UPDATE sessions SET dir = ? WHERE id = ?", rel(workdir), session_id)
|
||||
capture = Capture(self, session_id, source, workdir)
|
||||
@@ -548,12 +558,28 @@ class Engine:
|
||||
if session:
|
||||
self.intel.check_game(session, force=True)
|
||||
|
||||
def stop_session(self, session_id: int) -> None:
|
||||
def stop_session(self, session_id: int, *, pause_monitor: bool = True) -> None:
|
||||
"""Para a gravação. `pause_monitor` (padrão): a fonte monitorada fica com o monitor PAUSADO — senão, 60 s depois
|
||||
o monitor abriria uma sessão nova, porque a live continua no ar (reclamação do dono, 18/11/2026). A queda de
|
||||
live (captura cai sozinha) não passa por aqui e continua retomando na mesma sessão (`keep_live`)."""
|
||||
with self.lock:
|
||||
capture = self.captures.get(session_id)
|
||||
if capture:
|
||||
self.db.run("UPDATE sessions SET status = 'stopped' WHERE id = ? AND status IN ('starting', 'recording')", session_id)
|
||||
capture.stop()
|
||||
if pause_monitor:
|
||||
session = self.db.get("SELECT channel_id FROM sessions WHERE id = ?", session_id)
|
||||
if session and session["channel_id"]:
|
||||
changed = self.db.run("UPDATE channels SET monitor_paused_at = ?, monitor_paused_session = ? WHERE id = ? AND monitor = 1",
|
||||
now(), session_id, session["channel_id"]).rowcount
|
||||
if changed:
|
||||
log.info("fonte %s: monitor pausado (você parou a sessão %s)", session["channel_id"], session_id)
|
||||
|
||||
def clear_monitor_pause(self, channel_id: str) -> None:
|
||||
"""Religa o monitor da fonte (PATCH monitor=true, gravar pelo link ou retomar uma sessão dela)."""
|
||||
if self.db.run("UPDATE channels SET monitor_paused_at = NULL, monitor_paused_session = NULL WHERE id = ? AND monitor_paused_at IS NOT NULL",
|
||||
channel_id).rowcount:
|
||||
log.info("fonte %s: monitor religado", channel_id)
|
||||
|
||||
def capture_finished(self, session_id: int) -> None:
|
||||
with self.lock:
|
||||
@@ -571,24 +597,35 @@ class Engine:
|
||||
# ---------- monitor de canais
|
||||
def _monitor_loop(self) -> None:
|
||||
while not self.stop_event.is_set():
|
||||
for channel in self.db.all("SELECT * FROM channels WHERE monitor = 1"):
|
||||
if self.stop_event.is_set():
|
||||
break
|
||||
busy = self.db.get("SELECT id FROM sessions WHERE channel_id = ? AND status IN ('starting', 'recording')", channel["id"])
|
||||
if busy:
|
||||
continue
|
||||
live, title = self.check_live(channel["url"])
|
||||
self.db.run("UPDATE channels SET last_check_at = ?, last_status = ? WHERE id = ?",
|
||||
now(), "ao vivo" if live else "offline", channel["id"])
|
||||
if live:
|
||||
log.info("canal %s ao vivo: iniciando gravação", channel["id"])
|
||||
try:
|
||||
session_id = self.start_session(channel["url"], channel["id"])
|
||||
self.db.run("UPDATE sessions SET title = ? WHERE id = ?", title[:200], session_id)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
log.warning("canal %s: não iniciou (%s)", channel["id"], exc)
|
||||
self.monitor_once()
|
||||
self.stop_event.wait(self.settings.poll_s)
|
||||
|
||||
def monitor_once(self) -> list[int]:
|
||||
"""Uma passada do monitor: checa cada fonte monitorada (e não pausada) sem sessão ativa e grava as que estão
|
||||
ao vivo. Devolve os ids das sessões iniciadas (os testes chamam direto)."""
|
||||
started: list[int] = []
|
||||
for channel in self.db.all("SELECT * FROM channels WHERE monitor = 1"):
|
||||
if self.stop_event.is_set():
|
||||
break
|
||||
if channel.get("monitor_paused_at"):
|
||||
log.debug("fonte %s: monitor pausado (sessão %s parada à mão), pulando", channel["id"], channel.get("monitor_paused_session"))
|
||||
continue
|
||||
busy = self.db.get("SELECT id FROM sessions WHERE channel_id = ? AND status IN ('starting', 'recording')", channel["id"])
|
||||
if busy:
|
||||
continue
|
||||
live, title = self.check_live(channel["url"])
|
||||
self.db.run("UPDATE channels SET last_check_at = ?, last_status = ? WHERE id = ?",
|
||||
now(), "ao vivo" if live else "offline", channel["id"])
|
||||
if live:
|
||||
log.info("canal %s ao vivo: iniciando gravação", channel["id"])
|
||||
try:
|
||||
session_id = self.start_session(channel["url"], channel["id"])
|
||||
self.db.run("UPDATE sessions SET title = ? WHERE id = ?", title[:200], session_id)
|
||||
started.append(session_id)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
log.warning("canal %s: não iniciou (%s)", channel["id"], exc)
|
||||
return started
|
||||
|
||||
def live_check(self, url: str) -> LiveCheck:
|
||||
"""Streamlink --json, separando "offline" de "não deu para checar". Falha de checagem vai para o log com o
|
||||
motivo e o fim do stderr (antes era engolida e parecia "offline")."""
|
||||
@@ -701,7 +738,9 @@ class Engine:
|
||||
pcm = media.decode_pcm(self.settings.ffmpeg or "ffmpeg", [file])
|
||||
loudness = media.loudness_per_second(pcm)
|
||||
try:
|
||||
rel_words = self.voice.transcribe(media.to_wav(pcm), f"clipper-{segment['session_id']}-{segment['idx']}")
|
||||
owner = self.db.get("SELECT language FROM sessions WHERE id = ?", segment["session_id"])
|
||||
rel_words = self.voice.transcribe(media.to_wav(pcm), f"clipper-{segment['session_id']}-{segment['idx']}",
|
||||
language=(owner or {}).get("language") or None)
|
||||
words = [Word(round(w.start + segment["start_s"], 3), round(w.end + segment["start_s"], 3), w.word)
|
||||
for w in rel_words]
|
||||
except Exception as exc: # noqa: BLE001 - sem voz o corte segue pelo chat
|
||||
@@ -1051,7 +1090,7 @@ class Engine:
|
||||
self.db.run("UPDATE segments SET deleted = 1 WHERE session_id = ? AND idx = ?", seg["session_id"], seg["idx"])
|
||||
|
||||
def delete_session(self, session_id: int) -> None:
|
||||
self.stop_session(session_id)
|
||||
self.stop_session(session_id, pause_monitor=False)
|
||||
session = self.db.get("SELECT * FROM sessions WHERE id = ?", session_id)
|
||||
if not session:
|
||||
return
|
||||
|
||||
Reference in New Issue
Block a user