- roles.py: varredura, analista, editor e juiz, cada um com provedor, modelo, raciocínio (Codex), liga/desliga (o editor não desliga) e instruções do administrador somadas às padrão; gravado em settings `judge.roles`, com migração automática da configuração antiga (provedor/modelo único vira o de todos; o modelo do analista é respeitado). A reserva vale por papel. - Juiz de contexto (só texto): vê só o que vai no corte (+20 s antes/15 s depois marcados out=1), escreve o que um espectador frio entende e responde sim/não; context_judge.decide decide pelo código: aprova, ajusta o trecho e confere uma vez de novo, frase de contexto na tela (vira o texto de abertura do projeto) ou descarta com motivo em português (forçável). Corte manual só recebe aviso. - timeline.py: linha do tempo JSON curta (fala com falante, chat, rosto, volume e a frase de tela que a varredura/analista escrevem ao ver os quadros, em scene_notes); mosaico 4x2 (media.mosaic) no lugar dos quadros soltos; perfil do jogo enxuto. O formato antigo fica atrás da opção timelineJson. - Medição (F0): ai_calls por chamada (papel, IA, tamanho do prompt/imagens, tokens quando a CLI informa: codex --json, claude e gemini), avaliação do dono (owner_label: bom/ruim/sem contexto) e GET /v1/judge/report (taxa de aprovação, decisões do juiz, concordância). - Banco v17 (v16 fica reservada às expressões, como marcador sem efeito). - Testes: test_roles.py e test_context_judge.py; os testes bloqueiam qualquer CLI de IA real. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
226 lines
10 KiB
Python
226 lines
10 KiB
Python
"""FFmpeg do Clipador: áudio dos blocos (volume por segundo + WAV para o Whisper), corte vertical e miniatura.
|
||
Subprocesso sempre sem shell, argumentos em lista, com timeout; código != 0 é falha."""
|
||
|
||
from __future__ import annotations
|
||
|
||
import io
|
||
import math
|
||
import subprocess
|
||
import sys
|
||
import wave
|
||
from array import array
|
||
from pathlib import Path
|
||
|
||
from . import layout
|
||
|
||
SAMPLE_RATE = 16_000
|
||
NO_WINDOW = subprocess.CREATE_NO_WINDOW if sys.platform == "win32" else 0
|
||
|
||
|
||
class MediaError(RuntimeError):
|
||
pass
|
||
|
||
|
||
def run(args: list[str], timeout: float, cwd: Path | None = None) -> bytes:
|
||
try:
|
||
result = subprocess.run(args, capture_output=True, timeout=timeout, cwd=cwd, creationflags=NO_WINDOW)
|
||
except subprocess.TimeoutExpired as exc:
|
||
raise MediaError(f"{Path(args[0]).name} passou de {timeout:.0f} s") from exc
|
||
if result.returncode != 0:
|
||
tail = result.stderr.decode("utf-8", errors="replace").strip().splitlines()[-3:]
|
||
raise MediaError(f"{Path(args[0]).name} saiu com código {result.returncode}: {' | '.join(tail)}")
|
||
return result.stdout
|
||
|
||
|
||
def decode_pcm(ffmpeg: str, files: list[Path]) -> bytes:
|
||
"""Áudio mono 16 kHz s16le dos arquivos, em sequência."""
|
||
out = bytearray()
|
||
for file in files:
|
||
out += run([ffmpeg, "-v", "error", "-i", str(file), "-vn", "-ac", "1", "-ar", str(SAMPLE_RATE), "-f", "s16le", "-"], 120)
|
||
return bytes(out)
|
||
|
||
|
||
def loudness_per_second(pcm: bytes) -> list[float | None]:
|
||
"""RMS em dBFS por segundo (None = silêncio absoluto)."""
|
||
samples = array("h")
|
||
samples.frombytes(pcm[: len(pcm) - len(pcm) % 2])
|
||
out: list[float | None] = []
|
||
for i in range(0, len(samples), SAMPLE_RATE):
|
||
chunk = samples[i: i + SAMPLE_RATE]
|
||
if len(chunk) < SAMPLE_RATE // 4:
|
||
break
|
||
rms = math.sqrt(sum(s * s for s in chunk) / len(chunk))
|
||
out.append(round(20 * math.log10(rms / 32768), 2) if rms > 0 else None)
|
||
return out
|
||
|
||
|
||
def to_wav(pcm: bytes) -> bytes:
|
||
buffer = io.BytesIO()
|
||
with wave.open(buffer, "wb") as wav:
|
||
wav.setnchannels(1)
|
||
wav.setsampwidth(2)
|
||
wav.setframerate(SAMPLE_RATE)
|
||
wav.writeframes(pcm)
|
||
return buffer.getvalue()
|
||
|
||
|
||
def pick_encoder(ffmpeg: str, wanted: str) -> list[str]:
|
||
if wanted == "auto":
|
||
try:
|
||
encoders = run([ffmpeg, "-hide_banner", "-encoders"], 30).decode(errors="replace")
|
||
except MediaError:
|
||
encoders = ""
|
||
wanted = "h264_nvenc" if "h264_nvenc" in encoders else "libx264"
|
||
if wanted == "h264_nvenc":
|
||
return ["-c:v", "h264_nvenc", "-preset", "p5", "-rc", "vbr", "-cq", "23", "-b:v", "0"]
|
||
return ["-c:v", "libx264", "-preset", "veryfast", "-crf", "21"]
|
||
|
||
|
||
def render_vertical(ffmpeg: str, encoder: list[str], segments: list[tuple[Path, float]], start_s: float, end_s: float,
|
||
ass_text: str, out_file: Path, settings: dict | None = None) -> None:
|
||
"""`segments` = blocos (arquivo, início na sessão) que cobrem [start_s, end_s], em ordem.
|
||
`settings` = configuração do corte efetiva (layout.merge); define layout, câmera e legenda."""
|
||
if not segments:
|
||
raise MediaError("nenhum bloco gravado cobre o trecho")
|
||
work = out_file.parent
|
||
work.mkdir(parents=True, exist_ok=True)
|
||
stem = out_file.stem
|
||
# O filtro `ass` recebe o nome relativo (cwd = pasta do corte): caminho absoluto do Windows ("C:\...")
|
||
# exigiria escapar ":" e "\" dentro do filtergraph.
|
||
ass_file = work / f"{stem}.ass"
|
||
ass_file.write_text(ass_text, encoding="utf-8")
|
||
concat = work / f"{stem}.concat.txt"
|
||
concat.write_text("".join(f"file '{p.as_posix()}'\n" for p, _ in segments), encoding="utf-8")
|
||
offset = start_s - segments[0][1]
|
||
tmp = work / f"{stem}.tmp.mp4"
|
||
try:
|
||
run(
|
||
# -ss ANTES do -i: os quadros entram no filtro já com tempo 0 = início do corte. Depois do -i o
|
||
# filtro `ass` veria o tempo do bloco e a legenda sairia deslocada (medido: sumia do vídeo).
|
||
[ffmpeg, "-y", "-v", "error", "-ss", f"{max(0.0, offset):.3f}", "-f", "concat", "-safe", "0",
|
||
"-i", concat.name, "-t", f"{end_s - start_s:.3f}",
|
||
"-filter_complex", layout.video_filter(settings or layout.merge(), ass_file.name, ass_text),
|
||
"-map", "[v]", "-map", "0:a:0?",
|
||
*encoder, "-c:a", "aac", "-b:a", "160k", "-ar", "48000", "-movflags", "+faststart", tmp.name],
|
||
timeout=600, cwd=work,
|
||
)
|
||
tmp.replace(out_file)
|
||
finally:
|
||
concat.unlink(missing_ok=True)
|
||
ass_file.unlink(missing_ok=True)
|
||
tmp.unlink(missing_ok=True)
|
||
|
||
|
||
def segment_at(segments: list[tuple[Path, float, float]], t: float) -> tuple[Path, float] | None:
|
||
"""Bloco (arquivo, deslocamento dentro dele) que contém o instante `t` da sessão."""
|
||
for file, start, end in segments:
|
||
if start <= t < end:
|
||
return file, t - start
|
||
if segments and t >= segments[-1][2]:
|
||
file, start, end = segments[-1]
|
||
return file, max(0.0, end - start - 0.5)
|
||
return None
|
||
|
||
|
||
# Busca num bloco .ts: o demuxer mpegts do FFmpeg trata todo pacote como ponto de busca, então `-ss` antes do `-i`
|
||
# cai num quadro P perto do alvo. Medido (17/11/2026): no H.264 sai o PRÓXIMO quadro-chave (até 2 s depois do
|
||
# pedido); no HEVC (2K da Twitch) sai um quadro CINZA (referências faltando) — frames do juiz, capa e YuNet
|
||
# estragados. Um 2º `-ss` depois do `-i` também erra quando o bloco tem áudio (a base de tempo vem do áudio; 7,5 s
|
||
# virou 6,06 s). Agora: busca rápida `SEEK_PREROLL_S` antes, tempo absoluto do bloco (`-copyts -start_at_zero`) e
|
||
# o 1º quadro com t ≥ alvo (`select`). GOP da Twitch = 2 s; o YouTube recomenda ≤ 4 s. O concat (render, proxy)
|
||
# não tem esse problema: não passa por aqui.
|
||
SEEK_PREROLL_S = 4.0
|
||
|
||
|
||
def seek_args(offset: float) -> tuple[list[str], str]:
|
||
"""(argumentos antes do `-i`, filtro `select` do quadro exato) para o instante `offset` s de um bloco .ts."""
|
||
offset = max(0.0, offset)
|
||
return (["-ss", f"{max(0.0, offset - SEEK_PREROLL_S):.3f}", "-copyts", "-start_at_zero"],
|
||
f"select='gte(t,{offset:.3f})'")
|
||
|
||
|
||
def grab_frame(ffmpeg: str, segments: list[tuple[Path, float, float]], t: float, out_file: Path, width: int = 768) -> Path:
|
||
"""Um quadro do instante `t` (sessão) em JPG. Para a IA olhar a tela e para o editor de layout."""
|
||
found = segment_at(segments, t)
|
||
if not found:
|
||
raise MediaError(f"nenhum bloco gravado em {t:.0f}s")
|
||
file, offset = found
|
||
out_file.parent.mkdir(parents=True, exist_ok=True)
|
||
before, select = seek_args(offset)
|
||
vf = select + (f",scale={width}:-2" if width else "")
|
||
run([ffmpeg, "-y", "-v", "error", *before, "-i", str(file), "-map", "0:v:0", "-vf", vf, "-frames:v", "1",
|
||
"-q:v", "4", str(out_file)], 60)
|
||
return out_file
|
||
|
||
|
||
MOSAIC_TILE_W, MOSAIC_TILE_H = 384, 216
|
||
MOSAIC_COLS, MOSAIC_ROWS = 4, 2
|
||
|
||
|
||
def mosaic(ffmpeg: str, images: list[Path], out_file: Path, cols: int = MOSAIC_COLS, rows: int = MOSAIC_ROWS,
|
||
tile_w: int = MOSAIC_TILE_W, tile_h: int = MOSAIC_TILE_H) -> Path:
|
||
"""Vários quadros numa imagem só (grade `cols`×`rows`, da esquerda para a direita e de cima para baixo), cada um
|
||
em `tile_w`×`tile_h` (barras pretas se o quadro não for 16:9). Com menos quadros que a grade, a grade encolhe
|
||
(até 4 → uma linha só). Para a IA: 1 imagem no lugar de 8 (Claude = 1 leitura; Gemini cobra por imagem)."""
|
||
images = [Path(p) for p in images][: cols * rows]
|
||
if not images:
|
||
raise MediaError("mosaico sem quadros")
|
||
n = len(images)
|
||
if n <= cols:
|
||
cols, rows = n, 1
|
||
else:
|
||
rows = math.ceil(n / cols)
|
||
out_file.parent.mkdir(parents=True, exist_ok=True)
|
||
inputs = [arg for img in images for arg in ("-i", str(img))]
|
||
fit = (f"scale={tile_w}:{tile_h}:force_original_aspect_ratio=decrease,"
|
||
f"pad={tile_w}:{tile_h}:(ow-iw)/2:(oh-ih)/2,setsar=1")
|
||
chains = [f"[{i}:v]{fit}[t{i}]" for i in range(n)]
|
||
# Grade incompleta (ex.: 6 quadros em 4×2): completa com quadro preto do mesmo tamanho.
|
||
pads = cols * rows - n
|
||
for k in range(pads):
|
||
chains.append(f"color=c=black:s={tile_w}x{tile_h}:d=1[p{k}]")
|
||
labels = [f"[t{i}]" for i in range(n)] + [f"[p{k}]" for k in range(pads)]
|
||
layout_cells = "|".join(f"{(i % cols) * tile_w}_{(i // cols) * tile_h}" for i in range(cols * rows))
|
||
if cols * rows == 1:
|
||
graph = chains[0].replace("[t0]", "[out]")
|
||
else:
|
||
graph = ";".join(chains) + ";" + "".join(labels) + f"xstack=inputs={cols * rows}:layout={layout_cells}[out]"
|
||
run([ffmpeg, "-y", "-v", "error", *inputs, "-filter_complex", graph, "-map", "[out]", "-frames:v", "1",
|
||
"-q:v", "4", str(out_file)], 60)
|
||
return out_file
|
||
|
||
|
||
def preview_still(ffmpeg: str, frame_file: Path, settings: dict, ass_text: str, out_file: Path, reframe=None) -> Path:
|
||
"""Prévia do layout num quadro só (imagem no formato do corte com câmera, jogo, legenda e crédito de exemplo).
|
||
`reframe` = reenquadramento parado do jogo (capa de um corte com keyframes; ver `reframe.static_reframe`)."""
|
||
work = out_file.parent
|
||
ass_file = work / f"{out_file.stem}.ass"
|
||
ass_file.write_text(ass_text, encoding="utf-8")
|
||
try:
|
||
run([ffmpeg, "-y", "-v", "error", "-loop", "1", "-t", "1", "-i", frame_file.name,
|
||
"-filter_complex", layout.video_filter(settings, ass_file.name, ass_text, reframe), "-map", "[v]",
|
||
"-frames:v", "1", "-q:v", "3", out_file.name], 60, cwd=work)
|
||
finally:
|
||
ass_file.unlink(missing_ok=True)
|
||
return out_file
|
||
|
||
|
||
def thumbnail(ffmpeg: str, video: Path, at_s: float, out_file: Path) -> None:
|
||
run([ffmpeg, "-y", "-v", "error", "-ss", f"{max(0.0, at_s):.2f}", "-i", str(video), "-frames:v", "1",
|
||
"-vf", "scale=360:-2", "-q:v", "4", str(out_file)], 60)
|
||
|
||
|
||
def probe_size(ffprobe: str, file: Path) -> tuple[int, int]:
|
||
"""(largura, altura) do vídeo; 1280×720 se não der para ler (as camadas inseridas usam a proporção)."""
|
||
try:
|
||
out = run([ffprobe, "-v", "error", "-select_streams", "v:0", "-show_entries", "stream=width,height",
|
||
"-of", "csv=p=0", str(file)], 30).decode().strip().split(",")
|
||
return int(out[0]), int(out[1])
|
||
except (MediaError, ValueError, IndexError):
|
||
return 1280, 720
|
||
|
||
|
||
def probe_duration(ffprobe: str, file: Path) -> float:
|
||
out = run([ffprobe, "-v", "error", "-show_entries", "format=duration", "-of", "default=nw=1:nk=1", str(file)], 30)
|
||
return float(out.decode().strip() or 0)
|