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:
+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