Clipador: fontes em inglês (juízes em inglês, painel em português) e monitor de uso da IA
Clipador em inglês (doc/clipador/IDIOMAS.md):
- Fonte en-US: analista, editor e varredura com prompts, glossário de chat e saída em inglês;
a mesma resposta traz o bloco `pt` (tradução para o painel, sem chamada extra).
- Fala do corte traduzida por frase (clips.translation_json, migração v13) e
POST /v1/clips/{id}/translate.
- caption.translation (só para desenvolver): português embaixo da legenda em inglês.
- Risada e gírias do chat em inglês na heurística (LMAO, LOL, 💀, 😭, no way, bruh...).
- Idioma do público → código do Whisper (en-US dava 422 no serviço de voz).
- Painel: bloco "Em português" no corte, análise/resumo em PT, título traduzido na lista,
coluna "Ao vivo" mostra a gravação ativa da fonte.
IA: monitor de uso do limite (ai-usage) e 4º provedor (Antigravity CLI).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -19,6 +19,8 @@ import logging
|
||||
import os
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from typing import Protocol
|
||||
|
||||
@@ -29,6 +31,8 @@ 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"
|
||||
# Leitura de uso mais velha que isso não decide (o painel relê a cada 5 min).
|
||||
USAGE_STALE_S = 30 * 60
|
||||
AUTH_MODES = ("oauth", "apiKey")
|
||||
DEFAULT_COOLDOWN_MIN = 15.0
|
||||
DEFAULT_SETTINGS: dict = {
|
||||
@@ -180,6 +184,43 @@ class AiConfig:
|
||||
def provider(self, name: str) -> dict:
|
||||
return self.settings()["providers"].get(name, {"enabled": False, "authMode": "oauth"})
|
||||
|
||||
@property
|
||||
def usage_path(self) -> Path:
|
||||
return self.folder / "usage.json"
|
||||
|
||||
def over_limit(self, provider: str, now: float | None = None) -> str | None:
|
||||
"""Motivo para a IA sair da frente pelo USO (None = livre), lido de data/ai/usage.json, que o painel grava
|
||||
a cada 5 min (Claude pelo /usage, Codex pelo app-server; ver doc/ia.md). Mesma regra do painel
|
||||
(`overLimit` em lib/ai.ts): bateu o limite, ou uma janela ainda valendo em `limitPercent` ou mais.
|
||||
Leitura com mais de 30 min, arquivo ausente ou inválido: não decide nada."""
|
||||
now = time.time() if now is None else now
|
||||
try:
|
||||
data = json.loads(self.usage_path.read_text(encoding="utf-8"))
|
||||
usage = data["providers"][provider]
|
||||
at = datetime.fromisoformat(str(usage["at"]).replace("Z", "+00:00")).timestamp()
|
||||
except (OSError, ValueError, KeyError, TypeError):
|
||||
return None
|
||||
if now - at > USAGE_STALE_S:
|
||||
return None
|
||||
live = []
|
||||
for window in usage.get("windows") or []:
|
||||
resets = window.get("resetsAt")
|
||||
try:
|
||||
if resets and datetime.fromisoformat(str(resets).replace("Z", "+00:00")).timestamp() <= now:
|
||||
continue
|
||||
live.append((str(window.get("label", "janela")), float(window.get("usedPercent", 0))))
|
||||
except (ValueError, TypeError):
|
||||
continue
|
||||
hit = [label for label, used in live if used >= 100]
|
||||
if usage.get("blocked") and hit:
|
||||
return f"bateu o limite ({', '.join(hit)})"
|
||||
try:
|
||||
limit = float(data.get("limitPercent", 90))
|
||||
except (TypeError, ValueError):
|
||||
limit = 90.0
|
||||
hot = sorted((w for w in live if w[1] >= limit), key=lambda w: -w[1])
|
||||
return f"{hot[0][0]} em {round(hot[0][1])}% (limite {round(limit)}%)" if hot else None
|
||||
|
||||
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:
|
||||
|
||||
@@ -207,6 +207,11 @@ SCHEMA = [
|
||||
ALTER TABLE games ADD COLUMN translated_at TEXT;
|
||||
ALTER TABLE games ADD COLUMN aliases_json TEXT NOT NULL DEFAULT '[]';
|
||||
""",
|
||||
# v13: fonte em inglês (doc/clipador/IDIOMAS.md): a fala do corte em frases com tempo + tradução em português,
|
||||
# para o painel e para a legenda de desenvolvimento (inglês em cima, português embaixo). NULL = não traduzido.
|
||||
"""
|
||||
ALTER TABLE clips ADD COLUMN translation_json TEXT;
|
||||
""",
|
||||
]
|
||||
|
||||
|
||||
|
||||
@@ -112,7 +112,8 @@ def render_clip_edit(engine, clip: dict, session: dict, edit: dict, out: Path, t
|
||||
log.warning("capa do corte %s falhou: %s", clip["id"], exc)
|
||||
cover = None
|
||||
editor_render.render_project(ffmpeg, engine.settings.ffprobe, engine._encoder, segments, project, base, credit, out,
|
||||
REPO_ROOT, chat=chat_for(engine, project), cover_file=cover)
|
||||
REPO_ROOT, chat=chat_for(engine, project), cover_file=cover,
|
||||
translation=translation_for(engine, clip, project, base))
|
||||
total = editor.output_duration(project["cuts"])
|
||||
media.thumbnail(ffmpeg, out, min(3.0, total / 2), thumb)
|
||||
# Formato em que ESTE arquivo saiu (camadas padrão ← canal ← sessão ← projeto): a fila desenha o player por ele.
|
||||
@@ -120,6 +121,19 @@ def render_clip_edit(engine, clip: dict, session: dict, edit: dict, out: Path, t
|
||||
return cover.relative_to(REPO_ROOT).as_posix() if cover else None
|
||||
|
||||
|
||||
def translation_for(engine, clip: dict, project: dict, base: dict) -> list[dict] | None:
|
||||
"""Frases traduzidas para a legenda de desenvolvimento (doc/clipador/IDIOMAS.md): só com `caption.translation`
|
||||
ligado e fonte em inglês. Traduz o trecho do projeto se ainda não houver tradução que o cubra."""
|
||||
cfg = editor.effective_settings(base, project)
|
||||
if not cfg["caption"].get("translation"):
|
||||
return None
|
||||
ps = editor.pieces(project["cuts"])
|
||||
if not ps:
|
||||
return None
|
||||
data = engine.translate_clip(clip["id"], ps[0].start, ps[-1].end)
|
||||
return (data or {}).get("lines") or None
|
||||
|
||||
|
||||
def chat_for(engine, project: dict) -> list | None:
|
||||
"""Mensagens do chat da sessão para o bloco "chat na tela" (só quando o projeto pede)."""
|
||||
if not (project.get("chat") or {}).get("enabled"):
|
||||
@@ -365,7 +379,8 @@ def register(app: FastAPI, engine, clip_view, get_clip) -> None:
|
||||
cover = None
|
||||
editor_render.render_project(ffmpeg, settings.ffprobe, ["-c:v", "libx264", "-preset", "veryfast", "-crf", "24"],
|
||||
segments, project, base, credit, out, REPO_ROOT,
|
||||
out_range=(a, b), timeout=180, chat=chat_for(engine, project), cover_file=cover)
|
||||
out_range=(a, b), timeout=180, chat=chat_for(engine, project), cover_file=cover,
|
||||
translation=translation_for(engine, clip, project, base))
|
||||
took = time.monotonic() - t
|
||||
return {"file": out.relative_to(REPO_ROOT).as_posix(), "fromS": a, "toS": b, "seconds": round(took, 1), "version": now()}
|
||||
|
||||
|
||||
@@ -200,9 +200,11 @@ def chat_events(project: dict, chat: list | None, total: float,
|
||||
|
||||
|
||||
def build_project_ass(project: dict, cfg: dict, credit: str, t0: float = 0.0, t1: float | None = None,
|
||||
chat: list | None = None) -> str:
|
||||
chat: list | None = None, translation: list[dict] | None = None) -> str:
|
||||
"""ASS do projeto em tempo de saída. [t0, t1] recorta a janela (prévia real de poucos segundos).
|
||||
`chat` = mensagens da sessão (ChatMessage) para o bloco de chat na tela, se o projeto pedir."""
|
||||
`chat` = mensagens da sessão (ChatMessage) para o bloco de chat na tela, se o projeto pedir.
|
||||
`translation` = frases da fala com tradução ({s, e, text, pt}, tempo da sessão; `clips.translation_json`):
|
||||
com `caption.translation` ligado, o português sai embaixo da legenda (só para desenvolver, IDIOMAS.md)."""
|
||||
cap, cred = cfg["caption"], cfg["credit"]
|
||||
total = output_duration(project["cuts"])
|
||||
t1 = total if t1 is None else min(t1, total)
|
||||
@@ -211,6 +213,11 @@ def build_project_ass(project: dict, cfg: dict, credit: str, t0: float = 0.0, t1
|
||||
credit_align, credit_side, credit_margin = layout.credit_placement(cfg)
|
||||
cw, ch = layout.canvas_size(cfg)
|
||||
font, size, ow = cap["font"], cap["size"], cap["outlineWidth"]
|
||||
# Legenda em português (desenvolvimento): metade do tamanho; o estilo só entra quando ligada (o ASS do vídeo
|
||||
# normal fica idêntico ao de antes).
|
||||
tsize = max(30, int(size * 0.5))
|
||||
trans_style = (f"Style: Trans,Arial,{tsize},&H00FFE79B,&H00FFE79B,&H00000000,&H80000000,-1,0,0,0,100,100,0,0,1,"
|
||||
f"{max(3, ow // 2)},2,8,60,60,0,1\n") if cap.get("translation") and translation else ""
|
||||
header = f"""[Script Info]
|
||||
ScriptType: v4.00+
|
||||
PlayResX: {cw}
|
||||
@@ -226,7 +233,7 @@ Style: Credit,Arial,{cred['size']},&H00FFFFFF,&H00FFFFFF,&H00000000,&H80000000,-
|
||||
Style: Text,Arial Black,64,&H00FFFFFF,&H00FFFFFF,&H00000000,&H80000000,-1,0,0,0,100,100,0,0,1,6,2,5,60,60,0,1
|
||||
Style: Box,Arial Black,64,&H00FFFFFF,&H00FFFFFF,&H004D1DE1,&H00000000,-1,0,0,0,100,100,0,0,3,18,0,5,60,60,0,1
|
||||
Style: Bar,Arial,10,&H00FFFFFF,&H00FFFFFF,&H00000000,&H00000000,0,0,0,0,100,100,0,0,1,0,0,7,0,0,0,1
|
||||
Style: Chat,Arial,{(project.get('chat') or {}).get('size', 34)},&H00FFFFFF,&H00FFFFFF,&H78000000,&H00000000,-1,0,0,0,100,100,0,0,3,5,0,1,0,0,0,1
|
||||
{trans_style}Style: Chat,Arial,{(project.get('chat') or {}).get('size', 34)},&H00FFFFFF,&H00FFFFFF,&H78000000,&H00000000,-1,0,0,0,100,100,0,0,3,5,0,1,0,0,0,1
|
||||
|
||||
[Events]
|
||||
Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text
|
||||
@@ -249,12 +256,17 @@ Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text
|
||||
pos = f"\\pos({cw // 2},{layout.caption_y(cfg)})"
|
||||
dodges = hook_dodges(project, (cw, ch), layout.caption_y(cfg), int(cap["size"]), total)
|
||||
|
||||
def at(t: float) -> str:
|
||||
"""Posição da legenda no instante t (saída): desviada enquanto um gancho a cobriria."""
|
||||
def y_at(t: float) -> int:
|
||||
"""Altura (centro) da legenda no instante t (saída): desviada enquanto um gancho a cobriria."""
|
||||
for s, e, y in dodges:
|
||||
if s <= t < e:
|
||||
return f"\\pos({cw // 2},{y})"
|
||||
return pos
|
||||
return y
|
||||
return layout.caption_y(cfg)
|
||||
|
||||
def at(t: float) -> str:
|
||||
"""Posição da legenda no instante t (saída)."""
|
||||
y = y_at(t)
|
||||
return pos if y == layout.caption_y(cfg) else f"\\pos({cw // 2},{y})"
|
||||
# Ênfase: palavra de saída ↔ palavra marcada no projeto (mesmo texto, mesmo instante), casada nos tempos
|
||||
# ORIGINAIS. Depois as palavras são saneadas (ordem, sem sobreposição, duração mínima) — `clean_words` devolve
|
||||
# a mesma quantidade, na mesma ordem — e os blocos abaixo nunca ficam dois na tela ao mesmo tempo.
|
||||
@@ -303,6 +315,17 @@ Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text
|
||||
intro = "\\fscx85\\fscy85\\t(0,90,\\fscx100\\fscy100)" if preset == "pop" and i == 0 else ""
|
||||
event(0, start, end, "Caption", f"{{{at(start)}{intro}}}" + " ".join(parts))
|
||||
|
||||
if cap.get("translation") and translation:
|
||||
# Só para desenvolver (doc/clipador/IDIOMAS.md): a frase traduzida em português, menor e em azul claro,
|
||||
# logo embaixo da legenda em inglês (\\an8 = cresce para baixo; \\q0 = quebra a linha se for longa).
|
||||
for line in translation:
|
||||
a, _ = to_output(float(line["s"]), project["cuts"])
|
||||
b, _ = to_output(float(line["e"]), project["cuts"])
|
||||
if b - a < 0.2 or not str(line.get("pt") or "").strip():
|
||||
continue
|
||||
y = y_at(a) + int(size * 0.62)
|
||||
event(0, a, b, "Trans", f"{{\\an8\\pos({cw // 2},{y})\\q0}}{_escape(str(line['pt']))}")
|
||||
|
||||
cuts = project["cuts"]
|
||||
for o in project["overlays"]:
|
||||
if o["kind"] in ("zoom", "inset"):
|
||||
@@ -586,7 +609,7 @@ def has_audio_stream(ffprobe: str | None, file: Path) -> bool:
|
||||
def render_project(ffmpeg: str, ffprobe: str | None, encoder: list[str], segments: list[tuple[Path, float, float]],
|
||||
project: dict, base_cfg: dict, credit: str, out_file: Path, repo_root: Path,
|
||||
out_range: tuple[float, float] | None = None, timeout: float = 900, chat: list | None = None,
|
||||
cover_file: Path | None = None) -> None:
|
||||
cover_file: Path | None = None, translation: list[dict] | None = None) -> None:
|
||||
"""Renderiza o projeto (ou só a saída [a, b] para a prévia real). `segments` = (arquivo, início, fim) da sessão.
|
||||
`chat` = mensagens da sessão (para o chat na tela); `cover_file` = capa já renderizada, posta nos 2 primeiros
|
||||
quadros quando o projeto pede (`cover.atStart`)."""
|
||||
@@ -605,7 +628,7 @@ def render_project(ffmpeg: str, ffprobe: str | None, encoder: list[str], segment
|
||||
stem = out_file.stem
|
||||
segs, uniform = uniform_segments(ffmpeg, ffprobe, segs, work, stem) # emenda de resolução/codec (retomada)
|
||||
ass_file = work / f"{stem}.ass"
|
||||
ass_text = build_project_ass(project, cfg, credit, t0, t1, chat)
|
||||
ass_text = build_project_ass(project, cfg, credit, t0, t1, chat, translation)
|
||||
ass_file.write_text(ass_text, encoding="utf-8")
|
||||
input0, concat = _concat_input(work, stem, segs, in0, in1 - in0)
|
||||
|
||||
|
||||
+19
-7
@@ -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, output_language_note
|
||||
from .judge import JudgeError, build_scan_prompt, game_context, lang_key, output_language_note
|
||||
from .scoring import fit_window
|
||||
from .sources import parse_source
|
||||
|
||||
@@ -470,12 +470,17 @@ class Intel:
|
||||
screen_profile = self.profile(screen) if screen.lower() not in ("", "desconhecido") else None
|
||||
return (screen, screen_profile) if screen_profile else (game or ("" if screen.lower() == "desconhecido" else screen), None)
|
||||
|
||||
def lang(self, session: dict) -> str:
|
||||
"""'en' = fonte em inglês (juízes em inglês, tradução para o painel); 'pt' = o resto."""
|
||||
return lang_key(session.get("language") or self.e.settings.language)
|
||||
|
||||
def context(self, session: dict) -> str:
|
||||
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", "")))
|
||||
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)
|
||||
" | ".join(m["summary"] for m in memory[-3:] if m.get("summary")), confirmed=confirmed,
|
||||
lang=self.lang(session))
|
||||
# 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
|
||||
@@ -635,10 +640,11 @@ class Intel:
|
||||
"SELECT start_s, end_s, title FROM clips WHERE session_id = ? AND end_s > ? AND start_s < ?", session["id"], back_lo, hi)]
|
||||
existing += clip_delete.mark_spans(self.e.db, session["id"], back_lo, hi) # apagados não voltam pela varredura
|
||||
prompt = build_scan_prompt(self.e.streamer_name(session), session["platform"], lo, hi, back_lo, tl["words"],
|
||||
tl["chat"], self.context(session), frames, existing, dur["minS"], dur["maxS"])
|
||||
tl["chat"], self.context(session), frames, existing, dur["minS"], dur["maxS"],
|
||||
lang=self.lang(session))
|
||||
created = 0
|
||||
try:
|
||||
data = self.e.judge.scan(prompt, [p for _, p in frames])
|
||||
data = self.e.judge.scan(prompt, [p for _, p in frames], lang=self.lang(session))
|
||||
self.last_scan_error = None
|
||||
except (JudgeError, json.JSONDecodeError) as exc:
|
||||
# Avança mesmo assim: repetir a mesma janela com a CLI quebrada só gastaria cota.
|
||||
@@ -655,10 +661,13 @@ class Intel:
|
||||
log.info("varredura %s %.0f–%.0fs: %d proposta(s), %d candidato(s)", session["id"], lo, hi, len(proposals), created)
|
||||
memory = loads(session.get("memory_json"), [])
|
||||
if data.get("summary") or proposals:
|
||||
memory.append({"fromS": lo, "toS": hi, "summary": str(data.get("summary") or "")[:240],
|
||||
"proposals": len(proposals), "created": created})
|
||||
item = {"fromS": lo, "toS": hi, "summary": str(data.get("summary") or "")[:240],
|
||||
"proposals": len(proposals), "created": created}
|
||||
if data.get("summary_pt"): # fonte em inglês: o resumo vai em inglês à IA e em português ao painel
|
||||
item["summaryPt"] = str(data["summary_pt"])[:240]
|
||||
memory.append(item)
|
||||
screen = str(data.get("screen_game") or "")
|
||||
if screen.lower() in ("desconhecido", "não identificável", "nao identificavel"):
|
||||
if screen.lower() in ("desconhecido", "não identificável", "nao identificavel", "unknown"):
|
||||
screen = ""
|
||||
self.e.db.run("UPDATE sessions SET scanned_until = ?, memory_json = ?, screen_game = CASE WHEN ? != '' THEN ? ELSE screen_game END WHERE id = ?",
|
||||
hi, json.dumps(memory[-MEMORY_KEEP:], ensure_ascii=False), screen, screen[:120], session["id"])
|
||||
@@ -684,6 +693,9 @@ class Intel:
|
||||
ts = now()
|
||||
reasons = {"via": "varredura", "scanFromS": lo, "scanToS": hi, "proposalScore": score,
|
||||
"proposalTitle": str(m.get("title", ""))[:100], "proposalReason": str(m.get("reason", ""))[:300]}
|
||||
pt = m.get("pt") if isinstance(m.get("pt"), dict) else {}
|
||||
if pt.get("title") or pt.get("reason"): # fonte em inglês: a mesma proposta em português para o painel
|
||||
reasons |= {"proposalTitlePt": str(pt.get("title", ""))[:100], "proposalReasonPt": str(pt.get("reason", ""))[:300]}
|
||||
self.e.db.run(
|
||||
"INSERT INTO clips (session_id, peak_s, start_s, end_s, score, source, reasons_json, status, created_at, updated_at)"
|
||||
" VALUES (?, ?, ?, ?, ?, 'ai', ?, 'candidate', ?, ?)",
|
||||
|
||||
+266
-51
@@ -30,7 +30,7 @@ import sys
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
from dataclasses import dataclass
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
|
||||
@@ -353,6 +353,8 @@ class Verdict:
|
||||
model: str
|
||||
# Tags DO MOMENTO (sem "#"), escolhidas pela IA; as do canal e do jogo o sistema põe (app/hashtags.py).
|
||||
hashtags: tuple[str, ...] = ()
|
||||
# Fonte em inglês: título, legenda e motivo traduzidos para o painel ({} = sessão em português).
|
||||
pt: dict = field(default_factory=dict)
|
||||
|
||||
|
||||
class JudgeError(RuntimeError):
|
||||
@@ -402,6 +404,163 @@ def extract_json_object(text: str, fences: bool = True) -> dict | None:
|
||||
return None
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- juízes em inglês (fonte gringa)
|
||||
# Pedido do dono (18/11/2026): "se a fonte está em inglês, os juízes trabalham em inglês". A equipe não fala inglês:
|
||||
# o vídeo (gancho, título, legenda, hashtags) sai em inglês e a MESMA resposta traz um bloco `pt` com a tradução
|
||||
# para o painel — sem chamada extra. Regras completas em doc/clipador/IDIOMAS.md.
|
||||
CLIP_GUIDE_EN = """What makes a good live-stream clip (market research, 2026):
|
||||
- Opens on the strong moment: viewers decide in 1–2 s. No "like I was saying".
|
||||
- Explains itself: someone who never saw the stream gets it in a few seconds (minimal context at the start).
|
||||
- Clip-worthy: strong reaction (jump scare, laughing fit, rage), insane play/comeback, funny fail, beef/drama, a story
|
||||
that unfolds, a memorable line, and NEW GAME INFO (mechanic, secret, news, comparison) — around launches
|
||||
(e.g. GTA 6) information is worth as much as a reaction.
|
||||
- Not clip-worthy: waiting, menus/loading, reading donations/ads, chatter with no hook, stream inside jokes.
|
||||
- TIMING: streamers usually comment AFTER the action. Go back to the start of the ACTION that triggered the
|
||||
comment (20 s to 2 min before the line, up to the backtrack limit given) — the clip must show action and reaction.
|
||||
- Tight ending: end right after the payoff (reaction/resolution)."""
|
||||
|
||||
CHAT_GLOSSARY_EN = """Common chat slang on English-speaking Twitch/Kick/YouTube (read it by context):
|
||||
- Laughing: "LUL", "LULW", "KEKW", "OMEGALUL", "ICANT", "pepeLaugh", "LMAO", "LMFAO", "LOL", "ROFL", "💀"/"☠️"
|
||||
("I'm dead" = so funny), "😭" (crying laughing), "dead", "I'm crying".
|
||||
- Shock/confusion: "HUH", "?????", "WTF", "OMG", "no way", "nah", "bruh", "monkaS"/"monkaW" (tension), "Aware",
|
||||
"Clueless" (ironic: he doesn't realise), "COPIUM" (denial), "Sadge" (sad).
|
||||
- Hype/praise: "Pog", "POGGERS", "PogU", "W"/"dub" (win), "L" (loss), "LETSGO", "Clap", "EZ", "GG", "clutch",
|
||||
"cracked" (very skilled), "goated", "sheesh", "diff" (skill gap).
|
||||
- "F" = death/loss; "cooked"/"he's cooked" = doomed; "throwing"/"sold" = blew it; "bot"/"NPC" = bad/robotic play.
|
||||
- "lag", "ping", "rubberbanding", "desync", "server dying" → the game/stream is lagging; the joke is the lag.
|
||||
- "clip it"/"CLIP IT" → clip request; "hacker"/"cheater"/"aimbot" → suspected cheating.
|
||||
- Channel emotes (streamer prefix + base emote, e.g. tfueLUL) carry the same reaction as the base emote."""
|
||||
|
||||
PT_NOTE = ("The team that reviews clips only reads Brazilian Portuguese: fill `pt` with a faithful Brazilian "
|
||||
"Portuguese translation of the listed fields (keep game terms, names and slang meaning; do not add facts).")
|
||||
|
||||
ANALYST_SYSTEM_EN = """You are the ANALYST of a live-stream clipping team. You do not write titles: you describe
|
||||
faithfully WHAT HAPPENED in the segment so the editor can decide. You get game context, a timed transcript (the
|
||||
streamer speaks English), screen FRAMES with their timestamps and the chat.
|
||||
|
||||
Cross-check all three sources before concluding: speech alone misleads (e.g. "I'm playing three games... I died, I
|
||||
died" plus chat "server dying?/LMAO" and the screen jumping = the game is lagging and he dies because of the lag).
|
||||
Chat reacts a few seconds after the event.
|
||||
|
||||
""" + CHAT_GLOSSARY_EN + """
|
||||
|
||||
Fields (in English):
|
||||
- situation: the moment type (one from the list; the ids are fixed, keep them as they are).
|
||||
- what_happened: 2–3 factual sentences of what happened, in order, no exaggeration.
|
||||
- screen: what the frames show (cite the frame #) — or "frames don't help".
|
||||
- speech: what the speech reveals (cite the timestamp).
|
||||
- chat_meaning: what chat is saying/laughing at and why.
|
||||
- confidence: 0–1, how sure you are (lower it when sources disagree).
|
||||
- action_start_s: second of the recording where the ACTION that caused the reaction starts (may be before the speech).
|
||||
- reaction_end_s: second where the reaction/payoff ends.
|
||||
- hook: what would hook someone in the first 2 seconds of the clip (English, it goes on screen).
|
||||
- pt: what_happened, screen, speech, chat_meaning and hook translated. """ + PT_NOTE + """
|
||||
Do not use tools beyond what was given. Answer only with the requested JSON."""
|
||||
|
||||
JUDGE_SYSTEM_EN = """You are the EDITOR of live-stream clips for Shorts, TikTok, Reels and YouTube, for an
|
||||
English-speaking (US) audience. You get a candidate segment of a stream (game context, timed transcript, chat,
|
||||
emotes) and, when available, the ANALYST's analysis, which already cross-checked screen, speech and chat. Trust the
|
||||
analysis to understand WHAT happened; your job is to decide whether it makes a clip and write a title and caption
|
||||
FAITHFUL to it.
|
||||
|
||||
""" + CLIP_GUIDE_EN + """
|
||||
|
||||
""" + CHAT_GLOSSARY_EN + """
|
||||
|
||||
Title and caption describe the real situation (if the analysis says lag, the title is about the lag, not about a
|
||||
random line of the transcript). With analysis confidence < 0.5, be descriptive and do not invent details.
|
||||
Use the analysis action_start_s/reaction_end_s as the base for start_s/end_s.
|
||||
|
||||
Answer rules:
|
||||
- keep=false for what doesn't work; score 0–10 (7+ = strong clip; below 5 = discard).
|
||||
- start_s and end_s in seconds of the recording, INSIDE the window given and within the min/max duration given;
|
||||
start before the action (context) and end right after the reaction. Never cut mid-sentence.
|
||||
- title: up to 70 characters, English, catchy but true, written like a native US clip channel (not a literal
|
||||
translation), nothing that isn't in the speech/screen.
|
||||
- caption: 1–2 sentences in English, NO hashtags and no links (the system adds channel/game hashtags and credit).
|
||||
- hashtags: 2 to 4 tags OF THE MOMENT, English, without "#": the mission/activity, event, mode, place, item or
|
||||
character in THIS segment. Prefer game-profile terms and what streamer and chat say. Nothing generic ("gameplay",
|
||||
"live", "viral"), nothing that doesn't happen here, and do not repeat the channel or the game name.
|
||||
- reason: one sentence on why you kept or discarded it (cite the screen if it helped).
|
||||
- pt: title, caption and reason translated. """ + PT_NOTE + """
|
||||
- Do not use tools or read anything beyond what was given. Answer only with the requested JSON."""
|
||||
|
||||
SCAN_SYSTEM_EN = """You are a live-stream clip editor WATCHING a stream in windows of a few minutes. The streamer
|
||||
speaks English. You get game context, a timed transcript (seconds of the recording), screen frames with their
|
||||
timestamps, the chat (may be almost empty) and clips already made in this region.
|
||||
|
||||
""" + CLIP_GUIDE_EN + """
|
||||
|
||||
""" + CHAT_GLOSSARY_EN + """
|
||||
|
||||
Task: point out 0 to 2 moments in this window that would make a good clip ON THEIR OWN. If nothing works, return
|
||||
moments=[] (that's normal most of the time — don't force it). Don't repeat a clip already made.
|
||||
- start_s/end_s inside the window (may start back to the "backtrack" limit to catch the action), within the
|
||||
min/max duration given.
|
||||
- screen_game: the game on screen (or "unknown"); has_webcam: is there a streamer camera in the frame?
|
||||
- summary: 1 sentence of what's going on in the window (becomes memory for the next windows).
|
||||
- title/caption/reason in English like an editor would write (title ≤ 70 characters, true).
|
||||
- summary_pt and each moment's pt (title, reason): translated. """ + PT_NOTE + """
|
||||
Do not use tools beyond what was given. Answer only with the requested JSON."""
|
||||
|
||||
|
||||
def _pt_block(*keys: str) -> dict:
|
||||
return {"type": "object", "properties": {k: {"type": "string"} for k in keys}, "required": list(keys),
|
||||
"additionalProperties": False}
|
||||
|
||||
|
||||
def _with(schema: dict, **extra: dict) -> dict:
|
||||
"""Schema + campos novos obrigatórios (os CLIs exigem `required` com todas as propriedades)."""
|
||||
return {**schema, "properties": {**schema["properties"], **extra}, "required": [*schema["required"], *extra]}
|
||||
|
||||
|
||||
ANALYSIS_SCHEMA_EN = _with(ANALYSIS_SCHEMA, pt=_pt_block("what_happened", "screen", "speech", "chat_meaning", "hook"))
|
||||
VERDICT_SCHEMA_EN = _with(VERDICT_SCHEMA, pt=_pt_block("title", "caption", "reason"))
|
||||
SCAN_SCHEMA_EN = _with({**SCAN_SCHEMA, "properties": {**SCAN_SCHEMA["properties"],
|
||||
"moments": {"type": "array", "items": _with(_MOMENT, pt=_pt_block("title", "reason"))}}},
|
||||
summary_pt={"type": "string"})
|
||||
|
||||
# Tradução da fala de um corte (painel e legenda em português de desenvolvimento): frases numeradas → mesma quantidade.
|
||||
LINES_SCHEMA = {
|
||||
"type": "object",
|
||||
"properties": {"lines": {"type": "array", "items": {"type": "string"}}},
|
||||
"required": ["lines"],
|
||||
"additionalProperties": False,
|
||||
}
|
||||
LINES_SYSTEM = """You translate the speech of a live-streamer (auto transcript, may have errors and slang) into
|
||||
Brazilian Portuguese, for a team that doesn't speak English. You get numbered lines in order; they are one
|
||||
continuous talk, so use the neighbours as context. Return `lines` with EXACTLY the same number of items, same order,
|
||||
one translation per line: natural spoken Brazilian Portuguese, short, faithful (keep swearing level, game terms and
|
||||
names; translate the slang's meaning, e.g. "he's cooked" -> "ele tá ferrado"). If a line is noise, translate it
|
||||
as is. Answer only with the requested JSON."""
|
||||
|
||||
|
||||
def lang_key(language: str | None) -> str:
|
||||
"""'en' para fonte em inglês (juízes em inglês); 'pt' para o resto (prompts em português + nota de saída)."""
|
||||
return "en" if (language or "").strip().lower().startswith("en") else "pt"
|
||||
|
||||
|
||||
# Rótulos dos prompts montados aqui (o texto do usuário). Mesmas chaves nos dois idiomas.
|
||||
LABELS = {
|
||||
"pt": {"live_title": "Título da live", "unknown": "desconhecido", "channel": "Canal", "window": "Janela disponível",
|
||||
"candidate": "Candidato da heurística", "peak": "pico de reação em", "duration": "Duração do corte",
|
||||
"signals": "Sinais da heurística", "face": "Rosto do streamer (expressão medida na webcam, relativa ao normal dele)",
|
||||
"transcript": "Transcrição", "no_speech": "(sem fala transcrita)", "chat_per": "Mensagens do chat por",
|
||||
"no_chat": "sem chat", "top_emotes": "Emotes mais usados", "none": "nenhum", "chat_sample": "Amostra do chat",
|
||||
"no_chat_p": "(sem chat)", "frames_none": "Frames: (nenhum)", "frames": "Frames anexados, em ordem",
|
||||
"new_window": "Janela nova", "back_to": "pode voltar até {s}s para pegar o início de uma ação",
|
||||
"done": "Cortes já feitos aqui", "analysis": "Análise do ANALISTA (cruzou tela, fala e chat)"},
|
||||
"en": {"live_title": "Stream title", "unknown": "unknown", "channel": "Channel", "window": "Available window",
|
||||
"candidate": "Heuristic candidate", "peak": "reaction peak at", "duration": "Clip duration",
|
||||
"signals": "Heuristic signals", "face": "Streamer face (expression measured on the webcam, relative to his normal)",
|
||||
"transcript": "Transcript", "no_speech": "(no transcribed speech)", "chat_per": "Chat messages per",
|
||||
"no_chat": "no chat", "top_emotes": "Top emotes", "none": "none", "chat_sample": "Chat sample",
|
||||
"no_chat_p": "(no chat)", "frames_none": "Frames: (none)", "frames": "Attached frames, in order",
|
||||
"new_window": "New window", "back_to": "may go back to {s}s to catch the start of an action",
|
||||
"done": "Clips already made here", "analysis": "ANALYST's analysis (cross-checked screen, speech and chat)"},
|
||||
}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 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)"}
|
||||
@@ -412,8 +571,8 @@ 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 ""
|
||||
if code == DEFAULT_LANGUAGE or lang_key(code) == "en":
|
||||
return "" # inglês: os juízes já trabalham em inglês (ANALYST/JUDGE/SCAN_SYSTEM_EN)
|
||||
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).")
|
||||
@@ -423,33 +582,39 @@ MISSIONS_IN_PROMPT = 25
|
||||
MISSIONS_PROMPT_CHARS = 1500
|
||||
|
||||
|
||||
def mission_lines(profile: dict) -> list[str]:
|
||||
def mission_lines(profile: dict, lang: str = "pt") -> 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))
|
||||
lines.append(("Mission/objective end signals in this game: " if lang == "en" else
|
||||
"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 "")
|
||||
item = f"{m['name']}" + (f" ({'end' if lang == 'en' else '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 ""))
|
||||
more = (f"; …and {extra} more" if lang == "en" else f"; …e mais {extra}") if extra > 0 else ""
|
||||
lines.append(("Story missions: " if lang == "en" else "Missões da história: ") + "; ".join(parts) + more)
|
||||
if triggers or missions:
|
||||
lines.append("Se o trecho é o fim de uma missão, termine o corte logo depois do gatilho de fim "
|
||||
lines.append("If the segment is the end of a mission, end the clip right after the end trigger "
|
||||
"(the win/fail moment is the climax)." if lang == "en" else
|
||||
"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:
|
||||
confirmed: bool = False, lang: str = "pt") -> str:
|
||||
if lang == "en":
|
||||
return _game_context_en(game, screen_game, profile, live_title, history, confirmed)
|
||||
lines = [f"Título da live: {live_title or '(desconhecido)'}"]
|
||||
if confirmed:
|
||||
# O usuário confirmou no painel: não questionar (jogo novo/pouco conhecido lembra outros na tela).
|
||||
@@ -472,7 +637,30 @@ def game_context(game: str, screen_game: str, profile: dict | None, live_title:
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def _transcript(words: list[Word], lo: float, hi: float) -> str:
|
||||
def _game_context_en(game: str, screen_game: str, profile: dict | None, live_title: str, history: str,
|
||||
confirmed: bool) -> str:
|
||||
lines = [f"Stream title: {live_title or '(unknown)'}"]
|
||||
if confirmed:
|
||||
lines.append(f"Game CONFIRMED by the user: {game}. The screen may look like a similar game (e.g. GTA, Warzone) "
|
||||
f"— don't question the game; use the profile below to understand what happens.")
|
||||
else:
|
||||
lines.append(f"Game from the platform category: {game or '(unknown)'}")
|
||||
if screen_game and screen_game.lower() not in (game or "").lower():
|
||||
lines.append(f"Game the AI saw on screen recently: {screen_game} (check the frames; the category may be wrong)")
|
||||
if profile:
|
||||
lines.append(f"Game profile: {profile.get('summary', '')}")
|
||||
for key, label in (("clip_worthy", "Clip-worthy in this game"), ("avoid", "Not clip-worthy"),
|
||||
("mechanics", "Mechanics/activities (terms for the moment hashtags)"),
|
||||
("jargon", "Slang/terms"), ("news", "News")):
|
||||
if profile.get(key):
|
||||
lines.append(f"{label}: " + "; ".join(profile[key][:10]))
|
||||
lines.extend(mission_lines(profile, "en"))
|
||||
if history:
|
||||
lines.append(f"What happened earlier in the stream: {history}")
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def _transcript(words: list[Word], lo: float, hi: float, lang: str = "pt") -> str:
|
||||
lines, current, current_t = [], [], None
|
||||
for word in sorted((w for w in words if lo <= w.start <= hi), key=lambda w: w.start):
|
||||
if current_t is None or word.start - current_t > 4 or len(current) >= 14:
|
||||
@@ -482,10 +670,12 @@ def _transcript(words: list[Word], lo: float, hi: float) -> str:
|
||||
current.append(word.word)
|
||||
if current:
|
||||
lines.append(f"[{current_t:.0f}s] {' '.join(current)}")
|
||||
return "\n".join(lines) or "(sem fala transcrita)"
|
||||
return "\n".join(lines) or LABELS[lang]["no_speech"]
|
||||
|
||||
|
||||
def _chat_block(chat: list[ChatMessage], lo: float, hi: float, focus: float | None, bucket_s: int = 5) -> str:
|
||||
def _chat_block(chat: list[ChatMessage], lo: float, hi: float, focus: float | None, bucket_s: int = 5,
|
||||
lang: str = "pt") -> str:
|
||||
L = LABELS[lang]
|
||||
buckets: dict[int, int] = {}
|
||||
emotes: dict[str, int] = {}
|
||||
sample: list[str] = []
|
||||
@@ -498,50 +688,52 @@ def _chat_block(chat: list[ChatMessage], lo: float, hi: float, focus: float | No
|
||||
near = focus is None or focus - 10 <= message.t <= focus + 8
|
||||
if near and len(sample) < 60:
|
||||
sample.append(f"[{message.t:.0f}s] {message.text[:80]}")
|
||||
rate = ", ".join(f"{t}s:{n}" for t, n in sorted(buckets.items())) or "sem chat"
|
||||
top = ", ".join(f"{e}×{n}" for e, n in sorted(emotes.items(), key=lambda kv: -kv[1])[:12]) or "nenhum"
|
||||
return (f"Mensagens do chat por {bucket_s} s: {rate}\nEmotes mais usados: {top}\n"
|
||||
f"Amostra do chat:\n" + ("\n".join(sample) or "(sem chat)"))
|
||||
rate = ", ".join(f"{t}s:{n}" for t, n in sorted(buckets.items())) or L["no_chat"]
|
||||
top = ", ".join(f"{e}×{n}" for e, n in sorted(emotes.items(), key=lambda kv: -kv[1])[:12]) or L["none"]
|
||||
return (f"{L['chat_per']} {bucket_s} s: {rate}\n{L['top_emotes']}: {top}\n"
|
||||
f"{L['chat_sample']}:\n" + ("\n".join(sample) or L["no_chat_p"]))
|
||||
|
||||
|
||||
def _frames_block(frames: list[tuple[float, Path]]) -> str:
|
||||
def _frames_block(frames: list[tuple[float, Path]], lang: str = "pt") -> str:
|
||||
if not frames:
|
||||
return "Frames: (nenhum)"
|
||||
return "Frames anexados, em ordem: " + ", ".join(f"#{i + 1} = {t:.0f}s" for i, (t, _) in enumerate(frames))
|
||||
return LABELS[lang]["frames_none"]
|
||||
return LABELS[lang]["frames"] + ": " + ", ".join(f"#{i + 1} = {t:.0f}s" for i, (t, _) in enumerate(frames))
|
||||
|
||||
|
||||
def build_prompt(streamer: str, platform: str, start_s: float, end_s: float, peak_s: float,
|
||||
words: list[Word], chat: list[ChatMessage], heuristic: dict, live_title: str = "", *,
|
||||
context: str = "", frames: list[tuple[float, Path]] | None = None,
|
||||
backtrack_s: float = DEFAULT_BACKTRACK_S, min_s: float = DEFAULT_MIN_S, max_s: float = DEFAULT_MAX_S,
|
||||
face: str = "") -> str:
|
||||
face: str = "", lang: str = "pt") -> str:
|
||||
"""Prompt do juiz. Janela = candidato com `backtrack_s` para trás (a ação vem antes do comentário).
|
||||
`face`: resumo do rosto do streamer na janela (face.FaceService.summary); vazio = sem câmera/rastreio."""
|
||||
lo, hi = max(0.0, start_s - backtrack_s), end_s + CONTEXT_AFTER_S
|
||||
L, to = LABELS[lang], ("to" if lang == "en" else "a")
|
||||
return (
|
||||
f"Canal: {streamer} ({platform})\n"
|
||||
+ (context or f"Título da live: {live_title or '(desconhecido)'}") + "\n\n"
|
||||
f"Janela disponível: {lo:.0f}s a {hi:.0f}s. Candidato da heurística: {start_s:.0f}s a {end_s:.0f}s; "
|
||||
f"pico de reação em {peak_s:.0f}s. Duração do corte: {min_s:.0f} a {max_s:.0f} s.\n"
|
||||
f"Sinais da heurística: {json.dumps(heuristic, ensure_ascii=False)}\n"
|
||||
+ (f"Rosto do streamer (expressão medida na webcam, relativa ao normal dele): {face}\n" if face else "")
|
||||
+ f"{_frames_block(frames or [])}\n\n"
|
||||
f"Transcrição:\n{_transcript(words, lo, hi)}\n\n"
|
||||
f"{_chat_block(chat, lo, hi, peak_s)}"
|
||||
f"{L['channel']}: {streamer} ({platform})\n"
|
||||
+ (context or f"{L['live_title']}: {live_title or '(' + L['unknown'] + ')'}") + "\n\n"
|
||||
f"{L['window']}: {lo:.0f}s {to} {hi:.0f}s. {L['candidate']}: {start_s:.0f}s {to} {end_s:.0f}s; "
|
||||
f"{L['peak']} {peak_s:.0f}s. {L['duration']}: {min_s:.0f} {to} {max_s:.0f} s.\n"
|
||||
f"{L['signals']}: {json.dumps(heuristic, ensure_ascii=False)}\n"
|
||||
+ (f"{L['face']}: {face}\n" if face else "")
|
||||
+ f"{_frames_block(frames or [], lang)}\n\n"
|
||||
f"{L['transcript']}:\n{_transcript(words, lo, hi, lang)}\n\n"
|
||||
f"{_chat_block(chat, lo, hi, peak_s, lang=lang)}"
|
||||
)
|
||||
|
||||
|
||||
def build_scan_prompt(streamer: str, platform: str, lo: float, hi: float, back_lo: float, words: list[Word],
|
||||
chat: list[ChatMessage], context: str, frames: list[tuple[float, Path]],
|
||||
existing: list[tuple[float, float, str]], min_s: float, max_s: float) -> str:
|
||||
done = "; ".join(f"{a:.0f}–{b:.0f}s ({t[:40]})" for a, b, t in existing) or "nenhum"
|
||||
existing: list[tuple[float, float, str]], min_s: float, max_s: float, lang: str = "pt") -> str:
|
||||
L, to = LABELS[lang], ("to" if lang == "en" else "a")
|
||||
done = "; ".join(f"{a:.0f}–{b:.0f}s ({t[:40]})" for a, b, t in existing) or L["none"]
|
||||
return (
|
||||
f"Canal: {streamer} ({platform})\n{context}\n\n"
|
||||
f"Janela nova: {lo:.0f}s a {hi:.0f}s (pode voltar até {back_lo:.0f}s para pegar o início de uma ação).\n"
|
||||
f"Duração do corte: {min_s:.0f} a {max_s:.0f} s. Cortes já feitos aqui: {done}\n"
|
||||
f"{_frames_block(frames)}\n\n"
|
||||
f"Transcrição:\n{_transcript(words, back_lo, hi)}\n\n"
|
||||
f"{_chat_block(chat, back_lo, hi, None, bucket_s=10)}"
|
||||
f"{L['channel']}: {streamer} ({platform})\n{context}\n\n"
|
||||
f"{L['new_window']}: {lo:.0f}s {to} {hi:.0f}s ({L['back_to'].format(s=f'{back_lo:.0f}')}).\n"
|
||||
f"{L['duration']}: {min_s:.0f} {to} {max_s:.0f} s. {L['done']}: {done}\n"
|
||||
f"{_frames_block(frames, lang)}\n\n"
|
||||
f"{L['transcript']}:\n{_transcript(words, back_lo, hi, lang)}\n\n"
|
||||
f"{_chat_block(chat, back_lo, hi, None, bucket_s=10, lang=lang)}"
|
||||
)
|
||||
|
||||
|
||||
@@ -563,6 +755,7 @@ def _clean(data: dict, start_s: float, end_s: float, model: str, lo: float | Non
|
||||
title=str(data["title"]).strip()[:100], caption=str(data["caption"]).strip()[:600],
|
||||
reason=str(data["reason"]).strip()[:300], model=model,
|
||||
hashtags=tuple(str(t).strip()[:40] for t in (data.get("hashtags") or [])[:6] if str(t).strip()),
|
||||
pt={k: str(v).strip()[:600] for k, v in (data.get("pt") or {}).items() if k in ("title", "caption", "reason") and v},
|
||||
)
|
||||
|
||||
|
||||
@@ -701,7 +894,8 @@ class Judge:
|
||||
|
||||
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.
|
||||
com CLI e (no modo chave) com chave; as em pausa são puladas e as perto do limite de uso vão para o fim.
|
||||
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 []
|
||||
@@ -710,9 +904,13 @@ class Judge:
|
||||
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
|
||||
if not settings["fallback"]["enabled"]:
|
||||
return ready
|
||||
paused = self.pauses()
|
||||
# Perto do limite de uso (data/ai/usage.json, do painel): vai para depois das livres, antes das em pausa.
|
||||
limited = {p for p in ready if p not in paused and self.ai.over_limit(p)}
|
||||
active = [p for p in ready if p not in paused and p not in limited]
|
||||
return (active + [p for p in ready if p in limited]) or ready
|
||||
|
||||
def describe(self) -> dict:
|
||||
cmd = self.command() if self.enabled else None
|
||||
@@ -734,9 +932,11 @@ class Judge:
|
||||
return {"codex": codex_models(), "claude": CLAUDE_MODELS, "gemini": GEMINI_MODELS, "defaults": DEFAULT_MODELS}
|
||||
|
||||
# ---------- usos
|
||||
def analyze(self, prompt: str, images: list[Path]) -> dict:
|
||||
"""1º juiz (ANALISTA): o que aconteceu, cruzando tela + fala + chat. Não decide nem escreve título."""
|
||||
data = self.ask(ANALYST_SYSTEM, prompt, ANALYSIS_SCHEMA, images, model=self.analyst_model or self.model)
|
||||
def analyze(self, prompt: str, images: list[Path], lang: str = "pt") -> dict:
|
||||
"""1º juiz (ANALISTA): o que aconteceu, cruzando tela + fala + chat. Não decide nem escreve título.
|
||||
`lang="en"`: prompt em inglês e bloco `pt` (tradução para o painel) na mesma resposta."""
|
||||
system, schema = (ANALYST_SYSTEM_EN, ANALYSIS_SCHEMA_EN) if lang == "en" else (ANALYST_SYSTEM, ANALYSIS_SCHEMA)
|
||||
data = self.ask(system, prompt, schema, images, model=self.analyst_model or self.model)
|
||||
missing = [k for k in ANALYSIS_SCHEMA["required"] if k not in data]
|
||||
if missing:
|
||||
raise JudgeError(f"análise sem os campos {missing}")
|
||||
@@ -745,13 +945,27 @@ class Judge:
|
||||
|
||||
def judge(self, prompt: str, start_s: float, end_s: float, images: list[Path] | None = None, *,
|
||||
lo: float | None = None, hi: float | None = None, min_s: float = DEFAULT_MIN_S,
|
||||
max_s: float = DEFAULT_MAX_S) -> Verdict:
|
||||
data = self.ask(JUDGE_SYSTEM, prompt, VERDICT_SCHEMA, images or [])
|
||||
max_s: float = DEFAULT_MAX_S, lang: str = "pt") -> Verdict:
|
||||
system, schema = (JUDGE_SYSTEM_EN, VERDICT_SCHEMA_EN) if lang == "en" else (JUDGE_SYSTEM, VERDICT_SCHEMA)
|
||||
data = self.ask(system, prompt, schema, images or [])
|
||||
# Modelo de quem DE FATO respondeu (a reserva pode ter entrado no lugar da escolhida).
|
||||
return _clean(data, start_s, end_s, self.responder(), lo, hi, min_s, max_s)
|
||||
|
||||
def scan(self, prompt: str, images: list[Path]) -> dict:
|
||||
data = self.ask(SCAN_SYSTEM, prompt, SCAN_SCHEMA, images)
|
||||
def translate_lines(self, lines: list[str]) -> list[str]:
|
||||
"""Fala de um corte (frases em ordem) → português, mesma quantidade. Para o painel e a legenda de
|
||||
desenvolvimento; o vídeo publicado continua no idioma da fonte."""
|
||||
if not lines:
|
||||
return []
|
||||
prompt = "\n".join(f"{i + 1}. {text}" for i, text in enumerate(lines))
|
||||
data = self.ask(LINES_SYSTEM, prompt, LINES_SCHEMA, [])
|
||||
out = [str(x).strip() for x in (data.get("lines") or [])]
|
||||
if len(out) != len(lines):
|
||||
raise JudgeError(f"tradução com {len(out)} linhas para {len(lines)} frases", unavailable=False)
|
||||
return out
|
||||
|
||||
def scan(self, prompt: str, images: list[Path], lang: str = "pt") -> dict:
|
||||
system, schema = (SCAN_SYSTEM_EN, SCAN_SCHEMA_EN) if lang == "en" else (SCAN_SYSTEM, SCAN_SCHEMA)
|
||||
data = self.ask(system, prompt, schema, images)
|
||||
if not isinstance(data.get("moments"), list):
|
||||
raise JudgeError("varredura sem a lista de momentos")
|
||||
return data
|
||||
@@ -974,6 +1188,7 @@ def parse_gemini_output(stdout: str) -> dict:
|
||||
return data
|
||||
|
||||
|
||||
def analysis_block(analysis: dict) -> str:
|
||||
"""Análise do 1º juiz no formato que o editor lê."""
|
||||
return "Análise do ANALISTA (cruzou tela, fala e chat):\n" + json.dumps(analysis, ensure_ascii=False, indent=1)
|
||||
def analysis_block(analysis: dict, lang: str = "pt") -> str:
|
||||
"""Análise do 1º juiz no formato que o editor lê (sem o bloco `pt`, que é só para o painel)."""
|
||||
data = {k: v for k, v in analysis.items() if k != "pt"}
|
||||
return LABELS[lang]["analysis"] + ":\n" + json.dumps(data, ensure_ascii=False, indent=1)
|
||||
|
||||
@@ -91,6 +91,9 @@ DEFAULTS: dict = {
|
||||
"caption": {
|
||||
"enabled": True, "font": "Arial Black", "size": 84, "color": "#FFFFFF", "highlight": "#FFE500",
|
||||
"outline": "#000000", "outlineWidth": 7, "y": None, "uppercase": True, "maxWords": 3,
|
||||
# Só para desenvolver (fonte em inglês, doc/clipador/IDIOMAS.md): a tradução em português da fala embaixo
|
||||
# da legenda em inglês. Desligado = o vídeo publicável; nunca publicar com isto ligado.
|
||||
"translation": False,
|
||||
},
|
||||
"credit": {"enabled": True, "position": "top", "size": 44},
|
||||
"duration": {"minS": 60, "maxS": 90, "backtrackS": 120},
|
||||
@@ -173,7 +176,7 @@ def validate(settings: dict) -> dict:
|
||||
o["y"] = None if cap["y"] is None else float(cap["y"])
|
||||
if o["y"] is not None and not 0.08 <= o["y"] <= 0.9:
|
||||
raise LayoutError("caption.y vai de 0,08 a 0,9 (fração da altura) ou null = automático")
|
||||
for key in ("enabled", "uppercase"):
|
||||
for key in ("enabled", "uppercase", "translation"):
|
||||
if key in cap:
|
||||
o[key] = bool(cap[key])
|
||||
out["caption"] = o
|
||||
|
||||
@@ -184,6 +184,9 @@ def clip_view(row: dict) -> dict:
|
||||
"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"),
|
||||
# Fonte em inglês: a fala do corte em frases com a tradução ({language, startS, endS, model, lines: [{s, e,
|
||||
# text, pt}]}); None = sessão em português ou ainda não traduzido (doc/clipador/IDIOMAS.md).
|
||||
"translation": loads(row.get("translation_json"), None),
|
||||
# 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")}
|
||||
@@ -753,6 +756,14 @@ def create_app(settings: Settings | None = None, engine: Engine | None = None, s
|
||||
engine.wake_clips.set()
|
||||
return clip_view(_clip(clip_id))
|
||||
|
||||
@app.post("/v1/clips/{clip_id}/translate")
|
||||
def translate_clip(clip_id: int):
|
||||
"""Traduz (de novo) a fala do corte para o português. Só para fonte em inglês; 409 se não couber."""
|
||||
_clip(clip_id)
|
||||
if engine.translate_clip(clip_id, force=True) is None:
|
||||
raise UserError("Sem tradução: a fonte não está em inglês, a IA está desligada ou não respondeu.", 409)
|
||||
return clip_view(_clip(clip_id))
|
||||
|
||||
@app.post("/v1/clips/{clip_id}/rejudge")
|
||||
def rejudge(clip_id: int):
|
||||
_clip(clip_id)
|
||||
|
||||
+12
-6
@@ -24,15 +24,21 @@ from . import reaction
|
||||
|
||||
# Peso extra por categoria de reação. Uma mensagem pode somar mais de uma.
|
||||
REACTION_PATTERNS: dict[str, tuple[re.Pattern[str], float]] = {
|
||||
"risada": (re.compile(r"(k{3,}|kek|lul|lmao|lmfao|omegalul|icant|pepelaugh|haha|hehe|rsrs|ksks|😂|🤣|xd\b)", re.I), 1.0),
|
||||
# Chat em inglês (fonte gringa, 18/11/2026): a risada lá é LMAO/LOL/💀/😭 e "I'm dead", não "kkkk".
|
||||
"risada": (re.compile(r"(k{3,}|kek|lul|lmao+|lmfao|omegalul|icant|pepelaugh|haha|hehe|rsrs|ksks|😂|🤣|xd\b|"
|
||||
r"\blo+l+\b|\brofl\b|💀|☠️?|😭|\bi'?m dead\b|\bim crying\b|\bdying\b)", re.I), 1.0),
|
||||
"susto": (re.compile(r"(caralho|crlh|caraca|nossa|meu deus|mds|wtf|omg|que isso|q isso|monkas|monkaw|\bhuh+\b|"
|
||||
r"😱|😳|\?{3,}|!{3,})", re.I), 1.0),
|
||||
"hype": (re.compile(r"(\bpog|pogchamp|poggers|\bw+\b|\bgg+\b|\bez\b|insano|absurdo|brabo|🔥)", re.I), 0.7),
|
||||
r"😱|😳|\?{3,}|!{3,}|\bno+ ?wa+y+\b|\bna+h+\b|\bbru+h+\b|\bholy\b|\bjesus\b|"
|
||||
r"\boh my god\b|\bwhat the\b)", re.I), 1.0),
|
||||
"hype": (re.compile(r"(\bpog|pogchamp|poggers|\bw+\b|\bgg+\b|\bez\b|insano|absurdo|brabo|🔥|"
|
||||
r"\blet'?s ?go+\b|\bletsgo+\b|\bshe+sh\b|\bclutch\b|\bcracked\b|\bgoated\b|\binsane\b|"
|
||||
r"\bclap\b|\bdub\b)", re.I), 0.7),
|
||||
# Palavra inteira: "clip5k1hmm" (emote) casava com \bclip e dava peso de pedido de clipe.
|
||||
"clip": (re.compile(r"\b(clip|clips|clipa|clipe|clipou|clipar|clip it|clipit)\b", re.I), 3.0),
|
||||
"clip": (re.compile(r"\b(clip|clips|clipa|clipe|clipou|clipar|clip it|clipit|clip that|clipped)\b", re.I), 3.0),
|
||||
}
|
||||
# Palavras faladas que indicam reação (modo sem chat).
|
||||
SPOKEN_REACTION = re.compile(r"^(caralho|caraca|nossa|meu|deus|socorro|mano|nãããão|não|sim|vai|gente|que|isso|olha)$", re.I)
|
||||
# Palavras faladas que indicam reação (modo sem chat), em português e em inglês (fonte gringa).
|
||||
SPOKEN_REACTION = re.compile(r"^(caralho|caraca|nossa|meu|deus|socorro|mano|nãããão|não|sim|vai|gente|que|isso|olha|"
|
||||
r"bro|bruh|dude|yo|what|no+|oh|wow|holy|fuck|shit|wait|god|jesus|yes+|bro+)$", re.I)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
|
||||
@@ -96,6 +96,27 @@ def caption_blocks(words: list[Word], max_words: int = MAX_WORDS) -> list[tuple[
|
||||
return out
|
||||
|
||||
|
||||
PHRASE_GAP_S, PHRASE_MAX_S, PHRASE_MAX_WORDS = 0.7, 6.0, 16
|
||||
_SENTENCE_END = (".", "?", "!")
|
||||
|
||||
|
||||
def phrases(words: list[Word]) -> list[tuple[float, float, str]]:
|
||||
"""Fala em frases curtas com tempo (início, fim, texto) para traduzir: quebra em pausa > 0,7 s, fim de frase
|
||||
(. ? !) com 4+ palavras, 16 palavras ou 6 s. A tradução de uma frase inteira sai melhor que a de blocos de 3."""
|
||||
out: list[tuple[float, float, str]] = []
|
||||
current: list[Word] = []
|
||||
for w in clean_words(words):
|
||||
if current and (w.start - current[-1].end > PHRASE_GAP_S or w.end - current[0].start > PHRASE_MAX_S
|
||||
or len(current) >= PHRASE_MAX_WORDS
|
||||
or (current[-1].word.endswith(_SENTENCE_END) and len(current) >= 4)):
|
||||
out.append((current[0].start, current[-1].end, " ".join(x.word for x in current)))
|
||||
current = []
|
||||
current.append(w)
|
||||
if current:
|
||||
out.append((current[0].start, current[-1].end, " ".join(x.word for x in current)))
|
||||
return out
|
||||
|
||||
|
||||
def build_ass(words: list[Word], clip_start: float, clip_end: float, credit: str, settings: dict | None = None) -> str:
|
||||
"""`words` com tempos da sessão; a saída usa tempos relativos ao início do corte."""
|
||||
cfg = settings or layout.merge()
|
||||
|
||||
+53
-6
@@ -40,7 +40,7 @@ from .intel import Intel
|
||||
from .judge import Judge, JudgeError, analysis_block, build_prompt
|
||||
from .scoring import ChatMessage, Params, Word, find_moments, overlaps
|
||||
from .sources import Source, parse_source
|
||||
from .subtitles import build_ass
|
||||
from .subtitles import build_ass, phrases
|
||||
|
||||
log = logging.getLogger("cenaforge_clipper")
|
||||
LIVE_WINDOW_S = 900 # ao vivo, pontua só os últimos 15 min (o que veio antes já foi decidido)
|
||||
@@ -51,6 +51,15 @@ def rel(path: Path) -> str:
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- serviço de voz
|
||||
# O serviço de voz (voice/app/stt.py, WHISPER_LANGUAGES) aceita "pt-BR", "en" e "es"; fonte e sessão usam o idioma do
|
||||
# público ("en-US", "es-419"). Tradução num ponto só, aqui na fronteira (medido 18/11/2026: "en-US" voltava 422).
|
||||
VOICE_LANGUAGES = {"pt-BR": "pt-BR", "en-US": "en", "en": "en", "es-419": "es", "es": "es"}
|
||||
|
||||
|
||||
def voice_language(code: str) -> str:
|
||||
return VOICE_LANGUAGES.get(code, code.split("-")[0] if code and not code.startswith("pt") else "pt-BR")
|
||||
|
||||
|
||||
class VoiceClient:
|
||||
def __init__(self, url: str | None, key: str | None, language: str):
|
||||
self.url, self.key, self.language = url, key, language
|
||||
@@ -72,7 +81,7 @@ class VoiceClient:
|
||||
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": language or self.language,
|
||||
"X-Service-Key": self.key or "", "Content-Type": "audio/wav", "X-Language": voice_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)
|
||||
@@ -877,22 +886,25 @@ class Engine:
|
||||
n_frames = 8 if hi - f_lo > 80 else 6
|
||||
times = [f_lo + (hi - f_lo) * k / (n_frames - 1) for k in range(n_frames)]
|
||||
frames = self.intel.frames(session, times, f"clip{clip['id']}")
|
||||
# Fonte em inglês: os juízes trabalham em inglês e devolvem também o português do painel (IDIOMAS.md).
|
||||
lang = self.intel.lang(session)
|
||||
prompt = build_prompt(streamer, session["platform"], clip["start_s"], clip["end_s"], clip["peak_s"],
|
||||
tl["words"], tl["chat"], heuristic, session["title"], context=self.intel.context(session),
|
||||
frames=frames, backtrack_s=dur["backtrackS"], min_s=dur["minS"], max_s=dur["maxS"],
|
||||
face=self.face.summary(session, lo, hi))
|
||||
face=self.face.summary(session, lo, hi), lang=lang)
|
||||
analysis = None
|
||||
try:
|
||||
# Dois juízes: o ANALISTA (vê os frames) diz o que aconteceu; o EDITOR decide e escreve a partir disso.
|
||||
try:
|
||||
analysis = self.judge.analyze(prompt, [p for _, p in frames])
|
||||
analysis = self.judge.analyze(prompt, [p for _, p in frames], lang=lang)
|
||||
except (JudgeError, json.JSONDecodeError, KeyError, ValueError) as exc:
|
||||
log.warning("analista falhou no corte %s: %s (editor segue sozinho)", clip["id"], exc)
|
||||
editor_prompt = prompt + ("\n\n" + analysis_block(analysis) if analysis else "")
|
||||
editor_prompt = prompt + ("\n\n" + analysis_block(analysis, lang) if analysis else "")
|
||||
# Sem análise, o editor recebe os frames; com análise, só texto (mais barato, a tela já foi lida).
|
||||
verdict = self.judge.judge(editor_prompt, clip["start_s"], clip["end_s"],
|
||||
[] if analysis else [p for _, p in frames],
|
||||
lo=lo, hi=hi, min_s=layout.min_target({"duration": dur}), max_s=dur["maxS"])
|
||||
lo=lo, hi=hi, min_s=layout.min_target({"duration": dur}), max_s=dur["maxS"],
|
||||
lang=lang)
|
||||
# Corte manual: quem decidiu foi você; o juiz só escreve título e legenda (e não mexe no trecho).
|
||||
manual = clip["source"] == "manual"
|
||||
keep = manual or (verdict.keep and verdict.score >= self.min_score)
|
||||
@@ -904,6 +916,8 @@ class Engine:
|
||||
"start_s": verdict.start_s, "end_s": verdict.end_s,
|
||||
"judge": {"model": verdict.model, "keep": verdict.keep, "score": verdict.score,
|
||||
"reason": verdict.reason, "analysis": analysis,
|
||||
# Fonte em inglês: título/legenda/motivo em português (só o painel lê).
|
||||
**({"pt": verdict.pt} if verdict.pt else {}),
|
||||
"analystModel": (self.judge.analyst_model or self.judge.model) if analysis else None}}
|
||||
except (JudgeError, json.JSONDecodeError, KeyError, ValueError) as exc:
|
||||
# Falha do juiz não perde o momento: segue com a heurística e registra o motivo.
|
||||
@@ -942,6 +956,8 @@ class Engine:
|
||||
if update["status"] == "pending":
|
||||
# Novo veredito: o projeto que a IA tinha gerado é refeito no render (o que você editou fica).
|
||||
self.db.run("DELETE FROM edits WHERE clip_id = ? AND origin = 'ai'", clip["id"])
|
||||
# Fonte em inglês: a fala do corte em português para o painel (falha não segura o corte).
|
||||
self.translate_clip(clip["id"], update["start_s"], update["end_s"])
|
||||
verdict_info = update["judge"] or {}
|
||||
if clip["source"] != "manual" and "score" in verdict_info:
|
||||
# Aprendizado fraco pela IA (o forte vem da sua aprovação/rejeição no painel).
|
||||
@@ -950,6 +966,37 @@ class Engine:
|
||||
elif verdict_info["score"] >= 7:
|
||||
self.intel.learn_from_clip(clip, positive=True, factor=0.5)
|
||||
|
||||
def translate_clip(self, clip_id: int, lo: float | None = None, hi: float | None = None,
|
||||
force: bool = False) -> dict | None:
|
||||
"""Fonte em inglês (doc/clipador/IDIOMAS.md): a fala de [lo, hi] (padrão: o trecho do corte) em frases com
|
||||
tempo da sessão + tradução em português, em `clips.translation_json`. Serve ao painel ("o que ele disse") e à
|
||||
legenda de desenvolvimento (`caption.translation`). Reaproveita a tradução que já cobre o trecho.
|
||||
Sessão em português, IA desligada ou falha da IA → None (o corte segue sem tradução)."""
|
||||
clip = self.db.get("SELECT * FROM clips WHERE id = ?", clip_id)
|
||||
session = self.db.get("SELECT * FROM sessions WHERE id = ?", clip["session_id"]) if clip else None
|
||||
if not clip or not session or self.intel.lang(session) != "en" or not self.judge.enabled:
|
||||
return None
|
||||
lo = clip["start_s"] if lo is None else lo
|
||||
hi = clip["end_s"] if hi is None else hi
|
||||
current = loads(clip.get("translation_json"), None)
|
||||
if (isinstance(current, dict) and not force and current.get("startS", 1e12) <= lo + 0.5
|
||||
and current.get("endS", -1) >= hi - 0.5):
|
||||
return current
|
||||
tl = self.load_timeline(session["id"], max(0.0, lo - 30))
|
||||
items = phrases([w for w in tl["words"] if lo - 0.3 <= w.start <= hi])
|
||||
if not items:
|
||||
return None
|
||||
try:
|
||||
pt = self.judge.translate_lines([text for _, _, text in items])
|
||||
except (JudgeError, json.JSONDecodeError, KeyError, ValueError) as exc:
|
||||
log.warning("tradução da fala do corte %s falhou: %s", clip_id, exc)
|
||||
return None
|
||||
data = {"language": "pt-BR", "startS": round(lo, 2), "endS": round(hi, 2), "model": self.judge.responder(),
|
||||
"lines": [{"s": round(s, 3), "e": round(e, 3), "text": text, "pt": tr}
|
||||
for (s, e, text), tr in zip(items, pt)]}
|
||||
self.db.run("UPDATE clips SET translation_json = ? WHERE id = ?", json.dumps(data, ensure_ascii=False), clip_id)
|
||||
return data
|
||||
|
||||
def render_pending(self) -> None:
|
||||
self.recover_orphan_renders()
|
||||
self.discard_pending_duplicates()
|
||||
|
||||
Reference in New Issue
Block a user