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,18 @@
|
||||
"""Configuração comum dos testes do Clipador."""
|
||||
import pytest
|
||||
|
||||
import app.ai_settings as ai_settings_module
|
||||
import app.intel as intel_module
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _isolated_ai_settings(tmp_path_factory, monkeypatch):
|
||||
# Configurações → IA do painel (data/ai real) não entram nos testes: cada teste começa com o padrão do doc.
|
||||
monkeypatch.setattr(ai_settings_module, "DEFAULT_AI_DIR", tmp_path_factory.mktemp("ai-settings"))
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _no_real_game_seeds(tmp_path_factory, monkeypatch):
|
||||
# As sementes de jogo do repositório (app/seeds/games, ex.: GTA VI) entrariam em todo banco de teste e mudariam
|
||||
# a lista de jogos. Cada teste começa sem nenhuma; quem testa sementes passa a própria pasta.
|
||||
monkeypatch.setattr(intel_module, "SEEDS_DIR", tmp_path_factory.mktemp("no-seeds"))
|
||||
@@ -0,0 +1,313 @@
|
||||
"""Gemini no juiz, IA reserva e modo chave de API (contrato em doc/ia.md). Nenhuma CLI de verdade roda aqui:
|
||||
`subprocess.run` e os `find_*` do juiz são trocados por falsos."""
|
||||
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from app import judge as judge_module
|
||||
from app.ai_settings import DEFAULT_SETTINGS, AiConfig, normalize_settings
|
||||
from app.judge import (DEFAULT_MODELS, VERDICT_SCHEMA, Judge, JudgeError, extract_json_object, is_availability_error,
|
||||
parse_gemini_output)
|
||||
from tests.test_sources_and_api import KEY, auth, env # noqa: F401 - fixture reaproveitada
|
||||
|
||||
VERDICT = {"keep": True, "score": 8, "start_s": 100, "end_s": 170, "title": "Virada", "caption": "c",
|
||||
"hashtags": ["lag"], "reason": "r"}
|
||||
|
||||
|
||||
class ReversedCipher:
|
||||
"""Cifrador falso: o "blob" é o JSON de trás para frente (garante que o cofre passa pelo cifrador)."""
|
||||
|
||||
def unprotect(self, data: bytes) -> bytes:
|
||||
return data[::-1]
|
||||
|
||||
|
||||
_STAMPS = iter(range(1_700_000_000, 1_800_000_000, 7))
|
||||
|
||||
|
||||
def write_settings(folder: Path, data: dict) -> None:
|
||||
folder.mkdir(parents=True, exist_ok=True)
|
||||
path = folder / "settings.json"
|
||||
path.write_text(json.dumps(data), encoding="utf-8")
|
||||
# mtime sempre diferente do anterior (o sistema de arquivos pode ter resolução grossa)
|
||||
stamp = next(_STAMPS) * 1_000_000_000
|
||||
os.utime(path, ns=(stamp, stamp))
|
||||
|
||||
|
||||
def write_vault(folder: Path, keys: dict) -> None:
|
||||
folder.mkdir(parents=True, exist_ok=True)
|
||||
(folder / "vault.bin").write_bytes(json.dumps(keys).encode("utf-8")[::-1])
|
||||
|
||||
|
||||
def settings_with(**providers) -> dict:
|
||||
data = json.loads(json.dumps(DEFAULT_SETTINGS))
|
||||
for name, conf in providers.items():
|
||||
data["providers"][name].update(conf)
|
||||
return data
|
||||
|
||||
|
||||
class FakeCli:
|
||||
"""Faz o papel das três CLIs. `behavior[provider]` = "ok", "content" (resposta sem JSON) ou um texto de erro
|
||||
(sai com código 1 e esse texto no stderr)."""
|
||||
|
||||
def __init__(self, behavior: dict[str, str]):
|
||||
self.behavior = behavior
|
||||
self.calls: list[dict] = []
|
||||
|
||||
def run(self, args, input=None, capture_output=True, timeout=None, cwd=None, creationflags=0, env=None):
|
||||
provider = args[0]
|
||||
self.calls.append({"provider": provider, "args": list(args), "env": dict(env or {}), "cwd": cwd,
|
||||
"stdin": (input or b"").decode("utf-8"),
|
||||
"files": sorted(p.name for p in Path(cwd).iterdir()) if cwd else []})
|
||||
mode = self.behavior.get(provider, "ok")
|
||||
if mode not in ("ok", "content"):
|
||||
return subprocess.CompletedProcess(args, 1, b"", mode.encode("utf-8"))
|
||||
answer = VERDICT if mode == "ok" else None
|
||||
if provider == "codex":
|
||||
out = Path(args[args.index("-o") + 1])
|
||||
out.write_text(json.dumps(answer) if answer else "não sei", encoding="utf-8")
|
||||
return subprocess.CompletedProcess(args, 0, b"", b"")
|
||||
if provider == "claude":
|
||||
envelope = {"is_error": False, "structured_output": answer, "result": "" if answer else "não sei"}
|
||||
return subprocess.CompletedProcess(args, 0, json.dumps(envelope).encode(), b"")
|
||||
text = f"Aqui está:\n```json\n{json.dumps(answer)}\n```" if answer else "Não consegui."
|
||||
return subprocess.CompletedProcess(args, 0, json.dumps({"response": text, "stats": {}}).encode(), b"")
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def ai_dir(tmp_path):
|
||||
return tmp_path / "ai"
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def make_judge(tmp_path, ai_dir, monkeypatch):
|
||||
clock = {"t": 1_000_000.0}
|
||||
|
||||
def factory(behavior=None, provider="codex", model="", installed=("codex", "claude", "gemini")):
|
||||
cli = FakeCli(behavior or {})
|
||||
monkeypatch.setattr(judge_module.subprocess, "run", cli.run)
|
||||
for name in ("codex", "claude", "gemini"):
|
||||
monkeypatch.setattr(judge_module, f"find_{name}", (lambda n=name: [n] if n in installed else None))
|
||||
ai = AiConfig(ai_dir, cipher=ReversedCipher(), environ={"PATH": "x", "ANTHROPIC_API_KEY": "global",
|
||||
"GOOGLE_GENAI_USE_GCA": "true"})
|
||||
judge = Judge(provider, model, tmp_path / "judge", ai=ai, clock=lambda: clock["t"])
|
||||
judge.cli, judge.clock = cli, clock
|
||||
return judge
|
||||
|
||||
return factory
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- classificador
|
||||
@pytest.mark.parametrize("text", [
|
||||
"Error: 429 Too Many Requests", "You've hit your usage limit", "Your credit balance is too low",
|
||||
"API Error: 529 overloaded_error", "503 Service Unavailable", "Not logged in · Please run /login",
|
||||
"invalid api key", "IneligibleTierError: UNSUPPORTED_CLIENT", "connect ECONNREFUSED 127.0.0.1",
|
||||
"getaddrinfo ENOTFOUND api.openai.com", "network error", "a CLI passou de 240 s (tempo esgotado)",
|
||||
"Codex CLI não encontrado", "RESOURCE_EXHAUSTED: quota exceeded", "401 Unauthorized", "status 403",
|
||||
])
|
||||
def test_availability_errors(text):
|
||||
assert is_availability_error(text)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("text", ["", "o Codex não devolveu o JSON pedido", "resposta sem os campos ['title']",
|
||||
"Expecting value: line 1 column 1", "schema validation failed"])
|
||||
def test_content_errors_are_not_availability(text):
|
||||
assert not is_availability_error(text)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- settings.json e cofre
|
||||
def test_settings_default_when_missing_or_invalid(ai_dir):
|
||||
config = AiConfig(ai_dir, cipher=ReversedCipher())
|
||||
assert config.settings() == DEFAULT_SETTINGS
|
||||
ai_dir.mkdir(parents=True)
|
||||
(ai_dir / "settings.json").write_text("{quebrado", encoding="utf-8")
|
||||
assert AiConfig(ai_dir).settings() == DEFAULT_SETTINGS
|
||||
assert DEFAULT_SETTINGS["providers"]["gemini"] == {"enabled": False, "authMode": "apiKey"}
|
||||
|
||||
|
||||
def test_settings_normalized_field_by_field():
|
||||
data = normalize_settings({"providers": {"gemini": {"enabled": True, "authMode": "senha"}, "gpt": {}},
|
||||
"order": ["gemini", "gpt", "gemini"], "fallback": {"enabled": False, "cooldownMin": -3}})
|
||||
assert data["providers"]["gemini"] == {"enabled": True, "authMode": "apiKey"} # modo inválido fica no padrão
|
||||
assert data["order"] == ["gemini", "claude", "codex"] # desconhecido sai, faltantes vão para o fim
|
||||
assert data["fallback"] == {"enabled": False, "cooldownMin": 15.0}
|
||||
|
||||
|
||||
def test_settings_reread_when_mtime_changes(ai_dir):
|
||||
config = AiConfig(ai_dir)
|
||||
write_settings(ai_dir, settings_with(gemini={"enabled": True}))
|
||||
assert config.settings()["providers"]["gemini"]["enabled"] is True
|
||||
write_settings(ai_dir, settings_with(gemini={"enabled": False}, claude={"authMode": "apiKey"}))
|
||||
assert config.settings()["providers"]["gemini"]["enabled"] is False
|
||||
assert config.settings()["providers"]["claude"]["authMode"] == "apiKey"
|
||||
|
||||
|
||||
def test_env_per_auth_mode(ai_dir):
|
||||
environ = {"PATH": "x", "ANTHROPIC_API_KEY": "global", "CODEX_API_KEY": "global", "GEMINI_API_KEY": "global",
|
||||
"GOOGLE_GENAI_USE_GCA": "true"}
|
||||
config = AiConfig(ai_dir, cipher=ReversedCipher(), environ=environ)
|
||||
write_vault(ai_dir, {"claude": "sk-ant-1", "gemini": "AIza-2", "outro": "x"})
|
||||
# padrão: claude/codex em oauth (a variável sai), gemini em apiKey (a chave do cofre entra, GCA sai)
|
||||
claude, codex, gemini = (config.provider_env(p) for p in ("claude", "codex", "gemini"))
|
||||
assert "ANTHROPIC_API_KEY" not in claude and claude["PATH"] == "x"
|
||||
assert "CODEX_API_KEY" not in codex
|
||||
assert gemini["GEMINI_API_KEY"] == "AIza-2" and "GOOGLE_GENAI_USE_GCA" not in gemini
|
||||
write_settings(ai_dir, settings_with(claude={"authMode": "apiKey"}, gemini={"authMode": "oauth"}))
|
||||
assert config.provider_env("claude")["ANTHROPIC_API_KEY"] == "sk-ant-1"
|
||||
gemini = config.provider_env("gemini")
|
||||
assert gemini["GOOGLE_GENAI_USE_GCA"] == "true" and "GEMINI_API_KEY" not in gemini
|
||||
assert environ["ANTHROPIC_API_KEY"] == "global" # o ambiente do processo não muda
|
||||
assert config.api_keys() == {"claude": "sk-ant-1", "gemini": "AIza-2"}
|
||||
|
||||
|
||||
def test_unreadable_vault_means_no_keys(ai_dir):
|
||||
ai_dir.mkdir(parents=True)
|
||||
(ai_dir / "vault.bin").write_bytes(b"\x00lixo")
|
||||
config = AiConfig(ai_dir, cipher=ReversedCipher())
|
||||
assert config.api_keys() == {} and config.vault_error
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- cadeia de reserva
|
||||
def test_chain_skips_disabled_missing_cli_no_key_and_paused(make_judge, ai_dir):
|
||||
judge = make_judge(provider="codex")
|
||||
# padrão: gemini desligado → codex (escolhido) e depois claude
|
||||
assert judge.fallback_chain() == ["codex", "claude"]
|
||||
write_settings(ai_dir, settings_with(gemini={"enabled": True})) # ligado, mas sem chave no cofre
|
||||
assert judge.fallback_chain() == ["codex", "claude"]
|
||||
write_vault(ai_dir, {"gemini": "AIza"})
|
||||
assert judge.fallback_chain() == ["codex", "claude", "gemini"]
|
||||
judge.pause("claude", "429")
|
||||
assert judge.fallback_chain() == ["codex", "gemini"]
|
||||
judge.clock["t"] += 15 * 60 + 1 # a pausa vence
|
||||
assert judge.fallback_chain() == ["codex", "claude", "gemini"]
|
||||
write_settings(ai_dir, {**settings_with(gemini={"enabled": True}), "order": ["gemini", "codex", "claude"]})
|
||||
assert judge.fallback_chain() == ["codex", "gemini", "claude"]
|
||||
write_settings(ai_dir, {**settings_with(), "fallback": {"enabled": False, "cooldownMin": 15}})
|
||||
assert judge.fallback_chain() == ["codex"]
|
||||
write_settings(ai_dir, settings_with())
|
||||
assert make_judge(provider="codex", installed=("claude",)).fallback_chain() == ["claude"] # codex sem CLI
|
||||
|
||||
|
||||
def test_unavailable_switches_to_next_with_its_default_model_and_pauses(make_judge):
|
||||
judge = make_judge({"codex": "Error: 429 Too Many Requests"}, provider="codex", model="gpt-caro")
|
||||
verdict = judge.judge("prompt", 100, 170, lo=0, hi=300)
|
||||
assert [c["provider"] for c in judge.cli.calls] == ["codex", "claude"]
|
||||
assert verdict.model == f"claude:{DEFAULT_MODELS['claude']}" # quem de fato respondeu, com o modelo padrão dele
|
||||
claude_args = judge.cli.calls[1]["args"]
|
||||
assert claude_args[claude_args.index("--model") + 1] == "haiku"
|
||||
pauses = judge.describe()["pauses"]
|
||||
assert [p["provider"] for p in pauses] == ["codex"] and "429" in pauses[0]["reason"]
|
||||
# próxima chamada já pula o codex em pausa
|
||||
judge.cli.calls.clear()
|
||||
judge.judge("prompt", 100, 170, lo=0, hi=300)
|
||||
assert [c["provider"] for c in judge.cli.calls] == ["claude"]
|
||||
|
||||
|
||||
def test_content_error_does_not_switch(make_judge):
|
||||
judge = make_judge({"codex": "content"}, provider="codex")
|
||||
with pytest.raises(JudgeError) as info:
|
||||
judge.judge("prompt", 100, 170)
|
||||
assert info.value.unavailable is False
|
||||
assert [c["provider"] for c in judge.cli.calls] == ["codex"] and judge.pauses() == {}
|
||||
|
||||
|
||||
def test_all_fail_raises_summary(make_judge):
|
||||
judge = make_judge({"codex": "503 unavailable", "claude": "Not logged in"}, provider="codex")
|
||||
with pytest.raises(JudgeError) as info:
|
||||
judge.judge("prompt", 100, 170)
|
||||
message = str(info.value)
|
||||
assert "codex:" in message and "claude:haiku" in message and info.value.unavailable is True
|
||||
assert set(judge.pauses()) == {"codex", "claude"}
|
||||
|
||||
|
||||
def test_fallback_disabled_keeps_only_primary(make_judge, ai_dir):
|
||||
write_settings(ai_dir, {**settings_with(), "fallback": {"enabled": False, "cooldownMin": 15}})
|
||||
judge = make_judge({"codex": "429"}, provider="codex")
|
||||
with pytest.raises(JudgeError):
|
||||
judge.judge("prompt", 100, 170)
|
||||
assert [c["provider"] for c in judge.cli.calls] == ["codex"] and judge.pauses() == {}
|
||||
|
||||
|
||||
def test_primary_disabled_in_settings_is_skipped(make_judge, ai_dir):
|
||||
write_settings(ai_dir, settings_with(codex={"enabled": False}))
|
||||
judge = make_judge(provider="codex")
|
||||
assert judge.judge("prompt", 100, 170).model == "claude:haiku"
|
||||
assert judge.describe()["unavailableReason"] == "desligada em Configurações → IA"
|
||||
|
||||
|
||||
def test_describe_format(make_judge, ai_dir):
|
||||
judge = make_judge(provider="gemini", model="")
|
||||
write_settings(ai_dir, settings_with(gemini={"enabled": True}))
|
||||
write_vault(ai_dir, {"gemini": "AIza"})
|
||||
judge.pause("codex", "usage limit")
|
||||
data = judge.describe()
|
||||
assert data["provider"] == "gemini" and data["model"] == "gemini-3.5-flash" and data["authMode"] == "apiKey"
|
||||
assert data["fallback"] == {"enabled": True, "cooldownMin": 15.0, "chain": ["gemini", "claude"]}
|
||||
assert data["pauses"][0]["provider"] == "codex" and data["pauses"][0]["until"].endswith("+00:00")
|
||||
assert "gemini" in judge.models() and judge.models()["defaults"]["gemini"] == "gemini-3.5-flash"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- Gemini
|
||||
def test_gemini_call_args_images_and_env(make_judge, ai_dir, tmp_path):
|
||||
write_settings(ai_dir, settings_with(gemini={"enabled": True}))
|
||||
write_vault(ai_dir, {"gemini": "AIza-chave"})
|
||||
frames = []
|
||||
for i in range(2):
|
||||
frame = tmp_path / "frames" / f"clip1-{i}.JPG"
|
||||
frame.parent.mkdir(exist_ok=True)
|
||||
frame.write_bytes(b"jpg")
|
||||
frames.append(frame)
|
||||
judge = make_judge(provider="gemini", model="gemini-2.5-pro")
|
||||
verdict = judge.judge("PROMPT GRANDE", 100, 170, frames)
|
||||
call = judge.cli.calls[0]
|
||||
args = call["args"]
|
||||
assert args[:2] == ["gemini", "-p"] and "@frame-01.jpg @frame-02.jpg" in args[2]
|
||||
assert args[args.index("-o") + 1] == "json" and args[args.index("--approval-mode") + 1] == "plan"
|
||||
assert "--skip-trust" in args and args[args.index("-m") + 1] == "gemini-2.5-pro"
|
||||
assert "PROMPT GRANDE" in call["stdin"] and '"start_s"' in call["stdin"] and "PROMPT GRANDE" not in args[2]
|
||||
assert call["files"] == ["frame-01.jpg", "frame-02.jpg"] # imagens copiadas para a pasta de trabalho
|
||||
assert call["env"]["GEMINI_API_KEY"] == "AIza-chave" and "GOOGLE_GENAI_USE_GCA" not in call["env"]
|
||||
assert verdict.model == "gemini:gemini-2.5-pro" and verdict.title == "Virada"
|
||||
|
||||
|
||||
def test_extract_json_object_tolerates_fences_and_prose():
|
||||
assert extract_json_object('```json\n{"a": 1}\n```') == {"a": 1}
|
||||
assert extract_json_object('Claro! {"a": {"b": [1, 2]}} espero ter ajudado') == {"a": {"b": [1, 2]}}
|
||||
assert extract_json_object("o conjunto {x} e depois {\"ok\": true}") == {"ok": True}
|
||||
assert extract_json_object("sem json") is None and extract_json_object("") is None
|
||||
|
||||
|
||||
def test_parse_gemini_output():
|
||||
assert parse_gemini_output(json.dumps({"response": '```json\n{"keep": true}\n```', "stats": {}})) == {"keep": True}
|
||||
with pytest.raises(JudgeError) as info:
|
||||
parse_gemini_output(json.dumps({"response": "não deu"}))
|
||||
assert info.value.unavailable is False
|
||||
with pytest.raises(JudgeError) as info:
|
||||
parse_gemini_output(json.dumps({"error": {"type": "Error", "message": "429 RESOURCE_EXHAUSTED quota"}}))
|
||||
assert info.value.unavailable is None and is_availability_error(str(info.value))
|
||||
assert set(VERDICT) == set(VERDICT_SCHEMA["required"])
|
||||
|
||||
|
||||
def test_find_gemini_runs_bundle_with_node_on_windows(tmp_path, monkeypatch):
|
||||
npm = tmp_path / "npm"
|
||||
bundle = npm / "node_modules" / "@google" / "gemini-cli" / "bundle" / "gemini.js"
|
||||
bundle.parent.mkdir(parents=True)
|
||||
bundle.write_text("//", encoding="utf-8")
|
||||
monkeypatch.delenv("GEMINI_BIN", raising=False)
|
||||
monkeypatch.setattr(judge_module.sys, "platform", "win32")
|
||||
which = {"gemini.cmd": str(npm / "gemini.cmd"), "node": "C:/node/node.exe"}
|
||||
monkeypatch.setattr(judge_module.shutil, "which", lambda name: which.get(name))
|
||||
assert judge_module.find_gemini() == ["C:/node/node.exe", str(bundle)]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- API
|
||||
def test_api_accepts_gemini(env): # noqa: F811
|
||||
client, engine = env
|
||||
r = client.put("/v1/judge", json={"provider": "gemini", "model": "", "minScore": 6}, headers=auth())
|
||||
assert r.status_code == 200
|
||||
body = r.json()
|
||||
assert body["provider"] == "gemini" and body["model"] == "gemini-3.5-flash" and "gemini" in body["models"]
|
||||
assert "chain" in body["fallback"] and isinstance(body["pauses"], list)
|
||||
@@ -0,0 +1,187 @@
|
||||
"""Perfis de jogo bilíngues (doc/clipador/JOGOS.md): inglês para a IA, português para ler, missões, gatilhos de fim,
|
||||
outros nomes, cadastro pelo painel e sementes."""
|
||||
import json
|
||||
|
||||
from app.intel import clean_profile
|
||||
from app.judge import JudgeError
|
||||
from tests.test_sources_and_api import FakeJudge, auth, env, seed_session # noqa: F401 - fixture reaproveitada
|
||||
|
||||
EN = {
|
||||
"name": "Grand Theft Auto VI", "aliases": ["GTA 6", "GTA VI"], "summary": "Open-world crime game in Leonida.",
|
||||
"genre": "Action", "mechanics": ["heists"], "clip_worthy": ["police chase ends in a crash"], "avoid": ["menus"],
|
||||
"jargon": ["wanted level"], "news": ["Released Nov 2026"], "hashtags": ["#GTA6"], "sources": ["https://example.com"],
|
||||
"missions": [{"name": "Hometown", "chapter": "Prologue", "summary": "Lucia and Jason meet.",
|
||||
"completion_triggers": ["MISSION PASSED banner"]}],
|
||||
"end_triggers": ["MISSION PASSED", "WASTED"],
|
||||
}
|
||||
|
||||
|
||||
def to_pt(profile: dict) -> dict:
|
||||
"""Tradução falsa: marca os textos traduzíveis com [pt] e mantém o resto, como o TRANSLATE_SYSTEM pede."""
|
||||
out = json.loads(json.dumps(profile))
|
||||
out["summary"] = "[pt] " + out["summary"]
|
||||
out["clip_worthy"] = ["[pt] " + x for x in out["clip_worthy"]]
|
||||
for m in out["missions"]:
|
||||
m["summary"] = "[pt] " + m["summary"]
|
||||
return out
|
||||
|
||||
|
||||
class BilingualJudge(FakeJudge):
|
||||
def __init__(self, fail_translate=False):
|
||||
super().__init__()
|
||||
self.fail_translate = fail_translate
|
||||
self.translations: list[str] = []
|
||||
|
||||
def research_game(self, name, live_title="", notes=None):
|
||||
return {**EN, "name": name}
|
||||
|
||||
def translate_game(self, profile, target):
|
||||
self.translations.append(target)
|
||||
if self.fail_translate:
|
||||
raise JudgeError("cota acabou")
|
||||
if target == "pt-BR":
|
||||
return to_pt(profile)
|
||||
back = json.loads(json.dumps(profile))
|
||||
back["summary"] = "[en] " + back["summary"]
|
||||
return back
|
||||
|
||||
def refine_game(self, name, profile, instruction, search=True, section="", history=None):
|
||||
return {**profile, "end_triggers": [*profile["end_triggers"], "Reward screen"], "reply": "Acrescentei a tela de recompensa."}
|
||||
|
||||
|
||||
def add(engine, name="Grand Theft Auto VI"):
|
||||
engine.db.run("INSERT INTO games (id, name, status) VALUES (?, ?, 'pending')",
|
||||
name.lower().replace(" ", "-"), name)
|
||||
return name.lower().replace(" ", "-")
|
||||
|
||||
|
||||
def test_research_stores_english_for_ai_and_portuguese_for_reading(env): # noqa: F811
|
||||
client, engine = env
|
||||
engine.judge = BilingualJudge()
|
||||
gid = add(engine)
|
||||
engine.intel.research(gid)
|
||||
game = client.get("/v1/games", headers=auth()).json()["games"][0]
|
||||
assert game["status"] == "ready" and game["aiLanguage"] == "en-US" and game["translatedAt"]
|
||||
assert game["profileAi"]["summary"] == EN["summary"]
|
||||
assert game["profile"]["summary"].startswith("[pt] ")
|
||||
# Nome oficial da missão e hashtags não mudam na tradução.
|
||||
assert game["profile"]["missions"][0]["name"] == "Hometown" and game["profile"]["hashtags"] == ["#GTA6"]
|
||||
assert game["aliases"] == ["gta-6", "gta-vi"]
|
||||
# A IA lê o inglês.
|
||||
assert engine.intel.profile("Grand Theft Auto VI")["summary"] == EN["summary"]
|
||||
|
||||
|
||||
def test_failed_translation_keeps_english_in_both_and_explains(env): # noqa: F811
|
||||
client, engine = env
|
||||
engine.judge = BilingualJudge(fail_translate=True)
|
||||
gid = add(engine)
|
||||
engine.intel.research(gid)
|
||||
game = client.get("/v1/games", headers=auth()).json()["games"][0]
|
||||
assert game["status"] == "ready" and "tradução falhou" in game["error"]
|
||||
assert game["profile"]["summary"] == EN["summary"] and game["translatedAt"] is None
|
||||
|
||||
|
||||
def test_manual_save_in_portuguese_translates_to_english(env): # noqa: F811
|
||||
client, engine = env
|
||||
engine.judge = BilingualJudge()
|
||||
gid = add(engine)
|
||||
engine.intel.research(gid)
|
||||
pt = to_pt(EN)
|
||||
pt["summary"] = "Jogo de crime em Leonida, editado por mim."
|
||||
r = client.put(f"/v1/games/{gid}", json=pt, headers=auth())
|
||||
assert r.status_code == 200
|
||||
game = r.json()["games"][0]
|
||||
assert game["profile"]["summary"] == "Jogo de crime em Leonida, editado por mim."
|
||||
assert game["profileAi"]["summary"] == "[en] Jogo de crime em Leonida, editado por mim." and game["editedAt"]
|
||||
assert engine.judge.translations[-1] == "en-US"
|
||||
# Editar a versão da IA direto (lang=en) traduz para português.
|
||||
r = client.put(f"/v1/games/{gid}?lang=en", json=EN, headers=auth())
|
||||
assert r.json()["games"][0]["profileAi"]["summary"] == EN["summary"]
|
||||
assert engine.judge.translations[-1] == "pt-BR"
|
||||
|
||||
|
||||
def test_refine_applies_on_english_and_replies_in_portuguese(env): # noqa: F811
|
||||
client, engine = env
|
||||
engine.judge = BilingualJudge()
|
||||
gid = add(engine)
|
||||
engine.intel.research(gid)
|
||||
r = client.post(f"/v1/games/{gid}/refine", json={"instruction": "acrescente a tela de recompensa", "section": "end_triggers"},
|
||||
headers=auth())
|
||||
assert r.status_code == 200 and r.json()["reply"] == "Acrescentei a tela de recompensa."
|
||||
game = r.json()["games"][0]
|
||||
assert "Reward screen" in game["profileAi"]["end_triggers"] and "Reward screen" in game["profile"]["end_triggers"]
|
||||
|
||||
|
||||
def test_context_uses_english_profile_with_missions_and_end_triggers(env): # noqa: F811
|
||||
client, engine = env
|
||||
engine.judge = BilingualJudge()
|
||||
engine.intel.research(add(engine))
|
||||
sid = seed_session(engine)
|
||||
# Categoria por outro nome ("GTA 6") cai no mesmo perfil.
|
||||
engine.db.run("UPDATE sessions SET game = 'GTA 6' WHERE id = ?", sid)
|
||||
context = engine.intel.context(engine.db.get("SELECT * FROM sessions WHERE id = ?", sid))
|
||||
assert EN["summary"] in context and "MISSION PASSED; WASTED" in context
|
||||
assert "Hometown (fim: MISSION PASSED banner)" in context and "termine o corte logo depois do gatilho" in context
|
||||
|
||||
|
||||
def test_mission_list_in_prompt_is_capped():
|
||||
from app.judge import mission_lines
|
||||
profile = clean_profile({"missions": [{"name": f"Mission number {i}", "completion_triggers": ["MISSION PASSED"]}
|
||||
for i in range(110)]})
|
||||
lines = mission_lines(profile)
|
||||
assert len(profile["missions"]) == 110
|
||||
missions = next(line for line in lines if line.startswith("Missões"))
|
||||
assert "…e mais" in missions and len(missions) < 1700
|
||||
|
||||
|
||||
def test_add_game_conflicts_by_alias_and_delete(env): # noqa: F811
|
||||
client, engine = env
|
||||
engine.judge = BilingualJudge()
|
||||
engine.intel.research(add(engine))
|
||||
r = client.post("/v1/games", json={"name": "GTA 6"}, headers=auth())
|
||||
assert r.status_code == 409 and "já está na lista" in r.json()["error"]
|
||||
r = client.post("/v1/games", json={"name": "Hollow Knight: Silksong", "notes": "foco em chefes"}, headers=auth())
|
||||
assert r.status_code == 201 and r.json()["id"] == "hollow-knight-silksong"
|
||||
new = next(g for g in r.json()["games"] if g["id"] == "hollow-knight-silksong")
|
||||
assert new["notes"][0]["text"] == "foco em chefes"
|
||||
r = client.delete("/v1/games/hollow-knight-silksong", headers=auth())
|
||||
assert r.status_code == 200 and all(g["id"] != "hollow-knight-silksong" for g in r.json()["games"])
|
||||
assert client.delete("/v1/games/nao-existe", headers=auth()).status_code == 404
|
||||
|
||||
|
||||
def test_translate_route_makes_ai_version_for_old_games(env): # noqa: F811
|
||||
client, engine = env
|
||||
engine.judge = BilingualJudge()
|
||||
engine.db.run("INSERT INTO games (id, name, status, profile_json) VALUES ('rob-run', 'ROB RUN', 'ready', ?)",
|
||||
json.dumps(clean_profile({"name": "ROB RUN", "summary": "Jogo de assalto."})))
|
||||
assert client.get("/v1/games", headers=auth()).json()["games"][0]["profileAi"] is None
|
||||
r = client.post("/v1/games/rob-run/translate", headers=auth())
|
||||
assert r.status_code == 200 and r.json()["games"][0]["profileAi"]["summary"] == "[en] Jogo de assalto."
|
||||
|
||||
|
||||
def test_seeds_import_once_and_never_overwrite(env, tmp_path): # noqa: F811
|
||||
_, engine = env
|
||||
folder = tmp_path / "seeds"
|
||||
folder.mkdir()
|
||||
(folder / "game.json").write_text(json.dumps({
|
||||
"name": "Seed Game", "aliases": ["SG"], "researchedAt": "2026-11-18T00:00:00+00:00", "sources": ["https://a"],
|
||||
"profileAi": {"summary": "English summary", "missions": [{"name": "M1"}]},
|
||||
"profile": {"summary": "Resumo em português", "missions": [{"name": "M1"}]},
|
||||
}), encoding="utf-8")
|
||||
assert engine.intel.import_seeds(folder) == ["seed-game"]
|
||||
row = engine.db.get("SELECT * FROM games WHERE id = 'seed-game'")
|
||||
assert row["status"] == "ready" and row["model"] == "seed"
|
||||
assert json.loads(row["profile_ai_json"])["aliases"] == ["SG"] and json.loads(row["profile_json"])["sources"] == ["https://a"]
|
||||
assert engine.intel.profile("SG")["summary"] == "English summary"
|
||||
engine.db.run("UPDATE games SET profile_json = '{\"summary\": \"editado\"}' WHERE id = 'seed-game'")
|
||||
assert engine.intel.import_seeds(folder) == []
|
||||
assert json.loads(engine.db.get("SELECT profile_json FROM games WHERE id = 'seed-game'")["profile_json"])["summary"] == "editado"
|
||||
|
||||
|
||||
def test_category_by_alias_does_not_create_duplicate_game(env): # noqa: F811
|
||||
_, engine = env
|
||||
engine.judge = BilingualJudge()
|
||||
engine.intel.research(add(engine))
|
||||
sid = seed_session(engine)
|
||||
engine.intel.set_game(sid, "GTA VI", "platform")
|
||||
assert [r["id"] for r in engine.db.all("SELECT id FROM games")] == ["grand-theft-auto-vi"]
|
||||
@@ -0,0 +1,170 @@
|
||||
"""Parar à mão pausa o monitor da fonte (reclamação de 18/11/2026: 60 s depois de "Parar" o monitor abria uma sessão
|
||||
nova, porque a live continuava no ar) e idioma por fonte/sessão (transcrição e textos da IA em outro idioma)."""
|
||||
from dataclasses import replace
|
||||
|
||||
import pytest
|
||||
|
||||
import app.worker as worker_module
|
||||
from app.judge import output_language_note
|
||||
|
||||
from .test_sources_and_api import auth, env # noqa: F401 - fixture reaproveitada
|
||||
|
||||
URL = "https://www.twitch.tv/alanzoka"
|
||||
CHANNEL = "twitch-alanzoka"
|
||||
|
||||
|
||||
class FakeCapture:
|
||||
"""Captura falsa: `stop` avisa o motor como a real faz ao terminar (sai de `captures`, senão não dá para retomar)."""
|
||||
def __init__(self, eng, session_id, source, workdir, start_idx=0):
|
||||
self.eng, self.session_id = eng, session_id
|
||||
self.chat = None
|
||||
|
||||
def start(self):
|
||||
pass
|
||||
|
||||
def stop(self):
|
||||
self.eng.capture_finished(self.session_id)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def ready(env, monkeypatch): # noqa: F811
|
||||
"""Serviço com ferramentas "achadas", captura falsa e a live sempre no ar (sem Streamlink de verdade)."""
|
||||
client, engine = env
|
||||
monkeypatch.setattr(engine, "settings", replace(engine.settings, streamlink="streamlink", ffmpeg="ffmpeg"))
|
||||
monkeypatch.setattr(worker_module, "Capture", FakeCapture)
|
||||
monkeypatch.setattr(engine, "_fill_title", lambda *_a, **_k: None)
|
||||
# A pasta de dados do teste fica fora do repositório: o caminho relativo da sessão não importa aqui.
|
||||
monkeypatch.setattr(worker_module, "rel", lambda path: path.as_posix())
|
||||
engine.check_live = lambda url: (True, "live no ar")
|
||||
return client, engine
|
||||
|
||||
|
||||
def channel(client):
|
||||
return next(c for c in client.get("/v1/channels", headers=auth()).json()["channels"] if c["id"] == CHANNEL)
|
||||
|
||||
|
||||
def test_stop_by_hand_pauses_monitor_until_relit(ready):
|
||||
client, engine = ready
|
||||
assert client.post("/v1/channels", json={"url": URL}, headers=auth()).status_code == 201
|
||||
started = engine.monitor_once()
|
||||
assert len(started) == 1
|
||||
sid = started[0]
|
||||
assert channel(client)["monitorPausedAt"] is None
|
||||
|
||||
# Parar sem corpo (painel antigo) = pausa o monitor da fonte.
|
||||
assert client.post(f"/v1/sessions/{sid}/stop", headers=auth()).json() == {"ok": True}
|
||||
c = channel(client)
|
||||
assert c["monitor"] is True and c["monitorPausedAt"] and c["monitorPausedBySession"] == sid
|
||||
assert engine.db.get("SELECT status FROM sessions WHERE id = ?", sid)["status"] == "stopped"
|
||||
# A live continua no ar, mas o monitor NÃO abre sessão nova.
|
||||
assert engine.monitor_once() == []
|
||||
assert engine.db.get("SELECT COUNT(*) AS n FROM sessions")["n"] == 1
|
||||
|
||||
# "Religar" = PATCH monitor=true limpa a pausa; a próxima passada grava de novo.
|
||||
r = client.patch(f"/v1/channels/{CHANNEL}", json={"monitor": True}, headers=auth())
|
||||
assert r.json()["monitorPausedAt"] is None and r.json()["monitorPausedBySession"] is None
|
||||
assert len(engine.monitor_once()) == 1
|
||||
|
||||
|
||||
def test_stop_without_pause_keeps_monitor(ready):
|
||||
client, engine = ready
|
||||
client.post("/v1/channels", json={"url": URL}, headers=auth())
|
||||
sid = engine.monitor_once()[0]
|
||||
client.post(f"/v1/sessions/{sid}/stop", json={"pauseMonitor": False}, headers=auth())
|
||||
assert channel(client)["monitorPausedAt"] is None
|
||||
assert len(engine.monitor_once()) == 1 # a live segue no ar: grava de novo (você pediu assim)
|
||||
|
||||
|
||||
def test_recording_by_link_or_resuming_relights_monitor(ready):
|
||||
client, engine = ready
|
||||
client.post("/v1/channels", json={"url": URL}, headers=auth())
|
||||
sid = engine.monitor_once()[0]
|
||||
client.post(f"/v1/sessions/{sid}/stop", headers=auth())
|
||||
assert channel(client)["monitorPausedAt"]
|
||||
|
||||
# Gravar pelo link à mão: você ligou de propósito → a pausa some.
|
||||
r = client.post("/v1/sessions", json={"url": URL}, headers=auth())
|
||||
assert r.status_code == 201 and r.json()["id"] != sid
|
||||
assert channel(client)["monitorPausedAt"] is None
|
||||
|
||||
# Parar de novo e retomar pelo painel também religa.
|
||||
client.post(f"/v1/sessions/{r.json()['id']}/stop", headers=auth())
|
||||
assert channel(client)["monitorPausedAt"]
|
||||
assert client.post(f"/v1/sessions/{r.json()['id']}/resume", headers=auth()).status_code == 200
|
||||
assert channel(client)["monitorPausedAt"] is None
|
||||
|
||||
|
||||
def test_deleting_a_session_does_not_pause(ready):
|
||||
client, engine = ready
|
||||
client.post("/v1/channels", json={"url": URL}, headers=auth())
|
||||
sid = engine.monitor_once()[0]
|
||||
assert client.delete(f"/v1/sessions/{sid}", headers=auth()).status_code == 204
|
||||
assert channel(client)["monitorPausedAt"] is None
|
||||
|
||||
|
||||
def test_unmonitored_channel_is_not_paused(ready):
|
||||
client, engine = ready
|
||||
client.post("/v1/channels", json={"url": URL, "monitor": False}, headers=auth())
|
||||
sid = client.post("/v1/sessions", json={"url": URL}, headers=auth()).json()["id"]
|
||||
client.post(f"/v1/sessions/{sid}/stop", headers=auth())
|
||||
assert channel(client)["monitorPausedAt"] is None # nada a pausar: o monitor já estava desligado
|
||||
|
||||
|
||||
# ---------- idioma
|
||||
|
||||
def test_language_on_channel_and_session(ready):
|
||||
client, engine = ready
|
||||
default = engine.settings.language
|
||||
r = client.post("/v1/channels", json={"url": URL, "language": "en-US"}, headers=auth())
|
||||
assert r.status_code == 201 and r.json()["language"] == "en-US"
|
||||
assert client.post("/v1/channels", json={"url": "https://kick.com/gaules", "language": "xx"}, headers=auth()).status_code == 400
|
||||
r2 = client.post("/v1/channels", json={"url": "https://kick.com/gaules"}, headers=auth())
|
||||
assert r2.json()["language"] == default # sem idioma = padrão do serviço, já resolvido na visão
|
||||
|
||||
# A sessão herda o idioma da fonte; `language` explícito vence; VOD solto fica no padrão.
|
||||
s = client.post("/v1/sessions", json={"url": URL}, headers=auth()).json()
|
||||
assert s["language"] == "en-US"
|
||||
assert engine.db.get("SELECT language FROM sessions WHERE id = ?", s["id"])["language"] == "en-US"
|
||||
s2 = client.post("/v1/sessions", json={"url": "https://kick.com/gaules", "language": "es-419"}, headers=auth()).json()
|
||||
assert s2["language"] == "es-419"
|
||||
assert client.post("/v1/sessions", json={"url": URL, "language": "klingon"}, headers=auth()).status_code == 400
|
||||
|
||||
# PATCH troca ('' volta ao padrão) e não mexe quando ausente.
|
||||
assert client.patch(f"/v1/channels/{CHANNEL}", json={"displayName": "Alan"}, headers=auth()).json()["language"] == "en-US"
|
||||
assert client.patch(f"/v1/channels/{CHANNEL}", json={"language": ""}, headers=auth()).json()["language"] == default
|
||||
assert client.get("/v1/status", headers=auth()).json()["settings"]["language"] == default
|
||||
|
||||
|
||||
def test_language_note_reaches_the_ai_context(ready):
|
||||
client, engine = ready
|
||||
assert output_language_note("pt-BR") == "" and output_language_note("") == "" and output_language_note(None) == ""
|
||||
assert "English (US)" in output_language_note("en-US")
|
||||
client.post("/v1/channels", json={"url": URL, "language": "en-US"}, headers=auth())
|
||||
sid = client.post("/v1/sessions", json={"url": URL}, headers=auth()).json()["id"]
|
||||
gringa = engine.db.get("SELECT * FROM sessions WHERE id = ?", sid)
|
||||
assert "Idioma de saída: English (US)" in engine.intel.context(gringa)
|
||||
engine.db.run("UPDATE sessions SET language = '' WHERE id = ?", sid)
|
||||
assert "Idioma de saída" not in engine.intel.context(engine.db.get("SELECT * FROM sessions WHERE id = ?", sid))
|
||||
|
||||
|
||||
def test_transcription_uses_session_language(ready, monkeypatch):
|
||||
_client, engine = ready
|
||||
seen = {}
|
||||
|
||||
class FakeVoice:
|
||||
configured = True
|
||||
|
||||
def transcribe(self, wav, key, language=None):
|
||||
seen["language"] = language
|
||||
return []
|
||||
|
||||
monkeypatch.setattr(engine, "voice", FakeVoice())
|
||||
monkeypatch.setattr(worker_module.media, "decode_pcm", lambda *_a, **_k: b"")
|
||||
monkeypatch.setattr(worker_module.media, "loudness_per_second", lambda _pcm: [])
|
||||
monkeypatch.setattr(worker_module.media, "to_wav", lambda _pcm: b"")
|
||||
cur = engine.db.run("INSERT INTO sessions (platform, kind, url, status, dir, started_at, language) VALUES"
|
||||
" ('twitch', 'live', ?, 'processing', '', '2026-11-18T00:00:00+00:00', 'en-US')", URL)
|
||||
sid = cur.lastrowid
|
||||
engine.db.run("INSERT INTO segments (session_id, idx, file, start_s, end_s, wall_end) VALUES (?, 0, 'x/seg.ts', 0, 30, 0)", sid)
|
||||
engine.analyze_segment(engine.db.get("SELECT * FROM segments WHERE session_id = ?", sid))
|
||||
assert seen["language"] == "en-US"
|
||||
Reference in New Issue
Block a user