Compare commits

...
11 Commits
Author SHA1 Message Date
Mateuus 393d1f74b2 Merge branch 'clipper/expressions' into clipper/integ 2026-11-18 04:19:30 -03:00
MateuusandClaude Opus 5.5 44f78bd483 Clipador: mapa de expressões do streamer (expressões novas, pose e corpo)
- Expressões novas dos blendshapes que já vinham do MediaPipe: gargalhada, alegria
  (no mapa), medo, espanto, nojo, tristeza, tensão e bocejo (que deixou de contar
  como grito); raiva também por olhos semicerrados + lábios apertados. Canais novos
  opcionais na série (brow_inner, mouth_frown, squint, press, stretch, upper_lip,
  pucker), z relativo ao neutro do próprio streamer só com os segundos que têm o campo.
- Pose da cabeça pela matriz de transformação facial (yaw/pitch/roll) e balanço/aceno
  por zigue-zague; YuNet nos quadros sem rosto dá a caixa da cabeça (streamer de perfil).
- Corpo mesmo sem expressão: balançando, acenando, agitado, chegou perto e saiu do
  quadro, sem contar rastreio perdido como movimento.
- API /face com expr/body por segundo e lista do corpo; linha do juiz com o corpo;
  painel com os rótulos novos e o "Mapa de expressões" no modal do corte.
- Calibrado nas sessões 7, 8, 11 e 15 (doc/clipador/EXPRESSOES.md); intensidade dos
  picos inalterada (canais novos só rotulam). Testes em tests/test_expressions.py.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 04:16:25 -03:00
MateuusandClaude Opus 5.5 5be6c09c16 Doc: pesquisa e proposta do juiz de contexto e da linha do tempo em JSON (doc/clipador/PESQUISA-JUIZ.md)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 04:05:31 -03:00
MateuusandClaude Opus 5.5 1ea8445808 Painel: libera POST clips/id/translate e GET sessions/id/speakers no proxy do Clipador
O botão "Traduzir a fala" recebia 404 (rota não liberada) e a rota de vozes da sessão é nova.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 04:00:29 -03:00
MateuusandClaude Opus 5.5 439e111052 Integração: falantes + dublagem + vídeo final
- editor_api: importa dub e speakers juntos.
- voice_chunks (falantes) vira a migração v15, depois da v14 do vídeo final (antes era criada fora das migrações).
- dub.voice_for: qualquer voz que não é o streamer (other1, other2…) usa a segunda voz da dublagem.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 03:59:44 -03:00
MateuusandClaude Opus 5.5 377536f778 Clipador: quem fala cada palavra (streamer × outra pessoa) e legenda em duas linhas
A fala de colegas no Discord e de outros jogadores saía na legenda como se fosse do
streamer. Agora cada palavra tem falante:

- voz: cada trecho de fala vira uma impressão de voz (WeSpeaker ResNet34-LM, ONNX,
  pesos CC-BY-4.0) na análise do bloco (~0,2 s de CPU por bloco); as vozes da sessão
  são agrupadas sob demanda (0,05 s) e a do streamer é a que mexe a boca na webcam
  (YuNet, nova série `mouth` no rastreio) ou a mais alta no áudio. Sem prova, tudo
  continua como do streamer.
- dados: `scoring.Word.speaker`; `words_json` aceita o 4º elemento; tabela
  `voice_chunks` (CREATE TABLE IF NOT EXISTS, fora da lista de migrações).
- legenda: streamer na posição normal e outra pessoa logo abaixo, em outra cor
  (`caption.otherColor`/`otherSize`); blocos nunca misturam falantes; os dois juntos
  = duas linhas; gancho desvia as duas; vertical e horizontal.
- tradução com `speaker` por linha; juízes recebem a transcrição marcada.
- painel: cor da outra pessoa na configuração, falante na transcrição do editor
  (com correção manual), prévia em duas linhas e "O que falam" no modal.
- doc/clipador/FALANTES.md com abordagem, licenças e qualidade medida na sessão 15.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 03:57:00 -03:00
MateuusandClaude Opus 5.5 e96e180da5 Integração: vídeo final ao aprovar + dublagem em português
Conflito em editor_api.render_clip_edit (as duas frentes mexeram na chamada de render): passa a tradução, `dev`
e o dublador juntos. review_layers: a dublagem sai das frases traduzidas, então sem frase (fonte em português) não
houve dublagem e o vídeo de revisão já é o final.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 03:49:39 -03:00
Mateuus 06f463e684 Merge branch 'clipper/final' into clipper/integ 2026-11-18 03:45:49 -03:00
MateuusandClaude Opus 5.5 7a428ee5da Clipador: dublagem em português por TTS no vídeo de revisão (dev.dub)
- app/dub.py: frases traduzidas → uma fala TTS por frase no serviço de voz
  (POST /v1/synthesize, WAV), cache em disco por (voz, velocidade, texto),
  encaixe sem sincronia labial (velocidade natural, escorre até 1,5 s sem
  acumular atraso, acelera no máximo 1,2× e corta com fade só se preciso,
  nunca duas falas juntas), frase partida no meio vira uma fala só, voz
  reserva offline e faixa única do trecho nivelada pelo volume do corte.
- editor_render.render_project: o áudio original abaixa (dubDuck, rampa
  de 0,15 s) só onde há dublagem; nada muda com dev=False. Devolve resumo.
- layout: dev.dubVoice, dev.dubVoiceOther (speaker "other") e dev.dubDuck.
- editor_api: prévia e render da fila passam o dublador; translation_for
  também traduz quando só a dublagem está ligada.
- Painel: switch "Dublagem em português (teste)", vozes TTS prontas (sem
  clone) e volume do original.
- doc/clipador/DUBLAGEM.md e tests/test_dub.py (TTS falso).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 03:45:14 -03:00
MateuusandClaude Opus 5.5 dc0917b114 Clipador: vídeo final sem camadas de teste ao aprovar; publicação só usa o final
Pedido do dono: o vídeo da fila é de revisão (com as camadas `dev`, ex.: tradução);
ao aprovar, o serviço renderiza de novo sem elas, e só esse vai para as redes.

- db v14: clips.review_dev_json (camadas que entraram na revisão) e final_status/
  final_file/final_thumb/final_cover/final_error/final_at; backfill dos cortes antigos.
- Motor: queue_final/drop_final/render_final; fila renderiza finais primeiro com
  render_clip_edit(dev=False) em clip-<id>-final.mp4; revisão sem camada de teste
  vira o final sem render novo; prune guarda os blocos de quem ainda precisa do final.
- API: clip traz review.devLayers, final e publishFile; aprovar enfileira o final;
  desaprovar, mudar trecho, exportar, re-render e rejudge derrubam o final;
  POST /v1/clips/{id}/final (tentar de novo).
- Painel: etiqueta na lista, player Final/Revisão e estado do final no modal
  (gerando/pronto/erro com "Tentar de novo"), aviso no "Publicar"; o despachante
  relê o corte antes de enviar e espera o final (clipPublishFile), nunca a revisão.
- Testes: clipper/tests/test_final_render.py e testes do despachante no painel.
- Doc: doc/clipador/REVISAO.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 03:27:26 -03:00
MateuusandClaude Opus 5.5 ad36f0faf4 Cartoon: foco da cena segue a narração e personagens no barco quando há água
- focusOf ignora objeto procurado, não encontrado ou só "parecido" (não mostra pronto o que o texto nega)
- stageFocus: com chão de água e arca em cena, quem aparece fica dentro do barco
- assunto grande mais à frente (z 0,35) e maior (arca 1,35; demais 1,4)
- Noé e a Arca ep01: tomadas regeradas e narração em velocidade 1,1
- .gitignore: worktrees temporárias dos subagentes

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 03:25:39 -03:00
66 changed files with 10269 additions and 6532 deletions
+3
View File
@@ -45,3 +45,6 @@ voice/vendor/
# Publicador: venv local # Publicador: venv local
publisher/.venv/ publisher/.venv/
# Worktrees temporárias dos subagentes do Claude Code
.claude/worktrees/
+32
View File
@@ -212,6 +212,37 @@ SCHEMA = [
""" """
ALTER TABLE clips ADD COLUMN translation_json TEXT; ALTER TABLE clips ADD COLUMN translation_json TEXT;
""", """,
# v14: vídeo de revisão × vídeo final (doc/clipador/REVISAO.md). O render da fila é o de REVISÃO (com as camadas
# `dev` ligadas); ao aprovar, sai o FINAL (`dev=False`) em `clip-<id>-final.mp4`, que é o único que se publica.
# `review_dev_json` = camadas de desenvolvimento que entraram no arquivo de revisão (["translation", ...]; [] =
# nenhuma → o de revisão já é o final; NULL = desconhecido → renderiza o final). `final_status`: pending |
# rendering | ready | error (NULL = sem final: não aprovado, ou a aprovação foi desfeita/editada).
# Cortes de antes da v14: a única camada de desenvolvimento era a tradução, que só entra com `translation_json`;
# sem ela o arquivo já é limpo ([]).
"""
ALTER TABLE clips ADD COLUMN review_dev_json TEXT;
ALTER TABLE clips ADD COLUMN final_status TEXT CHECK (final_status IN ('pending', 'rendering', 'ready', 'error'));
ALTER TABLE clips ADD COLUMN final_file TEXT;
ALTER TABLE clips ADD COLUMN final_thumb TEXT;
ALTER TABLE clips ADD COLUMN final_cover TEXT;
ALTER TABLE clips ADD COLUMN final_error TEXT;
ALTER TABLE clips ADD COLUMN final_at TEXT;
UPDATE clips SET review_dev_json = '[]' WHERE file IS NOT NULL AND translation_json IS NULL;
UPDATE clips SET final_status = 'pending' WHERE status = 'approved' AND review_dev_json IS NULL AND file IS NOT NULL;
UPDATE clips SET final_status = 'ready', final_file = file, final_thumb = thumb, final_at = updated_at
WHERE status IN ('approved', 'published') AND review_dev_json = '[]';
""",
# v15: falantes (doc/clipador/FALANTES.md). Impressões de voz dos trechos de fala de cada bloco (WeSpeaker), com o
# volume; as vozes da sessão são agrupadas sob demanda a partir daqui (speakers.SpeakerService).
"""
CREATE TABLE IF NOT EXISTS voice_chunks (
session_id INTEGER NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,
idx INTEGER NOT NULL,
data_json TEXT NOT NULL,
updated_at TEXT NOT NULL,
PRIMARY KEY (session_id, idx)
);
""",
] ]
@@ -237,6 +268,7 @@ class Database:
# Chat só fica "conectado" enquanto grava (sessões antigas ficaram com o estado velho gravado). # Chat só fica "conectado" enquanto grava (sessões antigas ficaram com o estado velho gravado).
self.run("UPDATE sessions SET chat_status = 'off' WHERE status NOT IN ('starting', 'recording') AND chat_status != 'off'") self.run("UPDATE sessions SET chat_status = 'off' WHERE status NOT IN ('starting', 'recording') AND chat_status != 'off'")
self.run("UPDATE clips SET status = 'pending' WHERE status = 'rendering'") self.run("UPDATE clips SET status = 'pending' WHERE status = 'rendering'")
self.run("UPDATE clips SET final_status = 'pending' WHERE final_status = 'rendering'") # vídeo final idem
def _migrate(self) -> None: def _migrate(self) -> None:
version = self.conn.execute("PRAGMA user_version").fetchone()[0] version = self.conn.execute("PRAGMA user_version").fetchone()[0]
+391
View File
@@ -0,0 +1,391 @@
"""Dublagem em português por TTS — camada SÓ de desenvolvimento (doc/clipador/DUBLAGEM.md).
Pedido do dono (18/11/2026): fonte em inglês → "quando ele estiver falando, a gente dubla em português; baixa o áudio
dele, deixa um pouco baixo para escutar o som do carro, do ambiente do jogo". Só entra no vídeo de REVISÃO
(`dev.dub`); o vídeo final, depois de aprovar, sai com o áudio original (`layout.dev_flags(cfg, dev=False)`).
Fluxo: frases traduzidas (`clips.translation_json` → `[{s, e, text, pt, speaker?}]`, tempo da sessão) → tempo de
saída (`editor.to_output`, respeita os trechos removidos) → uma fala TTS por frase pelo serviço de voz local
(`POST /v1/synthesize`, WAV), com cache em disco por (voz, velocidade, texto) → encaixe no tempo (`fit`) → UMA faixa
WAV do trecho renderizado (`Dubber.build`) que o `editor_render` mistura com a voz original abaixada (`duck_factors`).
Voz: TTS PRONTA do catálogo (padrão `pt-br-antonio`, masculina, Edge). Nunca clonar a voz do streamer — é um
terceiro sem consentimento; o projeto só aceita clonagem com consentimento de quem fala.
"""
from __future__ import annotations
import hashlib
import io
import logging
import os
import threading
import time
import uuid
import wave
from concurrent.futures import ThreadPoolExecutor
from dataclasses import dataclass, field
from pathlib import Path
from typing import Callable
import httpx
from . import layout, media
from .editor import to_output
log = logging.getLogger("cenaforge_clipper.dub")
FALLBACK_VOICE = "pt-br-faber" # Piper, offline: quando a voz escolhida (Edge, online) falha
SPEAKER_OTHER = "other" # `lines[].speaker` (FALANTES.md): "streamer" | "other1", "other2"…; ausente = streamer
# Esclarecimento do dono (18/11/2026): NÃO é dublagem de filme — é para a equipe entender o contexto. Nada de
# sincronia labial: cada fala começa perto do início da original, em velocidade natural (inteligível primeiro), e pode
# escorrer depois da fala original. Duas nunca tocam juntas e o atraso não acumula (limite por frase, `MAX_LATE_S`).
TTS_SPEED = 1.05 # quase natural: o português traduzido costuma ser mais longo que o inglês falado
MAX_TEMPO = 1.2 # aceleração máxima (atempo), só quando nem escorrendo cabe; acima disso fica difícil de entender
MAX_LATE_S = 1.5 # quanto uma fala pode começar depois da original (porque a anterior escorreu); nunca acumula
# Frase PARTIDA no meio pela transcrição (a 1ª não termina em . ! ? …), do mesmo falante e colada (vão menor que
# MERGE_GAP_S), vira uma fala só. Juntar frases completas foi medido pior (corte 259: 8,5 s perdidos contra 3,0 s).
MERGE_GAP_S = 0.4
MERGE_MAX_S = 7.0 # …desde que a junção não passe disso (tempo da fala original)
MERGE_MAX_CHARS = 140
SENTENCE_END = (".", "!", "?", "…", ".\"", "?\"", "!\"")
GAP_S = 0.08 # silêncio mínimo entre duas dublagens (nunca duas tocando juntas)
MIN_SLOT_S = 0.45 # espaço menor que isso: a frase não é dublada (não daria para entender)
FADE_S = 0.12 # fade de saída quando a fala precisa ser cortada
RAMP_S = 0.15 # rampa do ducking (desce antes da dublagem começar, sobe depois que ela acaba)
DUCK_HOLD_S = 0.6 # vão entre duas dublagens menor que isso: a voz original continua baixa (sem "bombear")
SAMPLE_RATE = 48000
# Nível da dublagem: cada fala é guardada a −16 LUFS (média ≈ −16,5 dB RMS sem as pausas). No render, ela é posta
# `LEVEL_OVER_ORIGINAL_DB` acima do volume médio do próprio corte (medido no áudio original) — live baixa (medido no
# corte 259 do tfue: −32 dB) não ganha uma voz 14 dB mais alta que ele. Ganho entre `GAIN_RANGE_DB`; limitador no fim.
TTS_LEVEL_DB = -16.5
LEVEL_OVER_ORIGINAL_DB = 6.0
GAIN_RANGE_DB = (-20.0, 3.0)
WORKERS = 3 # sínteses em paralelo (Edge é online; o serviço tem fila por chave)
SYNTH_TIMEOUT_S = 120
CACHE_KEEP_DAYS = 30 # fala do cache sem uso há mais que isso é apagada quando o serviço sobe
class DubError(RuntimeError):
"""Falha ao sintetizar uma frase (serviço fora, voz inexistente…)."""
# ---------------------------------------------------------------- configuração
def options(cfg: dict) -> dict:
"""Vozes e volume da dublagem a partir da configuração efetiva do corte (grupo `dev`)."""
group = {**layout.DEFAULTS["dev"], **(cfg.get("dev") or {})}
return {"voice": group["dubVoice"], "voiceOther": group["dubVoiceOther"] or group["dubVoice"],
"duck": float(group["dubDuck"])}
def voice_for(line: dict, opts: dict) -> str:
"""Voz da frase: qualquer voz que não é o streamer (`other`, `other1`, `other2`…) usa a segunda voz; sem o
campo, a padrão."""
speaker = line.get("speaker")
return opts["voiceOther"] if isinstance(speaker, str) and speaker.startswith(SPEAKER_OTHER) else opts["voice"]
# ---------------------------------------------------------------- plano (contas puras, sem áudio)
@dataclass(frozen=True)
class DubLine:
at: float # início da frase no tempo de SAÍDA (do corte inteiro)
text: str # português
voice: str
speaker: str | None = None
end: float = 0.0 # fim da fala original (tempo de saída); 0 = desconhecido
@dataclass(frozen=True)
class Cue:
"""Uma dublagem posicionada: começa em `at` (tempo de saída), toca `length` s, acelerada por `tempo`."""
at: float
length: float
tempo: float
cut: bool # não coube nem acelerada: termina com fade
index: int # posição em `lines`
def plan_lines(lines: list[dict], cuts: list[dict], opts: dict) -> list[DubLine]:
"""Frases da tradução (tempo da sessão) → frases no tempo de saída, em ordem. Frase sem português, ou que caiu
inteira num trecho removido (nada dela na saída), fica de fora; fala curta ("Okay." de 0,18 s) é dublada.
Frase partida no meio + continuação (mesmo falante, colada) viram uma fala só (ex.: "…deve dar" + "tudo certo.")."""
out: list[DubLine] = []
for line in lines or []:
text = " ".join(str(line.get("pt") or "").split())
if not text:
continue
try:
s, e = float(line["s"]), float(line["e"])
except (KeyError, TypeError, ValueError):
continue
a, _ = to_output(s, cuts)
b, _ = to_output(e, cuts)
if b - a < 0.05:
continue
speaker = line.get("speaker") if isinstance(line.get("speaker"), str) else None
out.append(DubLine(round(a, 3), text, voice_for(line, opts), speaker, round(b, 3)))
out.sort(key=lambda x: x.at)
merged: list[DubLine] = []
for line in out:
prev = merged[-1] if merged else None
if (prev and prev.voice == line.voice and not prev.text.endswith(SENTENCE_END)
and line.at - prev.end < MERGE_GAP_S and line.end - prev.at <= MERGE_MAX_S
and len(prev.text) + len(line.text) < MERGE_MAX_CHARS):
merged[-1] = DubLine(prev.at, f"{prev.text} {line.text}", prev.voice, prev.speaker, max(prev.end, line.end))
else:
merged.append(line)
return merged
def fit(lines: list[DubLine], durations: list[float | None], total: float) -> list[Cue]:
"""Encaixa cada fala no tempo. `durations[i]` = duração natural do TTS da frase i: 0 = a síntese falhou (a frase
some e não limita a anterior); None = não sintetizada neste render (fora do trecho: não toca, mas ainda é o
limite da anterior).
- Começa no início da frase original (ou logo depois da dublagem anterior, se ela escorreu).
- Toca em velocidade natural e pode escorrer até `MAX_LATE_S` depois do começo da próxima frase (que começa
depois dela). O limite é contado de cada frase original: o atraso nunca acumula.
- Só se nem assim couber: acelera até `MAX_TEMPO`; se ainda não couber, corta com fade.
- Nunca duas tocando juntas (`GAP_S` entre elas) e nunca depois do fim do corte."""
cues: list[Cue] = []
cursor = float("-inf")
for i, (line, natural) in enumerate(zip(lines, durations)):
if not natural or natural <= 0:
continue
start = max(line.at, cursor + GAP_S)
nxt = next((lines[j].at for j in range(i + 1, len(lines)) if durations[j] is None or durations[j] > 0), None)
limit = min(total, nxt + MAX_LATE_S - GAP_S) if nxt is not None else total
room = limit - start
if room < MIN_SLOT_S or start >= total:
log.info("dublagem: frase %d sem espaço (%.2f s) — fica sem dublar", i, room)
continue
tempo = 1.0 if natural <= room else min(MAX_TEMPO, natural / room)
length = natural / tempo
cut = length > room + 1e-6
if cut:
length = room
cues.append(Cue(round(start, 3), round(length, 3), round(tempo, 3), cut, i))
cursor = start + length
return cues
def duck_spans(cues: list[Cue], merge_gap: float = DUCK_HOLD_S) -> list[tuple[float, float]]:
"""Intervalos em que a voz original fica baixa (as dublagens, com vãos curtos emendados)."""
spans: list[list[float]] = []
for c in sorted(cues, key=lambda c: c.at):
a, b = c.at, c.at + c.length
if spans and a - spans[-1][1] < merge_gap + 2 * RAMP_S:
spans[-1][1] = max(spans[-1][1], b)
else:
spans.append([a, b])
return [(round(a, 3), round(b, 3)) for a, b in spans]
def duck_factors(spans: list[tuple[float, float]], duck: float, ramp: float = RAMP_S) -> list[str]:
"""Fatores (expressões do FFmpeg em `t`) que multiplicam o volume da voz original: 1 fora das falas dubladas,
`duck` durante, com rampa de `ramp` s antes e depois. Vão no `volume='…':eval=frame` do `editor_render`."""
if duck >= 1 or not spans:
return []
depth, r = 1 - max(0.0, duck), max(0.01, ramp)
return [f"(1-{depth:.3f}*clip(min((t-{a - r:.3f})/{r:.3f},({b + r:.3f}-t)/{r:.3f}),0,1))" for a, b in spans]
# ---------------------------------------------------------------- síntese com cache
def wav_duration(data: bytes) -> float:
with wave.open(io.BytesIO(data)) as w:
return w.getnframes() / float(w.getframerate() or 1)
def voice_synth(url: str | None, key: str | None) -> Callable[[str, str], bytes]:
"""Função (texto, voz) → WAV pelo serviço de voz local (`POST /v1/synthesize`, mesma chave do `VoiceClient`)."""
def synth(text: str, voice: str) -> bytes:
if not (url and key):
raise DubError("serviço de voz não instalado")
try:
response = httpx.post(f"{url}/v1/synthesize", timeout=SYNTH_TIMEOUT_S, headers={"X-Service-Key": key},
json={"requestId": f"clipper-dub-{uuid.uuid4().hex[:24]}", "text": text, "voiceId": voice,
"params": {"speed": TTS_SPEED, "format": "wav"}})
except httpx.HTTPError as exc:
raise DubError(f"serviço de voz fora do ar ({url})") from exc
if response.status_code != 200:
raise DubError(f"voz {voice} respondeu {response.status_code}: {response.text[:160]}")
return response.content
return synth
class TtsCache:
"""Fala TTS por (voz, velocidade, texto) em disco — prévia e render seguintes não sintetizam de novo.
Com FFmpeg, cada fala é guardada já limpa: sem o silêncio do começo/fim (o Edge põe ~0,5 s), volume igualado
(loudnorm −16 LUFS, vozes de motores diferentes ficam parecidas) e 48 kHz mono."""
def __init__(self, folder: Path, synth: Callable[[str, str], bytes], ffmpeg: str | None):
self.folder, self.synth, self.ffmpeg = folder, synth, ffmpeg
self.synth_calls = 0
self._guard = threading.Lock()
self._locks: dict[str, threading.Lock] = {}
def path(self, voice: str, text: str) -> Path:
digest = hashlib.sha256(f"{voice}|{TTS_SPEED:.2f}|{text}".encode("utf-8")).hexdigest()[:24]
return self.folder / f"{digest}.wav"
def get(self, voice: str, text: str) -> tuple[Path, float]:
"""(arquivo, duração em s) da fala; sintetiza só se ainda não estiver no cache."""
out = self.path(voice, text)
with self._guard:
lock = self._locks.setdefault(out.name, threading.Lock())
with lock:
if not out.is_file():
raw = self.synth(text, voice)
with self._guard:
self.synth_calls += 1
self.folder.mkdir(parents=True, exist_ok=True)
tmp = out.with_suffix(".tmp.wav")
if self.ffmpeg:
raw_file = out.with_suffix(".raw.wav")
raw_file.write_bytes(raw)
try:
trim = "silenceremove=start_periods=1:start_threshold=-50dB"
media.run([self.ffmpeg, "-y", "-v", "error", "-i", str(raw_file), "-af",
f"{trim},areverse,{trim},areverse,loudnorm=I=-16:TP=-1.5:LRA=11,aresample={SAMPLE_RATE}",
"-ac", "1", "-c:a", "pcm_s16le", str(tmp)], timeout=60)
finally:
raw_file.unlink(missing_ok=True)
else:
tmp.write_bytes(raw)
tmp.replace(out)
else:
try:
os.utime(out) # "usada agora": a limpeza (`prune`) apaga só o que ninguém usa há tempo
except OSError:
pass
return out, wav_duration(out.read_bytes())
def prune(self, keep_days: float = CACHE_KEEP_DAYS) -> int:
"""Apaga as falas sem uso há mais de `keep_days` dias. Devolve quantas apagou."""
limit = time.time() - keep_days * 86400
removed = 0
for file in self.folder.glob("*.wav") if self.folder.is_dir() else []:
try:
if file.stat().st_mtime < limit:
file.unlink()
removed += 1
except OSError:
continue
return removed
# ---------------------------------------------------------------- faixa do trecho renderizado
def gain_for(level_db: float | None) -> float:
"""Ganho (dB) da faixa de dublagem para o volume médio `level_db` do áudio original (None = sem medida: 0 dB)."""
if level_db is None:
return 0.0
lo, hi = GAIN_RANGE_DB
return round(min(hi, max(lo, level_db + LEVEL_OVER_ORIGINAL_DB - TTS_LEVEL_DB)), 1)
@dataclass
class DubTrack:
file: Path # WAV 48 kHz estéreo, do tamanho do trecho (t1 − t0), começando em t0
spans: list[tuple[float, float]] # ducking, em tempo relativo a t0
duck: float
cues: int
seconds: float # quanto a dublagem custou neste render (síntese + faixa)
synthesized: int # falas sintetizadas agora (o resto veio do cache)
failed: list[str] = field(default_factory=list)
class Dubber:
def __init__(self, cache: TtsCache, ffmpeg: str | None):
self.cache, self.ffmpeg = cache, ffmpeg
def _speech(self, line: DubLine) -> tuple[Path, float] | None:
try:
return self.cache.get(line.voice, line.text)
except (DubError, media.MediaError, OSError, wave.Error, EOFError) as exc:
if line.voice != FALLBACK_VOICE and not str(exc).startswith("serviço de voz"):
log.warning("dublagem: voz %s falhou (%s); tentando %s", line.voice, exc, FALLBACK_VOICE)
try:
return self.cache.get(FALLBACK_VOICE, line.text)
except (DubError, media.MediaError, OSError, wave.Error, EOFError) as exc2:
exc = exc2
log.warning("dublagem: frase sem áudio (%s)", exc)
return None
def build(self, translation: list[dict], cuts: list[dict], cfg: dict, t0: float, t1: float, work: Path,
stem: str, level_db: float | None = None) -> DubTrack | None:
"""Faixa da dublagem da saída [t0, t1]. Só sintetiza as frases que tocam nesse trecho (prévia de 5 s não
sintetiza o corte inteiro). `level_db` = volume médio do áudio original do corte (nivela a dublagem; ver
`gain_for`). None = nada para dublar (ou serviço de voz fora)."""
if not self.ffmpeg:
return None
started = time.monotonic()
before = self.cache.synth_calls
opts = options(cfg)
lines = plan_lines(translation, cuts, opts)
if not lines:
return None
total = round(sum(c["end"] - c["start"] for c in cuts), 3)
# Frases que podem tocar em [t0, t1]: começam antes de t1 e a próxima (+ atraso máximo) passa de t0.
wanted = [i for i, ln in enumerate(lines)
if ln.at < t1 and (lines[i + 1].at + MAX_LATE_S if i + 1 < len(lines) else total) > t0]
if wanted and wanted[0] > 0: # a anterior decide se a 1ª atrasa: entra na conta (não na faixa)
wanted.insert(0, wanted[0] - 1)
speech: dict[int, tuple[Path, float] | None] = {}
with ThreadPoolExecutor(max_workers=WORKERS) as pool:
for i, result in zip(wanted, pool.map(lambda i: self._speech(lines[i]), wanted)):
speech[i] = result
failed = [lines[i].text for i in wanted if speech.get(i) is None]
if wanted and len(failed) == len(wanted):
log.warning("dublagem: nenhuma fala sintetizada (%d frases) — vídeo sai sem dublagem", len(wanted))
return None
durations = [(speech[i][1] if speech[i] else 0.0) if i in speech else None for i in range(len(lines))]
# Fora de `wanted` a duração não é conhecida (None): a frase vizinha usa o começo dela (`at`) como limite, que
# é o que importa; essas frases não entram na faixa.
cues = [c for c in fit(lines, durations, total) if c.at < t1 and c.at + c.length > t0]
if not cues:
return None
out = work / f"{stem}.dub.wav"
self._mix(cues, [speech[c.index][0] for c in cues], t0, t1, out, gain_for(level_db)) # type: ignore[index]
spans = [(round(a - t0, 3), round(b - t0, 3)) for a, b in duck_spans(cues)]
return DubTrack(out, spans, opts["duck"], len(cues), round(time.monotonic() - started, 2),
self.cache.synth_calls - before, failed)
def _mix(self, cues: list[Cue], files: list[Path], t0: float, t1: float, out: Path, gain_db: float = 0.0) -> None:
"""Uma faixa só (48 kHz estéreo, `t1 − t0` s): cada fala acelerada/cortada e posta no lugar, com `gain_db`."""
length = t1 - t0
args: list[str] = [self.ffmpeg or "ffmpeg", "-y", "-v", "error"]
graph = [f"aevalsrc=0:s={SAMPLE_RATE}:d={length:.3f}[base]"]
for k, (cue, file) in enumerate(zip(cues, files)):
args += ["-i", str(file)]
chain = f"[{k}:a]aformat=sample_rates={SAMPLE_RATE}:channel_layouts=mono"
if cue.tempo > 1.001:
chain += f",atempo={cue.tempo:.3f}"
chain += f",atrim=end={cue.length:.3f}"
if cue.cut:
chain += f",afade=t=out:st={max(0.0, cue.length - FADE_S):.3f}:d={FADE_S:.3f}"
skip = t0 - cue.at
if skip > 0: # prévia que começa no meio desta fala
chain += f",atrim=start={skip:.3f}"
chain += f",asetpts=PTS-STARTPTS,adelay=delays={int(round(max(0.0, -skip) * 1000))}:all=1[d{k}]"
graph.append(chain)
graph.append("[base]" + "".join(f"[d{k}]" for k in range(len(cues)))
+ f"amix=inputs={len(cues) + 1}:duration=first:normalize=0,volume={gain_db:.1f}dB,"
f"alimiter=limit=0.9:level=0,aformat=channel_layouts=stereo[out]")
out.parent.mkdir(parents=True, exist_ok=True)
media.run([*args, "-filter_complex", ";".join(graph), "-map", "[out]", "-c:a", "pcm_s16le", "-t", f"{length:.3f}",
str(out)], timeout=120)
def for_engine(engine) -> Dubber:
"""Dublador do motor (um por processo, criado na 1ª vez): cache em `data/clipper/dub/`, voz pelo serviço local."""
dubber = getattr(engine, "_dubber", None)
if dubber is None:
settings = engine.settings
voice = getattr(engine, "voice", None)
synth = voice_synth(getattr(voice, "url", None) or settings.voice_url, getattr(voice, "key", None) or settings.voice_key)
cache = TtsCache(settings.data_dir / "dub", synth, settings.ffmpeg)
if cache.prune():
log.info("dublagem: cache limpo (falas sem uso há %d dias)", CACHE_KEEP_DAYS)
dubber = Dubber(cache, settings.ffmpeg)
engine._dubber = dubber
return dubber
+17 -2
View File
@@ -148,11 +148,22 @@ def output_words(project: dict) -> list[Word]:
if p.start <= mid <= p.end: if p.start <= mid <= p.end:
s = p.out + max(w["s"], p.start) - p.start s = p.out + max(w["s"], p.start) - p.start
e = p.out + min(w["e"], p.end) - p.start e = p.out + min(w["e"], p.end) - p.start
out.append(Word(round(s, 3), round(max(e, s + 0.05), 3), w["w"])) out.append(Word(round(s, 3), round(max(e, s + 0.05), 3), w["w"], w.get("sp") or ""))
break break
return out return out
def word_item(w: Word) -> dict:
"""Palavra da sessão → palavra do projeto. `sp` (quem fala; doc/clipador/FALANTES.md) só quando atribuído."""
item = {"s": w.start, "e": w.end, "w": w.word}
if w.speaker:
item["sp"] = w.speaker
return item
SPEAKER_RE = re.compile(r"^(streamer|other\d{0,2})$")
def emphasized(project: dict) -> set[tuple[float, str]]: def emphasized(project: dict) -> set[tuple[float, str]]:
return {(round(w["s"], 3), w["w"]) for w in project["captions"]["words"] if w.get("emph")} return {(round(w["s"], 3), w["w"]) for w in project["captions"]["words"] if w.get("emph")}
@@ -194,7 +205,7 @@ def default_project(clip: dict, words: list[Word], session_duration: float) -> d
"cuts": [{"start": round(clip["start_s"], 3), "end": round(clip["end_s"], 3), "mode": None}], "cuts": [{"start": round(clip["start_s"], 3), "end": round(clip["end_s"], 3), "mode": None}],
"captions": { "captions": {
"enabled": True, "preset": "classic", "style": {}, "emphColor": "#22E36B", "enabled": True, "preset": "classic", "style": {}, "emphColor": "#22E36B",
"words": [{"s": w.start, "e": w.end, "w": w.word} for w in words if lo <= w.start <= hi][:MAX_WORDS], "words": [word_item(w) for w in words if lo <= w.start <= hi][:MAX_WORDS],
}, },
"overlays": ([{"id": "hook", "kind": "hook", "text": hook, "start": 0.0, "end": 3.0, "y": 0.2, "size": 68, "overlays": ([{"id": "hook", "kind": "hook", "text": hook, "start": 0.0, "end": 3.0, "y": 0.2, "size": 68,
"color": "#FFFFFF", "box": "#E11D48", "anim": "pop"}] if hook else []), "color": "#FFFFFF", "box": "#E11D48", "anim": "pop"}] if hook else []),
@@ -440,6 +451,10 @@ def validate_project(data: dict, *, session_id: int, session_duration: float, re
if e <= s: # o Whisper às vezes devolve palavra com duração zero (medido no skipnho): ganha 50 ms if e <= s: # o Whisper às vezes devolve palavra com duração zero (medido no skipnho): ganha 50 ms
e = round(s + 0.05, 3) e = round(s + 0.05, 3)
item = {"s": s, "e": e, "w": _text(w.get("w", ""), f"palavra {i}", 40)} item = {"s": s, "e": e, "w": _text(w.get("w", ""), f"palavra {i}", 40)}
if w.get("sp"):
if not isinstance(w["sp"], str) or not SPEAKER_RE.match(w["sp"]):
raise EditError(f"palavra {i}: falante (sp) precisa ser streamer ou otherN")
item["sp"] = w["sp"]
if w.get("emph"): if w.get("emph"):
item["emph"] = True item["emph"] = True
if w.get("hidden"): if w.get("hidden"):
+39 -20
View File
@@ -21,7 +21,7 @@ from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse from fastapi.responses import JSONResponse
from pydantic import BaseModel, Field from pydantic import BaseModel, Field
from . import editor, editor_render, layout, media from . import dub, editor, editor_render, layout, media, speakers
from .config import REPO_ROOT from .config import REPO_ROOT
from .db import loads, now from .db import loads, now
from .judge import JudgeError, _chat_block, _transcript from .judge import JudgeError, _chat_block, _transcript
@@ -93,8 +93,10 @@ def load_edit(engine, clip_id: int) -> dict | None:
return row return row
def render_clip_edit(engine, clip: dict, session: dict, edit: dict, out: Path, thumb: Path) -> str | None: def render_clip_edit(engine, clip: dict, session: dict, edit: dict, out: Path, thumb: Path, dev: bool = True) -> str | None:
"""Render do corte pelo projeto de edição (chamado pela fila do motor). Devolve o caminho da capa (ou None).""" """Render do corte pelo projeto de edição (chamado pela fila do motor). Devolve o caminho da capa (ou None).
`dev=True` = vídeo de REVISÃO (com as camadas `dev` ligadas; grava quais entraram em `clips.review_dev_json`);
`dev=False` = vídeo FINAL, depois de aprovar (sem nenhuma camada de desenvolvimento) — doc/clipador/REVISAO.md."""
project = validate_for(engine, clip, session, edit["project"]) project = validate_for(engine, clip, session, edit["project"])
segments = session_segments(engine, clip["session_id"]) segments = session_segments(engine, clip["session_id"])
if engine._encoder is None: if engine._encoder is None:
@@ -111,9 +113,13 @@ def render_clip_edit(engine, clip: dict, session: dict, edit: dict, out: Path, t
except media.MediaError as exc: # capa é extra: o vídeo vale mesmo sem ela except media.MediaError as exc: # capa é extra: o vídeo vale mesmo sem ela
log.warning("capa do corte %s falhou: %s", clip["id"], exc) log.warning("capa do corte %s falhou: %s", clip["id"], exc)
cover = None cover = None
translation = translation_for(engine, clip, project, base, dev=dev)
editor_render.render_project(ffmpeg, engine.settings.ffprobe, engine._encoder, segments, project, base, credit, out, 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)) translation=translation, dev=dev, dubber=dub.for_engine(engine))
if dev:
layers = review_layers(editor.effective_settings(base, project), translation)
engine.db.run("UPDATE clips SET review_dev_json = ? WHERE id = ?", json.dumps(layers), clip["id"])
total = editor.output_duration(project["cuts"]) total = editor.output_duration(project["cuts"])
media.thumbnail(ffmpeg, out, min(3.0, total / 2), thumb) 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. # Formato em que ESTE arquivo saiu (camadas padrão ← canal ← sessão ← projeto): a fila desenha o player por ele.
@@ -121,11 +127,24 @@ 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 return cover.relative_to(REPO_ROOT).as_posix() if cover else None
def review_layers(cfg: dict, translation: list[dict] | None) -> list[str]:
"""Camadas de desenvolvimento que entraram no vídeo de revisão (vazio = ele já é o vídeo final). A tradução só
conta se havia frases para desenhar (fonte em português nunca tem); as outras chaves do grupo `dev` (dublagem…)
contam pela configuração, por cautela: na dúvida, o final é renderizado de novo. A dublagem sai das mesmas frases
traduzidas (DUBLAGEM.md): sem frase, também não houve dublagem."""
flags = dict(layout.dev_flags(cfg, True))
if not translation:
flags["translation"] = flags["dub"] = False
return sorted(k for k, on in flags.items() if on)
def translation_for(engine, clip: dict, project: dict, base: dict, dev: bool = True) -> list[dict] | None: def translation_for(engine, clip: dict, project: dict, base: dict, dev: bool = True) -> list[dict] | None:
"""Frases traduzidas para a legenda de desenvolvimento (doc/clipador/IDIOMAS.md): só com `dev.translation` """Frases traduzidas para a legenda de desenvolvimento (doc/clipador/IDIOMAS.md) e a dublagem
ligado, render de desenvolvimento e fonte em inglês. Traduz o trecho do projeto se ainda não houver tradução.""" (doc/clipador/DUBLAGEM.md): só com `dev.translation` ou `dev.dub` ligado, render de desenvolvimento e fonte em
inglês. Traduz o trecho do projeto se ainda não houver tradução."""
cfg = editor.effective_settings(base, project) cfg = editor.effective_settings(base, project)
if not layout.dev_flags(cfg, dev)["translation"]: flags = layout.dev_flags(cfg, dev)
if not (flags["translation"] or flags["dub"]):
return None return None
ps = editor.pieces(project["cuts"]) ps = editor.pieces(project["cuts"])
if not ps: if not ps:
@@ -151,9 +170,7 @@ def auto_for(engine, clip: dict, session: dict) -> dict:
"""Projeto que a IA entrega: o que o pipeline já sabe (análise, Whisper, volume, configuração do corte).""" """Projeto que a IA entrega: o que o pipeline já sabe (análise, Whisper, volume, configuração do corte)."""
judge = _judge(clip) judge = _judge(clip)
lo, hi = editor.default_window(clip, session["duration_s"]) lo, hi = editor.default_window(clip, session["duration_s"])
rows = engine.db.all("SELECT words_json FROM segments WHERE session_id = ? AND end_s > ? AND start_s < ? ORDER BY idx", words = engine.words_between(clip["session_id"], lo, hi) # já com quem fala cada palavra (FALANTES.md)
clip["session_id"], lo, hi)
words = [Word(a, b, c) for r in rows for a, b, c in loads(r["words_json"], [])]
loudness = engine.load_timeline(clip["session_id"], max(0.0, lo - 5))["loudness"] loudness = engine.load_timeline(clip["session_id"], max(0.0, lo - 5))["loudness"]
return editor.auto_project(clip, judge.get("analysis"), words, loudness, session["duration_s"], return editor.auto_project(clip, judge.get("analysis"), words, loudness, session["duration_s"],
engine.intel.settings_for(session), model=judge.get("model") or "", generated_at=now()) engine.intel.settings_for(session), model=judge.get("model") or "", generated_at=now())
@@ -240,9 +257,7 @@ def register(app: FastAPI, engine, clip_view, get_clip) -> None:
return round(lo, 3), round(hi, 3) return round(lo, 3), round(hi, 3)
def _words(session_id: int, lo: float, hi: float) -> list[Word]: def _words(session_id: int, lo: float, hi: float) -> list[Word]:
rows = db.all("SELECT words_json FROM segments WHERE session_id = ? AND end_s > ? AND start_s < ? ORDER BY idx", return [w for w in engine.words_between(session_id, lo, hi) if lo <= w.start <= hi]
session_id, lo, hi)
return [Word(a, b, c) for r in rows for a, b, c in loads(r["words_json"], []) if lo <= a <= hi]
def _cached_proxy(clip: dict, lo: float, hi: float) -> dict | None: def _cached_proxy(clip: dict, lo: float, hi: float) -> dict | None:
f = edit_dir(engine, clip["session_id"], clip["id"]) / f"proxy-{_window_key(lo, hi)}.mp4" f = edit_dir(engine, clip["session_id"], clip["id"]) / f"proxy-{_window_key(lo, hi)}.mp4"
@@ -282,7 +297,7 @@ def register(app: FastAPI, engine, clip_view, get_clip) -> None:
"origin": row["origin"] if row else "ai", "aiProject": ai_project, "origin": row["origin"] if row else "ai", "aiProject": ai_project,
"exportedAt": row["exported_at"] if row else None, "cover": row["cover"] if row else None, "exportedAt": row["exported_at"] if row else None, "cover": row["cover"] if row else None,
"window": {"lo": w_lo, "hi": w_hi}, "sessionDurationS": session["duration_s"], "window": {"lo": w_lo, "hi": w_hi}, "sessionDurationS": session["duration_s"],
"words": [{"s": w.start, "e": w.end, "w": w.word} for w in _words(clip["session_id"], w_lo, w_hi)], "words": [editor.word_item(w) for w in _words(clip["session_id"], w_lo, w_hi)],
"chat": chat, "chatPerS": per_s, "loudnessDb": loud, "analysis": analysis, "chat": chat, "chatPerS": per_s, "loudnessDb": loud, "analysis": analysis,
"settings": engine.intel.settings_for(session), "credit": engine.channel_label(session), "settings": engine.intel.settings_for(session), "credit": engine.channel_label(session),
"presets": [{"id": k, "label": editor.PRESET_LABEL[k], "style": editor.PRESET_STYLE[k]} for k in editor.CAPTION_PRESETS], "presets": [{"id": k, "label": editor.PRESET_LABEL[k], "style": editor.PRESET_STYLE[k]} for k in editor.CAPTION_PRESETS],
@@ -333,8 +348,7 @@ def register(app: FastAPI, engine, clip_view, get_clip) -> None:
editor_render.make_proxy(ffmpeg, session_segments(engine, clip["session_id"]), lo, hi, folder / name) editor_render.make_proxy(ffmpeg, session_segments(engine, clip["session_id"]), lo, hi, folder / name)
log.info("proxy do corte %s (%.0f s de vídeo) em %.1f s", clip_id, hi - lo, time.monotonic() - t) log.info("proxy do corte %s (%.0f s de vídeo) em %.1f s", clip_id, hi - lo, time.monotonic() - t)
_clean_old(folder, "proxy", name) _clean_old(folder, "proxy", name)
return _cached_proxy(clip, lo, hi) | {"words": [{"s": w.start, "e": w.end, "w": w.word} return _cached_proxy(clip, lo, hi) | {"words": [editor.word_item(w) for w in _words(clip["session_id"], lo, hi)]}
for w in _words(clip["session_id"], lo, hi)]}
@app.get("/v1/clips/{clip_id}/waveform") @app.get("/v1/clips/{clip_id}/waveform")
def get_waveform(clip_id: int, lo: float, hi: float): def get_waveform(clip_id: int, lo: float, hi: float):
@@ -380,7 +394,8 @@ def register(app: FastAPI, engine, clip_view, get_clip) -> None:
editor_render.render_project(ffmpeg, settings.ffprobe, ["-c:v", "libx264", "-preset", "veryfast", "-crf", "24"], editor_render.render_project(ffmpeg, settings.ffprobe, ["-c:v", "libx264", "-preset", "veryfast", "-crf", "24"],
segments, project, base, credit, out, REPO_ROOT, 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)) translation=translation_for(engine, clip, project, base),
dubber=dub.for_engine(engine))
took = time.monotonic() - t took = time.monotonic() - t
return {"file": out.relative_to(REPO_ROOT).as_posix(), "fromS": a, "toS": b, "seconds": round(took, 1), "version": now()} return {"file": out.relative_to(REPO_ROOT).as_posix(), "fromS": a, "toS": b, "seconds": round(took, 1), "version": now()}
@@ -401,6 +416,7 @@ def register(app: FastAPI, engine, clip_view, get_clip) -> None:
db.run("UPDATE clips SET start_s = ?, end_s = ?, status = 'pending', error = NULL, transcript = ?, updated_at = ? WHERE id = ?", db.run("UPDATE clips SET start_s = ?, end_s = ?, status = 'pending', error = NULL, transcript = ?, updated_at = ? WHERE id = ?",
start, end, " ".join(w.word for w in words)[:4000], ts, clip_id) start, end, " ".join(w.word for w in words)[:4000], ts, clip_id)
db.run("UPDATE edits SET exported_at = ? WHERE clip_id = ?", ts, clip_id) db.run("UPDATE edits SET exported_at = ? WHERE clip_id = ?", ts, clip_id)
engine.drop_final(clip_id) # editou: o final antigo deixa de valer; volta a ser revisão (aprovar de novo)
engine.wake_clips.set() engine.wake_clips.set()
return clip_view(get_clip(clip_id)) | {"editedDurationS": editor.output_duration(project["cuts"])} return clip_view(get_clip(clip_id)) | {"editedDurationS": editor.output_duration(project["cuts"])}
@@ -420,8 +436,11 @@ def register(app: FastAPI, engine, clip_view, get_clip) -> None:
words = engine.voice.transcribe(wav, f"clipper-edit-{clip_id}-{uuid.uuid4().hex[:12]}") words = engine.voice.transcribe(wav, f"clipper-edit-{clip_id}-{uuid.uuid4().hex[:12]}")
except Exception as exc: # noqa: BLE001 - erro do serviço de voz vira mensagem except Exception as exc: # noqa: BLE001 - erro do serviço de voz vira mensagem
raise editor.EditError(f"transcrição falhou: {str(exc)[:200]}") from exc raise editor.EditError(f"transcrição falhou: {str(exc)[:200]}") from exc
# Quem fala: o mesmo das palavras antigas no mesmo instante (a re-transcrição não sabe o falante).
fresh = speakers.transfer([Word(round(w.start + a, 3), round(w.end + a, 3), w.word) for w in words],
_words(clip["session_id"], a - 1, b + 1))
return {"startS": a, "endS": b, "seconds": round(time.monotonic() - t, 1), return {"startS": a, "endS": b, "seconds": round(time.monotonic() - t, 1),
"words": [{"s": round(w.start + a, 3), "e": round(w.end + a, 3), "w": w.word} for w in words]} "words": [editor.word_item(w) for w in fresh]}
@app.post("/v1/clips/{clip_id}/tts") @app.post("/v1/clips/{clip_id}/tts")
def tts(clip_id: int, body: TtsIn): def tts(clip_id: int, body: TtsIn):
@@ -464,12 +483,12 @@ def register(app: FastAPI, engine, clip_view, get_clip) -> None:
project = validate_for(engine, clip, session, data) project = validate_for(engine, clip, session, data)
lo, hi = project["source"]["lo"], project["source"]["hi"] lo, hi = project["source"]["lo"], project["source"]["hi"]
tl = engine.load_timeline(clip["session_id"], max(0.0, lo - 5)) tl = engine.load_timeline(clip["session_id"], max(0.0, lo - 5))
words = [Word(w["s"], w["e"], w["w"]) for w in project["captions"]["words"]] or tl["words"] words = [Word(w["s"], w["e"], w["w"], w.get("sp") or "") for w in project["captions"]["words"]] or tl["words"]
view = clip_view(clip) view = clip_view(clip)
analysis = (view["judge"] or {}).get("analysis") if isinstance(view["judge"], dict) else None analysis = (view["judge"] or {}).get("analysis") if isinstance(view["judge"], dict) else None
cfg = editor.effective_settings(engine.intel.settings_for(session), project) cfg = editor.effective_settings(engine.intel.settings_for(session), project)
prompt = editor.suggest_prompt(engine.streamer_name(session), clip["title"], project, tl["chat"], analysis, prompt = editor.suggest_prompt(engine.streamer_name(session), clip["title"], project, tl["chat"], analysis,
_transcript(words, lo, hi), _chat_block(tl["chat"], lo, hi, clip["peak_s"]), cfg) _transcript(words, lo, hi, streamer=engine.streamer_name(session)), _chat_block(tl["chat"], lo, hi, clip["peak_s"]), cfg)
t = time.monotonic() t = time.monotonic()
try: try:
raw = engine.judge.ask(editor.SUGGEST_SYSTEM, prompt, editor.SUGGEST_SCHEMA, []) raw = engine.judge.ask(editor.SUGGEST_SYSTEM, prompt, editor.SUGGEST_SCHEMA, [])
+135 -38
View File
@@ -9,15 +9,21 @@ só entram números formatados aqui e nomes de arquivo relativos gerados por nó
from __future__ import annotations from __future__ import annotations
import logging
import re
import shutil import shutil
import subprocess
from array import array from array import array
from pathlib import Path from pathlib import Path
from . import layout, media, reframe from . import dub, layout, media, reframe
from .editor import Piece, effective_settings, emphasized, output_duration, output_words, pieces, slice_pieces, to_output from .editor import Piece, effective_settings, emphasized, output_duration, output_words, pieces, slice_pieces, to_output
from .scoring import Word from .scoring import Word
from .subtitles import _escape, _ts, caption_blocks, clean_words from .speakers import is_other
from .subtitles import (OTHER_LANE, STREAMER_LANE, _escape, _ts, caption_blocks, clean_words, has_other, lane,
other_color, other_offset, other_size, other_y)
log = logging.getLogger("cenaforge_clipper.editor_render")
W, H = layout.W, layout.H # quadro do vertical (padrão dos parâmetros); o formato real vem da configuração W, H = layout.W, layout.H # quadro do vertical (padrão dos parâmetros); o formato real vem da configuração
FPS = 30 FPS = 30
PEAKS_PER_S = 50 PEAKS_PER_S = 50
@@ -79,10 +85,12 @@ def banner_layout(o: dict, canvas: tuple[int, int]) -> dict:
def hook_dodges(project: dict, canvas: tuple[int, int], cap_y: int, cap_size: int, def hook_dodges(project: dict, canvas: tuple[int, int], cap_y: int, cap_size: int,
total: float) -> list[tuple[float, float, int]]: total: float, below: int = 0) -> list[tuple[float, float, int]]:
"""Onde a legenda vai enquanto cada gancho está na tela, se ele a cobriria: [(início, fim, y do centro)]. """Onde a legenda vai enquanto cada gancho está na tela, se ele a cobriria: [(início, fim, y do centro)].
Com a câmera em cima, o gancho fica logo abaixo dela (layout.hook_y) — o mesmo lugar da legenda automática Com a câmera em cima, o gancho fica logo abaixo dela (layout.hook_y) — o mesmo lugar da legenda automática
(emenda câmera/jogo). Nesses segundos a legenda desce para logo abaixo do gancho; depois volta ao lugar.""" (emenda câmera/jogo). Nesses segundos a legenda desce para logo abaixo do gancho; depois volta ao lugar.
`below` = quanto a legenda ocupa ABAIXO do centro além do próprio tamanho (a linha de outra pessoa,
doc/clipador/FALANTES.md): as duas linhas desviam juntas. 0 = só a linha do streamer (como antes)."""
_, ch = canvas _, ch = canvas
out = [] out = []
for o in project["overlays"]: for o in project["overlays"]:
@@ -94,10 +102,11 @@ def hook_dodges(project: dict, canvas: tuple[int, int], cap_y: int, cap_size: in
else: else:
cy, half = int(ch * o["y"]), int(o["size"] * 0.9) cy, half = int(ch * o["y"]), int(o["size"] * 0.9)
top, bottom = cy - half, cy + half top, bottom = cy - half, cy + half
if cap_y + cap_size <= top or cap_y - cap_size >= bottom: reach = max(cap_size, below) # até onde a legenda (com a linha de baixo) desce a partir do centro
if cap_y + reach <= top or cap_y - cap_size >= bottom:
continue # não se encostam continue # não se encostam
below = bottom + cap_size + 12 under = bottom + cap_size + 12
y = below if below + cap_size <= ch else max(cap_size, top - cap_size - 12) y = under if under + reach <= ch else max(cap_size, top - reach - 12)
out.append((float(o["start"]), float(min(o["end"], total)), y)) out.append((float(o["start"]), float(min(o["end"], total)), y))
return out return out
@@ -220,6 +229,17 @@ def build_project_ass(project: dict, cfg: dict, credit: str, t0: float = 0.0, t1
tsize = max(30, int(size * 0.5)) 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," 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 flags["translation"] and translation else "" f"{max(3, ow // 2)},2,8,60,60,0,1\n") if flags["translation"] and translation else ""
# Fala de outra pessoa (doc/clipador/FALANTES.md): faixa própria, logo abaixo, noutra cor e tamanho. Os estilos
# só entram quando o corte tem outra pessoa: o ASS de um corte só com o streamer fica idêntico ao de antes.
spoken = sorted((w for w in output_words(project) if w.word.strip()), key=lambda w: (w.start, w.end))
two = bool(cap["enabled"]) and has_other(spoken)
osize = other_size(cap)
other_c = layout.ass_color(other_color(cap))
oow = max(2, int(ow) * osize // max(1, int(size))) if ow else 0
other_styles = (f"Style: CaptionOther,{font},{osize},{other_c},{other_c},{outline},&H80000000,-1,0,0,0,100,100,0,0,1,"
f"{oow},3,5,60,60,0,1\n"
f"Style: KaraokeOther,{font},{osize},{high},{other_c},{outline},&H80000000,-1,0,0,0,100,100,0,0,1,"
f"{oow},3,5,60,60,0,1\n") if two else ""
header = f"""[Script Info] header = f"""[Script Info]
ScriptType: v4.00+ ScriptType: v4.00+
PlayResX: {cw} PlayResX: {cw}
@@ -231,7 +251,7 @@ ScaledBorderAndShadow: yes
Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding
Style: Caption,{font},{size},{base},{base},{outline},&H80000000,-1,0,0,0,100,100,0,0,1,{ow},3,5,60,60,0,1 Style: Caption,{font},{size},{base},{base},{outline},&H80000000,-1,0,0,0,100,100,0,0,1,{ow},3,5,60,60,0,1
Style: Karaoke,{font},{size},{high},{base},{outline},&H80000000,-1,0,0,0,100,100,0,0,1,{ow},3,5,60,60,0,1 Style: Karaoke,{font},{size},{high},{base},{outline},&H80000000,-1,0,0,0,100,100,0,0,1,{ow},3,5,60,60,0,1
Style: Credit,Arial,{cred['size']},&H00FFFFFF,&H00FFFFFF,&H00000000,&H80000000,-1,0,0,0,100,100,0,0,1,3,1,{credit_align},{credit_side},{credit_side},{credit_margin},1 {other_styles}Style: Credit,Arial,{cred['size']},&H00FFFFFF,&H00FFFFFF,&H00000000,&H80000000,-1,0,0,0,100,100,0,0,1,3,1,{credit_align},{credit_side},{credit_side},{credit_margin},1
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: 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: 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: Bar,Arial,10,&H00FFFFFF,&H00FFFFFF,&H00000000,&H00000000,0,0,0,0,100,100,0,0,1,0,0,7,0,0,0,1
@@ -255,35 +275,61 @@ Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text
emph = emphasized(project) emph = emphasized(project)
emph_c = layout.ass_inline_color(project["captions"]["emphColor"]) emph_c = layout.ass_inline_color(project["captions"]["emphColor"])
hi_c, base_c = layout.ass_inline_color(cap["highlight"]), layout.ass_inline_color(cap["color"]) hi_c, base_c = layout.ass_inline_color(cap["highlight"]), layout.ass_inline_color(cap["color"])
pos = f"\\pos({cw // 2},{layout.caption_y(cfg)})" oth_c = layout.ass_inline_color(other_color(cap))
dodges = hook_dodges(project, (cw, ch), layout.caption_y(cfg), int(cap["size"]), total) cap_y = layout.caption_y(cfg)
pos = f"\\pos({cw // 2},{cap_y})"
trans_on = bool(flags["translation"] and translation)
# Linha de outra pessoa logo abaixo da do streamer. Com a tradução de desenvolvimento ligada, a tradução do
# streamer (até 2 linhas) fica ENTRE as duas e a de outra pessoa, embaixo da linha dela.
offset = other_offset(int(size), osize, int(2.4 * tsize) + 6 if trans_on else 0)
# O gancho desvia as duas linhas juntas (a de baixo conta na altura ocupada).
below = offset + int(0.6 * osize) + (int(2.4 * tsize) if trans_on else 0) if two else 0
# Sem espaço embaixo para a linha de outra pessoa (horizontal: a legenda já fica a 85 % da altura), a do
# streamer SOBE o necessário: a ordem nunca inverte (streamer em cima, outra pessoa embaixo).
if two:
cap_y = min(cap_y, ch - 8 - below)
pos = f"\\pos({cw // 2},{cap_y})"
dodges = hook_dodges(project, (cw, ch), cap_y, int(cap["size"]), total, below=below)
def y_at(t: float) -> int: def y_at(t: float) -> int:
"""Altura (centro) da legenda no instante t (saída): desviada enquanto um gancho a cobriria.""" """Altura (centro) da legenda do streamer no instante t (saída): desviada enquanto um gancho a cobriria."""
for s, e, y in dodges: for s, e, y in dodges:
if s <= t < e: if s <= t < e:
return y return y
return layout.caption_y(cfg) return cap_y
def at(t: float) -> str: def oy_at(t: float) -> int:
"""Posição da legenda no instante t (saída).""" """Altura (centro) da linha de outra pessoa no instante t (saída)."""
return other_y(y_at(t), offset, osize, ch)
def at(t: float, other: bool = False) -> str:
"""Posição da legenda no instante t (saída). `\\pos` fixo: o libass não empilha as duas linhas."""
if other:
return f"\\pos({cw // 2},{oy_at(t)})"
y = y_at(t) y = y_at(t)
return pos if y == layout.caption_y(cfg) else f"\\pos({cw // 2},{y})" return pos if y == cap_y else f"\\pos({cw // 2},{y})"
# Ênfase: palavra de saída ↔ palavra marcada no projeto (mesmo texto, mesmo instante), casada nos tempos # Ê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 # ORIGINAIS. Depois as palavras são saneadas POR FAIXA (ordem, sem sobreposição, duração mínima) —
# a mesma quantidade, na mesma ordem — e os blocos abaixo nunca ficam dois na tela ao mesmo tempo. # `clean_words` devolve a mesma quantidade, na mesma ordem — e os blocos de uma faixa nunca ficam dois na
raw = sorted((w for w in output_words(project) if w.word.strip()), key=lambda w: (w.start, w.end)) # tela ao mesmo tempo (as duas faixas, sim: cada uma na sua linha).
raw = spoken
raw_emph = _match_emphasis(raw, project, emph) raw_emph = _match_emphasis(raw, project, emph)
words = clean_words(raw) words: list[Word] = list(raw)
for name in (STREAMER_LANE, OTHER_LANE):
idxs = [i for i, w in enumerate(raw) if lane(w.speaker) == name]
for i, w in zip(idxs, clean_words([raw[i] for i in idxs])):
words[i] = w
def txt(w: Word) -> str: def txt(w: Word) -> str:
return _escape(w.word.upper() if cap["uppercase"] else w.word) return _escape(w.word.upper() if cap["uppercase"] else w.word)
def key(w: Word) -> tuple[float, str]: def key(w: Word) -> tuple[float, str, str]:
return round(w.start, 3), w.word # depois de clean_words, cada início é único return round(w.start, 3), w.word, lane(w.speaker) # depois de clean_words, cada início é único na faixa
emph_keys = {key(words[i]) for i in raw_emph} emph_keys = {key(words[i]) for i in raw_emph}
for group, g_end in caption_blocks(words, cap["maxWords"]): for group, g_end in caption_blocks(words, cap["maxWords"]):
other = lane(group[0].speaker) == OTHER_LANE
base_g = oth_c if other else base_c
if preset == "karaoke": if preset == "karaoke":
parts, cursor = [], group[0].start parts, cursor = [], group[0].start
for w in group: for w in group:
@@ -292,40 +338,46 @@ Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text
color = f"\\1c{emph_c}" if key(w) in emph_keys else "" color = f"\\1c{emph_c}" if key(w) in emph_keys else ""
parts.append((f"{{\\k{gap}}}" if gap else "") + f"{{\\kf{dur}{color}}}{txt(w)}") parts.append((f"{{\\k{gap}}}" if gap else "") + f"{{\\kf{dur}{color}}}{txt(w)}")
cursor = w.end cursor = w.end
event(0, group[0].start, g_end, "Karaoke", f"{{{at(group[0].start)}}}" + " ".join(parts)) event(0, group[0].start, g_end, "KaraokeOther" if other else "Karaoke",
f"{{{at(group[0].start, other)}}}" + " ".join(parts))
continue continue
style = "CaptionOther" if other else "Caption"
for i, word in enumerate(group): for i, word in enumerate(group):
start = word.start start = word.start
end = group[i + 1].start if i + 1 < len(group) else g_end end = group[i + 1].start if i + 1 < len(group) else g_end
if end <= start: if end <= start:
continue continue
if preset == "single": if preset == "single":
color = emph_c if key(word) in emph_keys else (hi_c if len(group) > 1 else base_c) color = emph_c if key(word) in emph_keys else (hi_c if len(group) > 1 else base_g)
event(0, start, end, "Caption", f"{{{at(start)}{_anim('pop')}\\c{color}}}{txt(word)}") event(0, start, end, style, f"{{{at(start, other)}{_anim('pop')}\\c{color}}}{txt(word)}")
continue continue
parts = [] parts = []
for j, w in enumerate(group): for j, w in enumerate(group):
is_emph = key(w) in emph_keys is_emph = key(w) in emph_keys
if preset == "minimal": if preset == "minimal":
parts.append(f"{{\\c{emph_c}}}{txt(w)}{{\\c{base_c}}}" if is_emph else txt(w)) parts.append(f"{{\\c{emph_c}}}{txt(w)}{{\\c{base_g}}}" if is_emph else txt(w))
elif j == i: elif j == i:
color = emph_c if is_emph else hi_c color = emph_c if is_emph else hi_c
pop = "\\fscx118\\fscy118\\t(0,130,\\fscx100\\fscy100)" if preset == "pop" else "" pop = "\\fscx118\\fscy118\\t(0,130,\\fscx100\\fscy100)" if preset == "pop" else ""
parts.append(f"{{\\c{color}{pop}}}{txt(w)}{{\\c{base_c}\\fscx100\\fscy100}}") parts.append(f"{{\\c{color}{pop}}}{txt(w)}{{\\c{base_g}\\fscx100\\fscy100}}")
else: else:
parts.append(f"{{\\c{emph_c}}}{txt(w)}{{\\c{base_c}}}" if is_emph else txt(w)) parts.append(f"{{\\c{emph_c}}}{txt(w)}{{\\c{base_g}}}" if is_emph else txt(w))
intro = "\\fscx85\\fscy85\\t(0,90,\\fscx100\\fscy100)" if preset == "pop" and i == 0 else "" 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)) event(0, start, end, style, f"{{{at(start, other)}{intro}}}" + " ".join(parts))
if flags["translation"] and translation: if trans_on:
# Só para desenvolver (doc/clipador/IDIOMAS.md): a frase traduzida em português, menor e em azul claro, # 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). # logo embaixo da legenda de QUEM FALA (`speaker` da linha; sem ele, o streamer) — \\an8 = cresce para
for line in translation: # baixo; \\q0 = quebra a linha se for longa.
for line in translation or []:
a, _ = to_output(float(line["s"]), project["cuts"]) a, _ = to_output(float(line["s"]), project["cuts"])
b, _ = to_output(float(line["e"]), project["cuts"]) b, _ = to_output(float(line["e"]), project["cuts"])
if b - a < 0.2 or not str(line.get("pt") or "").strip(): if b - a < 0.2 or not str(line.get("pt") or "").strip():
continue continue
y = y_at(a) + int(size * 0.62) if two and is_other(line.get("speaker")):
y = oy_at(a) + int(osize * 0.62)
else:
y = y_at(a) + int(size * 0.62)
event(0, a, b, "Trans", f"{{\\an8\\pos({cw // 2},{y})\\q0}}{_escape(str(line['pt']))}") event(0, a, b, "Trans", f"{{\\an8\\pos({cw // 2},{y})\\q0}}{_escape(str(line['pt']))}")
cuts = project["cuts"] cuts = project["cuts"]
@@ -416,12 +468,14 @@ def zoom_filter(project: dict, t0: float = 0.0, size: tuple[int, int] = (W, H))
class AudioInput: class AudioInput:
"""Entrada de áudio extra (narração, música, efeito): arquivo + onde entra (tempo de saída) + volume.""" """Entrada de áudio extra (narração, música, efeito, dublagem): arquivo + onde entra (tempo de saída) + volume.
`spans` (só `dub`) = intervalos em que a voz original abaixa para `duck`, com rampa (`dub.duck_factors`)."""
def __init__(self, file: Path, at: float, volume: float, kind: str, trim_start: float = 0.0, duck: float = 1.0, def __init__(self, file: Path, at: float, volume: float, kind: str, trim_start: float = 0.0, duck: float = 1.0,
length: float = 0.0): length: float = 0.0, spans: list[tuple[float, float]] | None = None):
self.file, self.at, self.volume, self.kind = file, at, volume, kind self.file, self.at, self.volume, self.kind = file, at, volume, kind
self.trim_start, self.duck, self.length = trim_start, duck, length self.trim_start, self.duck, self.length = trim_start, duck, length
self.spans = spans or []
COVER_INTRO_S = 2 / FPS # capa nos 2 primeiros quadros (as redes usam o quadro 0 como miniatura padrão) COVER_INTRO_S = 2 / FPS # capa nos 2 primeiros quadros (as redes usam o quadro 0 como miniatura padrão)
@@ -477,13 +531,17 @@ def build_filter(project: dict, cfg: dict, ps: list[Piece], in0: float, ass_name
g.append(f"[{cover_input}:v]scale={fw}:{fh},setsar=1,format=yuv420p[cv]") g.append(f"[{cover_input}:v]scale={fw}:{fh},setsar=1,format=yuv420p[cv]")
g.append(f"[vbase][cv]overlay=enable='lt(t,{COVER_INTRO_S:.4f})':eof_action=pass,format=yuv420p[v]") g.append(f"[vbase][cv]overlay=enable='lt(t,{COVER_INTRO_S:.4f})':eof_action=pass,format=yuv420p[v]")
# Áudio: original (com volume e abaixado sob a narração) + narração + efeitos; música por baixo com ducking. # Áudio: original (com volume e abaixado sob a narração/dublagem) + narração + dublagem + efeitos; música por
# baixo com ducking. A dublagem (camada de desenvolvimento) abaixa o original com rampa só onde ela fala.
narr = [(k, x) for k, x in enumerate(extras, start=1) if x.kind == "narration"] narr = [(k, x) for k, x in enumerate(extras, start=1) if x.kind == "narration"]
vol_expr = f"{original_volume:.3f}" vol_expr = f"{original_volume:.3f}"
for _, x in narr: for _, x in narr:
end = x.at + (x.length or 0) end = x.at + (x.length or 0)
if x.duck < 1 and x.length: if x.duck < 1 and x.length:
vol_expr = f"{vol_expr}*if(between(t,{x.at:.3f},{end:.3f}),{x.duck:.3f},1)" vol_expr = f"{vol_expr}*if(between(t,{x.at:.3f},{end:.3f}),{x.duck:.3f},1)"
for x in extras:
if x.kind == "dub":
vol_expr = "*".join([vol_expr, *dub.duck_factors(x.spans, x.duck)])
g.append(f"[acat]volume='{vol_expr}':eval=frame[aorig]") g.append(f"[acat]volume='{vol_expr}':eval=frame[aorig]")
voice_labels = ["[aorig]"] voice_labels = ["[aorig]"]
music_label = None music_label = None
@@ -608,13 +666,33 @@ def has_audio_stream(ffprobe: str | None, file: Path) -> bool:
return bool(out.strip()) return bool(out.strip())
def mean_volume(ffmpeg: str, segs: list[tuple[Path, float, float]], start: float, end: float, work: Path,
stem: str) -> float | None:
"""Volume médio (dB RMS, `volumedetect`) do áudio original de [start, end] da sessão; None se não der para medir.
Só o áudio é decodificado (~0,1 s num corte de 1 min)."""
if not segs:
return None
args, concat = _concat_input(work, f"{stem}.level", segs, start, end - start)
try:
result = subprocess.run([ffmpeg, "-v", "info", "-nostats", *args, "-vn", "-af", "volumedetect", "-f", "null", "-"],
capture_output=True, timeout=120, cwd=work, creationflags=media.NO_WINDOW)
except (OSError, subprocess.TimeoutExpired):
return None
finally:
concat.unlink(missing_ok=True)
match = re.search(rb"mean_volume:\s*(-?[\d.]+) dB", result.stderr)
return float(match.group(1)) if match and result.returncode == 0 else None
def render_project(ffmpeg: str, ffprobe: str | None, encoder: list[str], segments: list[tuple[Path, float, float]], 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, 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, out_range: tuple[float, float] | None = None, timeout: float = 900, chat: list | None = None,
cover_file: Path | None = None, translation: list[dict] | None = None, dev: bool = True) -> None: cover_file: Path | None = None, translation: list[dict] | None = None, dev: bool = True,
dubber: "dub.Dubber | None" = None) -> dict:
"""Renderiza o projeto (ou só a saída [a, b] para a prévia real). `segments` = (arquivo, início, fim) da sessão. """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 `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`).""" quadros quando o projeto pede (`cover.atStart`). `dubber` = dublagem em português (`dev.dub`, só com `dev=True`
e `translation`; app/dub.py). Devolve um resumo (`{"dub": {...} | None}`) — quem chama pode ignorar."""
cfg = effective_settings(base_cfg, project) cfg = effective_settings(base_cfg, project)
total = output_duration(project["cuts"]) total = output_duration(project["cuts"])
t0, t1 = out_range if out_range else (0.0, total) t0, t1 = out_range if out_range else (0.0, total)
@@ -649,6 +727,21 @@ def render_project(ffmpeg: str, ffprobe: str | None, encoder: list[str], segment
if music: if music:
extras.append(AudioInput(repo_root / music["file"], 0.0, music["volume"], "music", trim_start=t0, extras.append(AudioInput(repo_root / music["file"], 0.0, music["volume"], "music", trim_start=t0,
duck=0.5 if music["duck"] else 1.0)) duck=0.5 if music["duck"] else 1.0))
dub_track: dub.DubTrack | None = None
if dubber is not None and translation and layout.dev_flags(cfg, dev)["dub"]:
try:
# Volume do original no corte INTEIRO (a prévia de 5 s nivela igual ao render da fila).
full = pieces(project["cuts"])
level = mean_volume(ffmpeg, _segments_for(segments, full[0].start, full[-1].end), full[0].start,
full[-1].end, work, stem)
dub_track = dubber.build(translation, project["cuts"], cfg, t0, t1, work, stem, level_db=level)
except (media.MediaError, OSError) as exc: # camada de teste: o vídeo sai mesmo sem ela
log.warning("dublagem falhou (%s): o vídeo sai sem dublagem", exc)
if dub_track:
extras.append(AudioInput(dub_track.file, 0.0, 1.0, "dub", duck=dub_track.duck, length=t1 - t0,
spans=dub_track.spans))
log.info("dublagem: %d falas, %d sintetizadas agora, %.1f s", dub_track.cues, dub_track.synthesized,
dub_track.seconds)
extra_args: list[str] = [] extra_args: list[str] = []
for x in extras: for x in extras:
extra_args += (["-stream_loop", "-1"] if x.kind == "music" else []) + ["-i", str(x.file)] extra_args += (["-stream_loop", "-1"] if x.kind == "music" else []) + ["-i", str(x.file)]
@@ -689,8 +782,12 @@ def render_project(ffmpeg: str, ffprobe: str | None, encoder: list[str], segment
"-t", f"{t1 - t0:.3f}", "-movflags", "+faststart", tmp.name], timeout=timeout, cwd=work) "-t", f"{t1 - t0:.3f}", "-movflags", "+faststart", tmp.name], timeout=timeout, cwd=work)
tmp.replace(out_file) tmp.replace(out_file)
finally: finally:
for f in (ass_file, concat, tmp, graph_file, *helper_files, *([uniform] if uniform else [])): for f in (ass_file, concat, tmp, graph_file, *helper_files, *([uniform] if uniform else []),
*([dub_track.file] if dub_track else [])):
f.unlink(missing_ok=True) f.unlink(missing_ok=True)
return {"dub": None if dub_track is None else {
"cues": dub_track.cues, "synthesized": dub_track.synthesized, "seconds": dub_track.seconds,
"failed": len(dub_track.failed)}}
def make_proxy(ffmpeg: str, segments: list[tuple[Path, float, float]], lo: float, hi: float, out_file: Path) -> None: def make_proxy(ffmpeg: str, segments: list[tuple[Path, float, float]], lo: float, hi: float, out_file: Path) -> None:
+153 -11
View File
@@ -167,16 +167,32 @@ class YuNetDetector:
return [(float(f[0]), float(f[1]), float(f[2]), float(f[3]), float(f[14])) for f in faces] return [(float(f[0]), float(f[1]), float(f[2]), float(f[3]), float(f[14])) for f in faces]
def pose_from_matrix(m: Any) -> tuple[float, float, float]:
"""(yaw, pitch, roll) em graus da matriz 4×4 de transformação facial do MediaPipe (linhas × colunas).
Conferido em quadros reais (sessão 8): pitch DIMINUI quando a cabeça vai para trás (bebendo de lata: −25° contra
~+12° do normal, que olha um pouco para baixo); yaw ±50° = rosto virado de lado; roll ±45° = cabeça deitada.
"""
pitch = math.degrees(math.atan2(float(m[2][1]), float(m[2][2])))
yaw = math.degrees(math.atan2(-float(m[2][0]), math.hypot(float(m[2][1]), float(m[2][2]))))
roll = math.degrees(math.atan2(float(m[1][0]), float(m[0][0])))
return yaw, pitch, roll
class MediaPipeTracker: class MediaPipeTracker:
"""MediaPipe Face Landmarker em modo VIDEO: 478 pontos + 52 blendshapes. Um por bloco. """MediaPipe Face Landmarker em modo VIDEO: 478 pontos + 52 blendshapes + matriz de pose. Um por bloco.
API do mediapipe 1.2.3 (bancada): `from mediapipe.tasks import python` NÃO existe nesta versão — importar os API do mediapipe 1.2.3 (bancada): `from mediapipe.tasks import python` NÃO existe nesta versão — importar os
submódulos. Timestamps têm de crescer sempre dentro do mesmo landmarker. submódulos. Timestamps têm de crescer sempre dentro do mesmo landmarker.
`detector` (YuNet, opcional): quando o MediaPipe não acha o rosto — streamer de perfil olhando o monitor do lado
(sessão 15, tfue: rosto em só 10 % dos quadros, YuNet em 100 %) —, a caixa da cabeça vira `FaceSample(head=True)`:
sem expressão, mas com posição e tamanho para o corpo (agitação, chegar perto, sair do quadro).
""" """
name = "mediapipe" name = "mediapipe"
def __init__(self, model_path: Path): def __init__(self, model_path: Path, detector: Detector | None = None):
try: try:
import mediapipe as mp import mediapipe as mp
import numpy as np import numpy as np
@@ -193,8 +209,10 @@ class MediaPipeTracker:
min_face_presence_confidence=0.5, min_face_presence_confidence=0.5,
min_tracking_confidence=0.5, min_tracking_confidence=0.5,
output_face_blendshapes=True, output_face_blendshapes=True,
output_facial_transformation_matrixes=True, # pose da cabeça (balanço, aceno, cabeça para trás)
) )
self._lm = vision.FaceLandmarker.create_from_options(options) self._lm = vision.FaceLandmarker.create_from_options(options)
self._detector = detector
self._last_ms = -1 self._last_ms = -1
def process(self, t: float, rgb: Any) -> reaction.FaceSample: def process(self, t: float, rgb: Any) -> reaction.FaceSample:
@@ -203,16 +221,90 @@ class MediaPipeTracker:
image = self._mp.Image(image_format=self._mp.ImageFormat.SRGB, data=self._np.ascontiguousarray(rgb)) image = self._mp.Image(image_format=self._mp.ImageFormat.SRGB, data=self._np.ascontiguousarray(rgb))
result = self._lm.detect_for_video(image, ms) result = self._lm.detect_for_video(image, ms)
if not result.face_landmarks: if not result.face_landmarks:
return reaction.FaceSample(t, False) return self._head_only(t, rgb)
xs = [p.x for p in result.face_landmarks[0]] xs = [p.x for p in result.face_landmarks[0]]
ys = [p.y for p in result.face_landmarks[0]] ys = [p.y for p in result.face_landmarks[0]]
blend = {c.category_name: float(c.score) for c in result.face_blendshapes[0]} if result.face_blendshapes else {} blend = {c.category_name: float(c.score) for c in result.face_blendshapes[0]} if result.face_blendshapes else {}
return reaction.FaceSample(t, True, (min(xs) + max(xs)) / 2, (min(ys) + max(ys)) / 2, max(ys) - min(ys), blend) matrixes = getattr(result, "facial_transformation_matrixes", None)
pose = pose_from_matrix(matrixes[0]) if matrixes else None
return reaction.FaceSample(t, True, (min(xs) + max(xs)) / 2, (min(ys) + max(ys)) / 2, max(ys) - min(ys), blend,
pose)
def _head_only(self, t: float, rgb: Any) -> reaction.FaceSample:
"""Sem rosto no MediaPipe: a caixa do YuNet (se houver) diz onde está a cabeça. Falha do detector não derruba
o bloco: o quadro fica só sem rosto, como antes."""
if self._detector is None:
return reaction.FaceSample(t, False)
try:
detections = self._detector.detect(self._np.ascontiguousarray(rgb[:, :, ::-1])) # YuNet quer BGR
except Exception as exc: # noqa: BLE001 - OpenCV pode falhar num quadro; o rastreio do rosto segue
log.debug("YuNet falhou no quadro %.2f: %s", t, exc)
return reaction.FaceSample(t, False)
if not detections:
return reaction.FaceSample(t, False)
x, y, w, h, _score = max(detections, key=lambda d: d[4])
height, width = rgb.shape[:2]
return reaction.FaceSample(t, False, (x + w / 2) / width, (y + h / 2) / height, h / height, head=True)
def close(self) -> None: def close(self) -> None:
self._lm.close() self._lm.close()
class MouthMeter:
"""Movimento da boca por quadro, para a atribuição de falante (speakers.py; doc/clipador/FALANTES.md).
Medido na sessão 15 (tfue, webcam pequena e rosto de PERFIL): o MediaPipe só achava o rosto em ~4 % dos quadros
e o `jawOpen` ficava em 0,00 mesmo falando. O YuNet acha o rosto em 99 % dos quadros e dá os cantos da boca:
o recorte da boca (alinhado pelo YuNet em cada quadro, 24×20, normalizado) é comparado com o do quadro anterior.
Valor = diferença média (0 = parado); None = sem rosto neste quadro ou no anterior. É um sinal FRACO por trecho
(fala × boca parada separa pouco num trecho só) e forte na soma: serve para dizer QUAL voz é a do streamer."""
PATCH = (24, 20)
def __init__(self, model_path: Path, score: float = 0.5):
try:
import cv2
import numpy as np
except ImportError as exc: # pragma: no cover - depende da instalação
raise FaceUnavailable("opencv não instalado (rode o setup.bat)") from exc
self._cv2, self._np, self._path, self._score = cv2, np, model_path, score
self._det = None
self._size: tuple[int, int] | None = None
self._prev: Any = None
def feed(self, rgb: Any) -> float | None:
cv2, np = self._cv2, self._np
if rgb is None:
self._prev = None
return None
h, w = rgb.shape[:2]
if self._det is None:
self._det = cv2.FaceDetectorYN.create(str(self._path), "", (w, h), self._score, 0.3, 5)
elif self._size != (w, h):
self._det.setInputSize((w, h))
self._size = (w, h)
bgr = np.ascontiguousarray(rgb[:, :, ::-1])
_, faces = self._det.detect(bgr)
if faces is None or len(faces) == 0:
self._prev = None
return None
f = max(faces, key=lambda r: r[14])
fh = float(f[3])
(rx, ry), (lx, ly) = f[10:12], f[12:14] # cantos da boca (direito, esquerdo)
mx, my = (rx + lx) / 2, (ry + ly) / 2
mw = max(abs(lx - rx), float(f[2]) * 0.3)
x0, x1 = int(mx - mw * 0.9), int(mx + mw * 0.9)
y0, y1 = int(my - fh * 0.12), int(my + fh * 0.22)
if x0 < 0 or y0 < 0 or x1 > w or y1 > h or x1 - x0 < 4 or y1 - y0 < 4:
self._prev = None
return None
gray = cv2.cvtColor(bgr[y0:y1, x0:x1], cv2.COLOR_BGR2GRAY)
patch = cv2.resize(gray, self.PATCH).astype(np.float32)
patch = (patch - patch.mean()) / (patch.std() + 1e-3)
prev, self._prev = self._prev, patch
return None if prev is None else float(np.abs(patch - prev).mean())
class OpenSeeFaceTracker: class OpenSeeFaceTracker:
"""Plano B (OpenSeeFace, só os .onnx no onnxruntime): presença e posição do rosto, SEM blendshapes. """Plano B (OpenSeeFace, só os .onnx no onnxruntime): presença e posição do rosto, SEM blendshapes.
@@ -428,6 +520,8 @@ def to_frame(seconds: list[reaction.FaceSecond], crop: dict) -> list[reaction.Fa
s.cy = crop["y"] + s.cy * crop["h"] s.cy = crop["y"] + s.cy * crop["h"]
if s.size is not None: if s.size is not None:
s.size = s.size * crop["h"] s.size = s.size * crop["h"]
if s.hsize is not None:
s.hsize = s.hsize * crop["h"]
return seconds return seconds
@@ -449,8 +543,12 @@ class FaceService:
detector_factory: Callable[[], Detector] | None = None, detector_factory: Callable[[], Detector] | None = None,
reader: Callable[..., Iterator[tuple[float, Any]]] | None = None, reader: Callable[..., Iterator[tuple[float, Any]]] | None = None,
grabber: Callable[..., Any] | None = None, grabber: Callable[..., Any] | None = None,
sizer: Callable[[Path], tuple[int, int]] | None = None): sizer: Callable[[Path], tuple[int, int]] | None = None,
mouth_factory: Callable[[], Any] | None = None):
self.e = engine self.e = engine
# Movimento da boca por quadro (atribuição de falante). Falha ao criar = bloco sem a série `mouth` (o
# rastreio de reação segue igual). Nos testes (store falso) cai nesse caso sozinho.
self._mouth_factory = mouth_factory or (lambda: MouthMeter(self.store.path("yunet")))
self.store = store or ModelStore(engine.settings.data_dir / "models") self.store = store or ModelStore(engine.settings.data_dir / "models")
# Recebe o backend que a sessão já usa (None = sessão nova) e devolve o rastreador. # Recebe o backend que a sessão já usa (None = sessão nova) e devolve o rastreador.
self._tracker_factory: Callable[[str | None], Tracker] = tracker_factory or self._default_tracker self._tracker_factory: Callable[[str | None], Tracker] = tracker_factory or self._default_tracker
@@ -479,7 +577,7 @@ class FaceService:
if backend == OpenSeeFaceTracker.name: if backend == OpenSeeFaceTracker.name:
return OpenSeeFaceTracker(self.store.path("osf_landmarks"), self.store.path("osf_detector")) return OpenSeeFaceTracker(self.store.path("osf_landmarks"), self.store.path("osf_detector"))
try: try:
return MediaPipeTracker(self.store.path("face_landmarker")) return MediaPipeTracker(self.store.path("face_landmarker"), self._head_detector())
except FaceUnavailable as first: except FaceUnavailable as first:
if backend == MediaPipeTracker.name: if backend == MediaPipeTracker.name:
raise # sessão começou no MediaPipe: espera ele voltar em vez de trocar no meio raise # sessão começou no MediaPipe: espera ele voltar em vez de trocar no meio
@@ -488,6 +586,15 @@ class FaceService:
except Exception as exc: # noqa: BLE001 - erro do próprio MediaPipe ao carregar o modelo except Exception as exc: # noqa: BLE001 - erro do próprio MediaPipe ao carregar o modelo
raise FaceUnavailable(f"MediaPipe não carregou: {exc}") from exc raise FaceUnavailable(f"MediaPipe não carregou: {exc}") from exc
def _head_detector(self) -> Detector | None:
"""YuNet para a cabeça quando o MediaPipe perde o rosto; sem ele o rastreio segue como antes (só sem corpo de
perfil)."""
try:
return self._detector_factory()
except FaceUnavailable as exc:
log.info("rastreio sem a caixa da cabeça (YuNet indisponível: %s)", exc)
return None
def session_backend(self, session_id: int) -> str | None: def session_backend(self, session_id: int) -> str | None:
"""Backend que a série da sessão já usa (None = nenhum bloco rastreado ainda).""" """Backend que a série da sessão já usa (None = nenhum bloco rastreado ainda)."""
row = self.e.db.get("SELECT data_json FROM face_track WHERE session_id = ? AND status = 'done' ORDER BY idx LIMIT 1", row = self.e.db.get("SELECT data_json FROM face_track WHERE session_id = ? AND status = 'done' ORDER BY idx LIMIT 1",
@@ -592,12 +699,21 @@ class FaceService:
started = time.perf_counter() started = time.perf_counter()
tracker = self._tracker_factory(self.session_backend(sid)) # FaceUnavailable sobe: não marca o bloco tracker = self._tracker_factory(self.session_backend(sid)) # FaceUnavailable sobe: não marca o bloco
self.backend = tracker.name self.backend = tracker.name
mouth = self._mouth_meter()
mouth_values: list[float | None] = []
try: try:
file = REPO_ROOT / segment["file"] file = REPO_ROOT / segment["file"]
crop = expand(cam) crop = expand(cam)
px, out = crop_geometry(crop, self._frame_size(sid, file)) px, out = crop_geometry(crop, self._frame_size(sid, file))
samples = [tracker.process(segment["start_s"] + t, rgb) samples = []
for t, rgb in self._reader(self.e.settings.ffmpeg or "ffmpeg", file, px, out)] for t, rgb in self._reader(self.e.settings.ffmpeg or "ffmpeg", file, px, out):
samples.append(tracker.process(segment["start_s"] + t, rgb))
if mouth is not None:
try:
mouth_values.append(mouth.feed(rgb))
except Exception as exc: # noqa: BLE001 - a boca é extra: falhou, o bloco segue sem ela
log.info("movimento da boca do bloco %s/%s: %s", sid, idx, exc)
mouth, mouth_values = None, []
except FaceUnavailable: except FaceUnavailable:
raise # não é culpa do bloco: não grava, o laço tenta de novo mais tarde raise # não é culpa do bloco: não grava, o laço tenta de novo mais tarde
except Exception as exc: # noqa: BLE001 - FFmpeg, MediaPipe (RuntimeError) etc.: o bloco vira "error" e o laço segue except Exception as exc: # noqa: BLE001 - FFmpeg, MediaPipe (RuntimeError) etc.: o bloco vira "error" e o laço segue
@@ -612,14 +728,31 @@ class FaceService:
self._save(sid, idx, "error", {"cam": cam}, msg) self._save(sid, idx, "error", {"cam": cam}, msg)
return "error" return "error"
# Segundos inteiros cujo início cai no bloco: [ceil(início), ceil(fim)) — blocos vizinhos não se repetem. # Segundos inteiros cujo início cai no bloco: [ceil(início), ceil(fim)) — blocos vizinhos não se repetem.
seconds = to_frame(reaction.per_second(samples, last - first, start_s=first), crop) seconds = to_frame(reaction.per_second(samples, last - first, start_s=first, params=self.params), crop)
data = {"cam": cam, "crop": crop, "fps": FPS, "backend": tracker.name, "frames": len(samples), data = {"cam": cam, "crop": crop, "fps": FPS, "backend": tracker.name, "frames": len(samples),
"ms": int((time.perf_counter() - started) * 1000), "coords": "frame", "ms": int((time.perf_counter() - started) * 1000), "coords": "frame",
"seconds": reaction.seconds_to_json(seconds)} "seconds": reaction.seconds_to_json(seconds)}
if mouth is not None and mouth_values:
# Quadro i = início do bloco + i / fps (speakers.py soma isto por trecho de fala).
data["mouth"] = [None if v is None else round(v, 4) for v in mouth_values]
self._save(sid, idx, "done", data, None) self._save(sid, idx, "done", data, None)
self.last_error = None self.last_error = None
self._after_block(sid, idx)
return "done" return "done"
def _mouth_meter(self) -> Any:
try:
return self._mouth_factory()
except Exception as exc: # noqa: BLE001 - sem YuNet/opencv: rastreio segue, só sem a série da boca
log.debug("medidor de boca indisponível: %s", exc)
return None
def _after_block(self, session_id: int, idx: int) -> None:
"""Série nova da boca: a atribuição de falante da sessão é refeita na próxima leitura."""
speakers = getattr(self.e, "speakers", None)
if speakers is not None:
speakers.invalidate(session_id)
def _frame_size(self, session_id: int, file: Path) -> tuple[int, int]: def _frame_size(self, session_id: int, file: Path) -> tuple[int, int]:
key = str(file) key = str(file)
if key not in self._sizes: if key not in self._sizes:
@@ -694,7 +827,8 @@ class FaceService:
return "" return ""
seconds = self.dense(session["id"], max(0.0, lo - BASELINE_EXTRA_S), hi) seconds = self.dense(session["id"], max(0.0, lo - BASELINE_EXTRA_S), hi)
inside = [s for s in seconds if lo <= s.t <= hi] inside = [s for s in seconds if lo <= s.t <= hi]
if not inside or not any(s.smile is not None for s in inside): # Só a cabeça (de perfil, sem expressão) também rende linha: o corpo diz alguma coisa ao analista.
if not inside or not any(s.smile is not None or (s.head or 0.0) > 0 for s in inside):
return "" return ""
return reaction.summarize(seconds, lo, hi, self.params, relative=False) return reaction.summarize(seconds, lo, hi, self.params, relative=False)
@@ -707,16 +841,23 @@ class FaceService:
seconds = self.dense(sid, max(0.0, start - BASELINE_EXTRA_S), end) seconds = self.dense(sid, max(0.0, start - BASELINE_EXTRA_S), end)
signal = reaction.reaction_signal(seconds, params=self.params) signal = reaction.reaction_signal(seconds, params=self.params)
moments = reaction.reaction_moments(seconds, self.params) moments = reaction.reaction_moments(seconds, self.params)
body = reaction.body_moments(seconds, self.params)
expressions = reaction.expression_map(seconds, self.params, body)
counts = {r["status"]: r["n"] for r in self.e.db.all( counts = {r["status"]: r["n"] for r in self.e.db.all(
"SELECT status, COUNT(*) AS n FROM face_track WHERE session_id = ? GROUP BY status", sid)} "SELECT status, COUNT(*) AS n FROM face_track WHERE session_id = ? GROUP BY status", sid)}
total = self.e.db.get("SELECT COUNT(*) AS n FROM segments WHERE session_id = ? AND deleted = 0", sid)["n"] total = self.e.db.get("SELECT COUNT(*) AS n FROM segments WHERE session_id = ? AND deleted = 0", sid)["n"]
rows = [] rows = []
for s, z in zip(seconds, signal): for s, z, mapped in zip(seconds, signal, expressions):
if s.t < start: if s.t < start:
continue continue
item = s.to_json() item = s.to_json()
if z is not None: if z is not None:
item["signal"] = round(z, 2) item["signal"] = round(z, 2)
# Mapa de expressões: a expressão dominante e o movimento do corpo no segundo (ausentes = nada).
if mapped["expr"]:
item["expr"] = mapped["expr"]
if mapped["body"]:
item["body"] = mapped["body"]
rows.append(item) rows.append(item)
return { return {
"sessionId": sid, "enabled": self.enabled, "fps": FPS, "coords": "frame", "sessionId": sid, "enabled": self.enabled, "fps": FPS, "coords": "frame",
@@ -727,6 +868,7 @@ class FaceService:
"fromS": start, "toS": end, "fromS": start, "toS": end,
"seconds": rows, "seconds": rows,
"moments": [m.to_json() for m in moments if start <= m.peak_s <= end], "moments": [m.to_json() for m in moments if start <= m.peak_s <= end],
"body": [b.to_json() for b in body if b.end_s >= start and b.start_s <= end],
} }
# ---------- câmera local (YuNet + reaction.locate_cam) # ---------- câmera local (YuNet + reaction.locate_cam)
+33 -9
View File
@@ -660,16 +660,40 @@ def _game_context_en(game: str, screen_game: str, profile: dict | None, live_tit
return "\n".join(lines) return "\n".join(lines)
def _transcript(words: list[Word], lo: float, hi: float, lang: str = "pt") -> str: SPEAKER_NOTE = {
lines, current, current_t = [], [], None "pt": "Quem fala vem marcado: [{s}] = o streamer; [other1], [other2]… = OUTRA pessoa (colega no Discord, outro "
for word in sorted((w for w in words if lo <= w.start <= hi), key=lambda w: w.start): "jogador no chat de voz do jogo). Nunca atribua a {s} o que outra pessoa disse.",
if current_t is None or word.start - current_t > 4 or len(current) >= 14: "en": "Each line is tagged with who speaks: [{s}] = the streamer; [other1], [other2]… = SOMEONE ELSE (teammate on "
"Discord, another player on in-game voice chat). Never attribute to {s} what someone else said.",
}
def _transcript(words: list[Word], lo: float, hi: float, lang: str = "pt", streamer: str = "") -> str:
"""Transcrição com tempo para os prompts. Com fala de outra pessoa no trecho (doc/clipador/FALANTES.md), cada
linha diz quem fala ([Tfue] / [other1]) e nunca mistura falantes; sem outra pessoa, sai igual a antes."""
inside = sorted((w for w in words if lo <= w.start <= hi), key=lambda w: w.start)
tagged = any(w.speaker and w.speaker != "streamer" for w in inside)
me = (streamer or "streamer").replace("[", "(").replace("]", ")")
lines: list[str] = []
current: list[str] = []
current_t: float | None = None
current_sp = ""
def flush() -> None:
tag = f" [{me if current_sp == 'streamer' else current_sp}]" if tagged else ""
lines.append(f"[{current_t:.0f}s]{tag} {' '.join(current)}")
for word in inside:
sp = word.speaker or "streamer"
if current_t is None or word.start - current_t > 4 or len(current) >= 14 or (tagged and sp != current_sp):
if current: if current:
lines.append(f"[{current_t:.0f}s] {' '.join(current)}") flush()
current, current_t = [], word.start current, current_t, current_sp = [], word.start, sp
current.append(word.word) current.append(word.word)
if current: if current:
lines.append(f"[{current_t:.0f}s] {' '.join(current)}") flush()
if lines and tagged:
lines.insert(0, SPEAKER_NOTE["en" if lang == "en" else "pt"].format(s=me))
return "\n".join(lines) or LABELS[lang]["no_speech"] return "\n".join(lines) or LABELS[lang]["no_speech"]
@@ -717,7 +741,7 @@ def build_prompt(streamer: str, platform: str, start_s: float, end_s: float, pea
f"{L['signals']}: {json.dumps(heuristic, ensure_ascii=False)}\n" f"{L['signals']}: {json.dumps(heuristic, ensure_ascii=False)}\n"
+ (f"{L['face']}: {face}\n" if face else "") + (f"{L['face']}: {face}\n" if face else "")
+ f"{_frames_block(frames or [], lang)}\n\n" + f"{_frames_block(frames or [], lang)}\n\n"
f"{L['transcript']}:\n{_transcript(words, lo, hi, lang)}\n\n" f"{L['transcript']}:\n{_transcript(words, lo, hi, lang, streamer)}\n\n"
f"{_chat_block(chat, lo, hi, peak_s, lang=lang)}" f"{_chat_block(chat, lo, hi, peak_s, lang=lang)}"
) )
@@ -732,7 +756,7 @@ def build_scan_prompt(streamer: str, platform: str, lo: float, hi: float, back_l
f"{L['new_window']}: {lo:.0f}s {to} {hi:.0f}s ({L['back_to'].format(s=f'{back_lo:.0f}')}).\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"{L['duration']}: {min_s:.0f} {to} {max_s:.0f} s. {L['done']}: {done}\n"
f"{_frames_block(frames, lang)}\n\n" f"{_frames_block(frames, lang)}\n\n"
f"{L['transcript']}:\n{_transcript(words, back_lo, hi, lang)}\n\n" f"{L['transcript']}:\n{_transcript(words, back_lo, hi, lang, streamer)}\n\n"
f"{_chat_block(chat, back_lo, hi, None, bucket_s=10, lang=lang)}" f"{_chat_block(chat, back_lo, hi, None, bucket_s=10, lang=lang)}"
) )
+33 -4
View File
@@ -85,19 +85,31 @@ HOOK_FONT = "Luckiest Guy" if "Luckiest Guy" in PACKAGED_FONTS else "Arial Black
# +0,1 s de folga cobre o arredondamento de quadro e do contêiner no arquivo final. # +0,1 s de folga cobre o arredondamento de quadro e do contêiner no arquivo final.
DURATION_MARGIN_S = 1.0 DURATION_MARGIN_S = 1.0
DURATION_SLACK_S = 0.1 DURATION_SLACK_S = 0.1
# Dublagem de desenvolvimento (app/dub.py): voz masculina pt-BR natural do serviço de voz (Edge, online); a das
# falas de outra pessoa é outra voz pt-BR nativa (Kokoro, offline), para não parecer o mesmo falando sozinho.
DUB_VOICE = "pt-br-antonio"
DUB_VOICE_OTHER = "kokoro-pm-alex"
DUB_DUCK = 0.25
VOICE_ID_RE = re.compile(r"^[a-z0-9][a-z0-9-]{1,47}$") # mesmo padrão do serviço de voz
DEFAULTS: dict = { DEFAULTS: dict = {
"layout": {"mode": "auto", "cam": None, "game": None, "camHeight": 0.34}, "layout": {"mode": "auto", "cam": None, "game": None, "camHeight": 0.34},
"caption": { "caption": {
"enabled": True, "font": "Arial Black", "size": 84, "color": "#FFFFFF", "highlight": "#FFE500", "enabled": True, "font": "Arial Black", "size": 84, "color": "#FFFFFF", "highlight": "#FFE500",
"outline": "#000000", "outlineWidth": 7, "y": None, "uppercase": True, "maxWords": 3, "outline": "#000000", "outlineWidth": 7, "y": None, "uppercase": True, "maxWords": 3,
# Fala de OUTRA pessoa (colega no Discord, voz do jogo): linha logo abaixo da do streamer, nesta cor;
# `otherSize` None = 85 % de `size` (doc/clipador/FALANTES.md).
"otherColor": "#5CE1FF", "otherSize": None,
# Legado (18/11/2026, manhã): virou `dev.translation`. Ainda lido por `dev_flags` (camadas já salvas). # Legado (18/11/2026, manhã): virou `dev.translation`. Ainda lido por `dev_flags` (camadas já salvas).
"translation": False, "translation": False,
}, },
# Camadas SÓ DE DESENVOLVIMENTO (doc/clipador/IDIOMAS.md): entram no vídeo de revisão (antes de aprovar) e NUNCA no # Camadas SÓ DE DESENVOLVIMENTO (doc/clipador/IDIOMAS.md): entram no vídeo de revisão (antes de aprovar) e NUNCA no
# vídeo final — o render com `dev=False` ignora este grupo inteiro. `translation`: português embaixo da legenda; # vídeo final — o render com `dev=False` ignora este grupo inteiro. `translation`: português embaixo da legenda;
# `dub`: dublagem em português por TTS com a voz original abaixada. # `dub`: dublagem em português por TTS com a voz original abaixada (app/dub.py, doc/clipador/DUBLAGEM.md):
"dev": {"translation": False, "dub": False}, # `dubVoice` = voz TTS pronta do catálogo (nunca clone do streamer), `dubVoiceOther` = voz das falas com
# `speaker: "other"`, `dubDuck` = volume do áudio original enquanto a dublagem toca (0–1).
"dev": {"translation": False, "dub": False, "dubVoice": DUB_VOICE, "dubVoiceOther": DUB_VOICE_OTHER,
"dubDuck": DUB_DUCK},
"credit": {"enabled": True, "position": "top", "size": 44}, "credit": {"enabled": True, "position": "top", "size": 44},
"duration": {"minS": 60, "maxS": 90, "backtrackS": 120}, "duration": {"minS": 60, "maxS": 90, "backtrackS": 120},
"format": {"aspect": "vertical"}, "format": {"aspect": "vertical"},
@@ -171,7 +183,7 @@ def validate(settings: dict) -> dict:
cap = settings.get("caption") cap = settings.get("caption")
if cap is not None: if cap is not None:
o = {} o = {}
for key in ("color", "highlight", "outline"): for key in ("color", "highlight", "outline", "otherColor"):
if key in cap: if key in cap:
if not HEX_RE.match(str(cap[key])): if not HEX_RE.match(str(cap[key])):
raise LayoutError(f"caption.{key} precisa ser cor #RRGGBB") raise LayoutError(f"caption.{key} precisa ser cor #RRGGBB")
@@ -185,6 +197,10 @@ def validate(settings: dict) -> dict:
o[key] = int(cap[key]) o[key] = int(cap[key])
if not lo <= o[key] <= hi: if not lo <= o[key] <= hi:
raise LayoutError(f"caption.{key} vai de {lo} a {hi}") raise LayoutError(f"caption.{key} vai de {lo} a {hi}")
if "otherSize" in cap:
o["otherSize"] = None if cap["otherSize"] in (None, "") else int(cap["otherSize"])
if o["otherSize"] is not None and not 30 <= o["otherSize"] <= 140:
raise LayoutError("caption.otherSize vai de 30 a 140 ou null = automático (85 % do tamanho)")
if "y" in cap: if "y" in cap:
o["y"] = None if cap["y"] is None else float(cap["y"]) 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: if o["y"] is not None and not 0.08 <= o["y"] <= 0.9:
@@ -197,7 +213,20 @@ def validate(settings: dict) -> dict:
if dev is not None: if dev is not None:
if not isinstance(dev, dict): if not isinstance(dev, dict):
raise LayoutError("dev precisa ser um objeto") raise LayoutError("dev precisa ser um objeto")
out["dev"] = {k: bool(dev[k]) for k in ("translation", "dub") if k in dev} o = {k: bool(dev[k]) for k in ("translation", "dub") if k in dev}
for key in ("dubVoice", "dubVoiceOther"):
if key in dev:
if not VOICE_ID_RE.match(str(dev[key] or "")):
raise LayoutError(f"dev.{key} precisa ser o id de uma voz do serviço de voz (ex.: {DUB_VOICE})")
o[key] = str(dev[key])
if "dubDuck" in dev:
try:
o["dubDuck"] = round(float(dev["dubDuck"]), 3)
except (TypeError, ValueError) as exc:
raise LayoutError("dev.dubDuck precisa ser número de 0 a 1") from exc
if not 0 <= o["dubDuck"] <= 1:
raise LayoutError("dev.dubDuck vai de 0 a 1 (volume do áudio original durante a dublagem)")
out["dev"] = o
cred = settings.get("credit") cred = settings.get("credit")
if cred is not None: if cred is not None:
o = {} o = {}
+45
View File
@@ -170,6 +170,19 @@ class ClipsDeleteIn(BaseModel):
confirmPublished: bool = False confirmPublished: bool = False
APPROVED = ("approved", "published") # estados em que o corte tem (ou espera) vídeo final
def final_view(row: dict) -> dict | None:
"""Vídeo final do corte (doc/clipador/REVISAO.md); None = sem final (não aprovado ou a aprovação foi desfeita)."""
if not row.get("final_status"):
return None
return {"status": row["final_status"], "file": row.get("final_file"), "thumb": row.get("final_thumb"),
"cover": row.get("final_cover"), "error": row.get("final_error"), "at": row.get("final_at"),
# O vídeo de revisão não tinha nenhuma camada de desenvolvimento: ele mesmo virou o final (sem render novo).
"reused": bool(row.get("final_file")) and row.get("final_file") == row.get("file")}
def clip_view(row: dict) -> dict: def clip_view(row: dict) -> dict:
return { return {
"id": row["id"], "sessionId": row["session_id"], "peakS": row["peak_s"], "startS": row["start_s"], "id": row["id"], "sessionId": row["session_id"], "peakS": row["peak_s"], "startS": row["start_s"],
@@ -191,6 +204,12 @@ def clip_view(row: dict) -> dict:
"edit": ({"updatedAt": row["edit_updated_at"], "exportedAt": row.get("edit_exported_at"), "cover": row.get("edit_cover"), "edit": ({"updatedAt": row["edit_updated_at"], "exportedAt": row.get("edit_exported_at"), "cover": row.get("edit_cover"),
"origin": row.get("edit_origin")} "origin": row.get("edit_origin")}
if row.get("edit_updated_at") else None), if row.get("edit_updated_at") else None),
# Revisão × final (doc/clipador/REVISAO.md). `file` é sempre o vídeo de REVISÃO (o da fila, para aprovar);
# `review.devLayers` = camadas de teste que entraram nele ([] = nenhuma; None = desconhecido).
"review": {"devLayers": loads(row.get("review_dev_json"), None)},
"final": final_view(row),
# O ÚNICO arquivo que pode ser publicado: o final pronto de um corte aprovado. None = ainda não (esperar).
"publishFile": row.get("final_file") if row["status"] in APPROVED and row.get("final_status") == "ready" else None,
} }
@@ -391,6 +410,8 @@ def create_app(settings: Settings | None = None, engine: Engine | None = None, s
at, frame = _frame(row, body.t, "preview-src.jpg", width=0) at, frame = _frame(row, body.t, "preview-src.jpg", width=0)
# Legenda de exemplo: 1º bloco começa em 0 s, então o quadro único da prévia já mostra a legenda. # Legenda de exemplo: 1º bloco começa em 0 s, então o quadro único da prévia já mostra a legenda.
sample = [Word(i * 0.35, 0.3 + i * 0.35, w) for i, w in enumerate("ASSIM VAI FICAR A LEGENDA".split())] sample = [Word(i * 0.35, 0.3 + i * 0.35, w) for i, w in enumerate("ASSIM VAI FICAR A LEGENDA".split())]
# E a fala de outra pessoa (colega no Discord), na linha de baixo, com a cor dela (FALANTES.md).
sample += [Word(0.05 + i * 0.35, 0.35 + i * 0.35, w, "other1") for i, w in enumerate("E A DO COLEGA".split())]
ass = build_ass(sample, 0.0, 3.0, engine.channel_label(row), cfg) ass = build_ass(sample, 0.0, 3.0, engine.channel_label(row), cfg)
out = settings.clips_dir / str(row["id"]) / "preview.jpg" out = settings.clips_dir / str(row["id"]) / "preview.jpg"
try: try:
@@ -419,6 +440,13 @@ def create_app(settings: Settings | None = None, engine: Engine | None = None, s
raise UserError("`to` precisa ser maior que `from`.") raise UserError("`to` precisa ser maior que `from`.")
return engine.face.view(_session(session_id), from_, to) return engine.face.view(_session(session_id), from_, to)
@app.get("/v1/sessions/{session_id}/speakers")
def get_speakers(session_id: int):
"""Vozes da sessão (doc/clipador/FALANTES.md): quantas, qual é o streamer e por quê (boca/volume), fala por
rótulo. `active: false` = sem prova suficiente: tudo fica como do streamer."""
_session(session_id)
return engine.speakers.view(session_id)
@app.post("/v1/sessions/{session_id}/face/reset") @app.post("/v1/sessions/{session_id}/face/reset")
def reset_face(session_id: int): def reset_face(session_id: int):
"""Apaga a série do rosto da sessão; o laço do rastreio refaz (ex.: depois de corrigir a câmera). Com um bloco """Apaga a série do rosto da sessão; o laço do rastreio refaz (ex.: depois de corrigir a câmera). Com um bloco
@@ -743,6 +771,11 @@ def create_app(settings: Settings | None = None, engine: Engine | None = None, s
if retime: if retime:
editor_api.retime_edit(engine, clip_id, start, end) # corte com edição: estica/encolhe as pontas do projeto editor_api.retime_edit(engine, clip_id, start, end) # corte com edição: estica/encolhe as pontas do projeto
engine.wake_clips.set() engine.wake_clips.set()
# Aprovou → pede o vídeo final (sem camadas de teste); desaprovou/mudou o trecho → o final deixa de valer.
if status in APPROVED and row["status"] not in APPROVED:
engine.queue_final(clip_id)
elif row["status"] in APPROVED and status not in APPROVED:
engine.drop_final(clip_id)
if body.status in ("approved", "rejected") and body.status != row["status"]: if body.status in ("approved", "rejected") and body.status != row["status"]:
# Sua decisão é o sinal forte: emotes da reação deste corte ganham/perdem peso no canal (uma vez). # Sua decisão é o sinal forte: emotes da reação deste corte ganham/perdem peso no canal (uma vez).
engine.intel.learn_from_clip(row, positive=body.status == "approved", mark=True) engine.intel.learn_from_clip(row, positive=body.status == "approved", mark=True)
@@ -753,9 +786,20 @@ def create_app(settings: Settings | None = None, engine: Engine | None = None, s
"""Força o render (ex.: corte que a IA descartou ou que deu erro).""" """Força o render (ex.: corte que a IA descartou ou que deu erro)."""
_clip(clip_id) _clip(clip_id)
db.run("UPDATE clips SET status = 'pending', error = NULL, updated_at = ? WHERE id = ?", now(), clip_id) db.run("UPDATE clips SET status = 'pending', error = NULL, updated_at = ? WHERE id = ?", now(), clip_id)
engine.drop_final(clip_id)
engine.wake_clips.set() engine.wake_clips.set()
return clip_view(_clip(clip_id)) return clip_view(_clip(clip_id))
@app.post("/v1/clips/{clip_id}/final")
def render_final(clip_id: int):
"""(Re)gera o vídeo final de um corte aprovado ("tentar de novo" depois de um erro). 409 se não aprovado."""
row = _clip(clip_id)
if row["status"] not in APPROVED:
raise UserError("Só corte aprovado tem vídeo final. Aprove o corte primeiro.", 409)
if row.get("final_status") not in ("pending", "rendering"):
engine.queue_final(clip_id)
return clip_view(_clip(clip_id))
@app.post("/v1/clips/{clip_id}/translate") @app.post("/v1/clips/{clip_id}/translate")
def translate_clip(clip_id: int): 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.""" """Traduz (de novo) a fala do corte para o português. Só para fonte em inglês; 409 se não couber."""
@@ -768,6 +812,7 @@ def create_app(settings: Settings | None = None, engine: Engine | None = None, s
def rejudge(clip_id: int): def rejudge(clip_id: int):
_clip(clip_id) _clip(clip_id)
db.run("UPDATE clips SET status = 'candidate', updated_at = ? WHERE id = ?", now(), clip_id) db.run("UPDATE clips SET status = 'candidate', updated_at = ? WHERE id = ?", now(), clip_id)
engine.drop_final(clip_id)
engine.wake_clips.set() engine.wake_clips.set()
return clip_view(_clip(clip_id)) return clip_view(_clip(clip_id))
+487 -26
View File
@@ -7,7 +7,10 @@ rosto do YuNet) e transforma em:
- um sinal de reação por segundo **relativo ao neutro do próprio streamer** (z robusto: mediana + MAD da janela - um sinal de reação por segundo **relativo ao neutro do próprio streamer** (z robusto: mediana + MAD da janela
recente, só com segundos em que o rosto aparece). Tem streamer que fica sorrindo o tempo todo, tem quem fale recente, só com segundos em que o rosto aparece). Tem streamer que fica sorrindo o tempo todo, tem quem fale
de boca aberta: o que importa é o desvio do normal DELE, não o valor absoluto do blendshape; de boca aberta: o que importa é o desvio do normal DELE, não o valor absoluto do blendshape;
- picos rotulados (risada, grito, susto, choque, confuso, raiva) com o início da reação, e um texto curto para o juiz; - picos rotulados (risada, grito, susto, choque, confuso, raiva e, desde 18/11/2026, gargalhada, medo, espanto,
nojo, tristeza, tenso; bocejo não é reação) com o início da reação, e um texto curto para o juiz;
- o corpo/cabeça mesmo sem expressão (balançando, acenando, agitado, chegou perto, saiu do quadro) e o mapa de
expressões por segundo (doc/clipador/EXPRESSOES.md);
- a posição da câmera no quadro (`locate_cam`) a partir das detecções de alguns quadros espalhados. - a posição da câmera no quadro (`locate_cam`) a partir das detecções de alguns quadros espalhados.
Sem rosto no segundo → sinal `None`, e `None` nunca vira pico. Sem rosto no segundo → sinal `None`, e `None` nunca vira pico.
@@ -28,6 +31,35 @@ EXPRESSION_CHANNELS: tuple[str, ...] = ("smile", "jaw", "surprise", "frown", "br
BASELINE_STEP_S = 5 # o neutro do streamer é recalculado a cada 5 s (anda devagar; a janela já ignora os últimos 10 s) BASELINE_STEP_S = 5 # o neutro do streamer é recalculado a cada 5 s (anda devagar; a janela já ignora os últimos 10 s)
SECOND_FIELDS: tuple[str, ...] = ("cx", "cy", "size", "smile", "jaw", "surprise", "frown", "brow", "blink", "motion") SECOND_FIELDS: tuple[str, ...] = ("cx", "cy", "size", "smile", "jaw", "surprise", "frown", "brow", "blink", "motion")
# --- Mapa de expressões (18/11/2026, doc/clipador/EXPRESSOES.md). Tudo OPCIONAL na série: o que foi gravado antes
# não tem estes campos e continua valendo (canal ausente = parado, nunca vira pico).
# Expressões a mais dos 52 blendshapes (máximo do segundo). `noseSneer*` e `cheekSquint*` saem ~0 SEMPRE no modelo do
# MediaPipe (medido em 4 sessões): nojo e raiva não podem depender deles — o lábio de cima (`upper_lip`) faz o papel.
EXTRA_EXPRESSION_CHANNELS: tuple[str, ...] = (
"brow_inner", # browInnerUp sozinho (medo/tristeza; `brow` junta a interna e a externa)
"mouth_frown", # cantos da boca para baixo (tristeza)
"squint", # olhos semicerrados (raiva/tensão)
"press", # lábios apertados (tensão/raiva)
"stretch", # boca esticada para os lados (medo, careta)
"upper_lip", # lábio de cima levantado (nojo; sobe junto na gargalhada)
"pucker", # boca em "O" (bico ou funil: espanto, "uuuh")
)
POSE_FIELDS: tuple[str, ...] = ("yaw", "pitch", "roll") # graus, média do segundo (matriz de transformação facial)
# Corpo/cabeça: `shake`/`nod` = idas e voltas da cabeça (yaw/pitch) na janela de 2 s que começa 0,5 s antes do segundo;
# `head` = fração dos quadros com a CABEÇA visível (rosto com pontos OU só a caixa do detector, quando o MediaPipe
# perde o rosto de perfil); `head_motion` = caminho da cabeça em tamanhos de cabeça por segundo, sem os saltos de
# reaquisição; `hsize` = tamanho da caixa do detector nos quadros sem pontos (quem se inclina para a câmera de perfil).
BODY_FIELDS: tuple[str, ...] = ("shake", "nod", "head", "head_motion", "hsize")
EXTRA_SECOND_FIELDS: tuple[str, ...] = EXTRA_EXPRESSION_CHANNELS + POSE_FIELDS + BODY_FIELDS
_ONE_DECIMAL: frozenset[str] = frozenset(POSE_FIELDS + ("shake", "nod")) # graus e contagens: 1 casa basta
# Rótulos que não são reação: o pico sai como o "neutro" (bocejo abre a boca como grito, mas não é momento de corte).
NOT_REACTION: frozenset[str] = frozenset({"neutro", "bocejo"})
# Todos os rótulos de expressão (`label`, `yawn_seconds` e "alegria" do mapa); os de corpo estão em `BODY_PRIORITY`.
EXPRESSION_LABELS: tuple[str, ...] = (
"risada", "gargalhada", "alegria", "grito", "susto", "medo", "choque", "espanto", "confuso", "raiva", "nojo",
"tristeza", "tenso", "bocejo", "neutro",
)
@dataclass(frozen=True) @dataclass(frozen=True)
class ReactionParams: class ReactionParams:
@@ -62,6 +94,42 @@ class ReactionParams:
raw_thresholds: dict[str, float] = field(default_factory=lambda: { raw_thresholds: dict[str, float] = field(default_factory=lambda: {
"smile": 0.4, "jaw": 0.35, "surprise": 0.35, "frown": 0.35, "brow": 0.35, "motion": 0.5, "smile": 0.4, "jaw": 0.35, "surprise": 0.35, "frown": 0.35, "brow": 0.35, "motion": 0.5,
}) # usados pelo `label` quando não há z (segundo isolado) }) # usados pelo `label` quando não há z (segundo isolado)
# --- expressões a mais (EXTRA_EXPRESSION_CHANNELS) e corpo; calibrado em doc/clipador/EXPRESSOES.md ---
extra_floors: dict[str, float] = field(default_factory=lambda: {
"brow_inner": 0.10, "mouth_frown": 0.05, "squint": 0.06, "press": 0.08, "stretch": 0.06, "upper_lip": 0.10,
"pucker": 0.12, "head_motion": 0.15,
})
# Peso de cada expressão nova na INTENSIDADE (0 = só rotula). Ver o doc: com peso, viram picos sozinhas.
extra_weights: dict[str, float] = field(default_factory=lambda: {
"brow_inner": 0.0, "mouth_frown": 0.0, "squint": 0.0, "press": 0.0, "stretch": 0.0, "upper_lip": 0.0,
"pucker": 0.0,
})
extra_raw: dict[str, float] = field(default_factory=lambda: {
"brow_inner": 0.5, "mouth_frown": 0.3, "squint": 0.7, "press": 0.5, "stretch": 0.3, "upper_lip": 0.4,
"pucker": 0.6,
}) # limiares absolutos das expressões novas para o `label` sem z
yawn_jaw_raw: float = 0.5 # bocejo: boca muito aberta por ≥ `yawn_min_s` segundos seguidos…
yawn_min_s: int = 2
yawn_squint_z: float = 1.0 # …com os olhos apertando em algum deles (ver `yawn_seconds`)
disgust_smile_max: float = 0.3 # nojo só com o sorriso abaixo disto (valor absoluto)
laugh_jaw_raw: float = 0.3 # risada de boca escancarada = gargalhada
head_back_deg: float = 20.0 # cabeça jogada para trás: X graus acima do neutro dele (com risada = gargalhada)
map_z: float = 2.0 # mapa: segundo com sinal ≥ isto ganha rótulo de expressão (abaixo de `threshold`, sorriso = alegria)
# Corpo/cabeça
shake_deg: float = 8.0 # ida ou volta de pelo menos X graus no yaw conta como uma "perna" do balanço
nod_deg: float = 6.0 # idem no pitch (aceno)
osc_legs: int = 3 # pernas na janela de 2 s para "balançando"/"acenando" (2 = olhou para o lado e voltou)
head_min: float = 0.8 # cabeça visível em ≥ 80 % do segundo para o movimento valer (senão é o rastreio pulando)
head_max_step: float = 1.0 # passo máximo entre dois quadros, em tamanhos de cabeça (mais que isso = reaquisição)
agitation_z: float = 2.5 # agitação: movimento da cabeça com z ≥ isto…
agitation_window_s: int = 5 # …em pelo menos `agitation_min_s` segundos de uma janela deste tamanho
agitation_min_s: int = 3
lean_ratio: float = 1.18 # chegou perto: cabeça ≥ 18 % maior que o tamanho normal dele (p99,9 nas sessões 8/15)…
lean_min_s: int = 1 # …por pelo menos isto
leave_before_s: int = 3 # saiu do quadro: cabeça visível por ≥ 3 s…
leave_gone_s: int = 3 # …e depois sumida por ≥ 3 s (só com o campo `head`: série antiga não diz "saiu")
leave_gone_max: float = 0.1 # "sumida" = cabeça em no máximo 10 % dos quadros do segundo
leave_transition_s: int = 2 # segundos com a cabeça só em parte do quadro entre o "visível" e o "fora"
# --- câmera (locate_cam) --- # --- câmera (locate_cam) ---
min_score: float = 0.6 # confiança mínima da detecção min_score: float = 0.6 # confiança mínima da detecção
# Confiança MÉDIA mínima do grupo que vira câmera. Teste ao vivo de 17/11: webcam real (skipnho) 0,92–0,94 em # Confiança MÉDIA mínima do grupo que vira câmera. Teste ao vivo de 17/11: webcam real (skipnho) 0,92–0,94 em
@@ -91,6 +159,9 @@ class FaceSample:
cy: float = 0.0 cy: float = 0.0
size: float = 0.0 size: float = 0.0
blend: dict[str, float] = field(default_factory=dict) # nomes do MediaPipe (jawOpen, mouthSmileLeft…) blend: dict[str, float] = field(default_factory=dict) # nomes do MediaPipe (jawOpen, mouthSmileLeft…)
pose: tuple[float, float, float] | None = None # (yaw, pitch, roll) em graus; None = sem matriz de transformação
# Só a caixa da cabeça (detector), sem pontos nem blendshapes: `present` fica False e `cx`/`cy`/`size` são da caixa.
head: bool = False
@dataclass @dataclass
@@ -109,20 +180,37 @@ class FaceSecond:
brow: float | None = None brow: float | None = None
blink: float | None = None blink: float | None = None
motion: float | None = None motion: float | None = None
# Mapa de expressões (EXTRA_SECOND_FIELDS): opcionais, ausentes na série gravada antes de 18/11/2026.
brow_inner: float | None = None
mouth_frown: float | None = None
squint: float | None = None
press: float | None = None
stretch: float | None = None
upper_lip: float | None = None
pucker: float | None = None
yaw: float | None = None
pitch: float | None = None
roll: float | None = None
shake: float | None = None
nod: float | None = None
head: float | None = None
head_motion: float | None = None
hsize: float | None = None
def to_json(self) -> dict: def to_json(self) -> dict:
"""Formato compacto para o banco/API: 3 casas, sem os campos `None`.""" """Formato compacto para o banco/API: 3 casas (graus e contagens: 1), sem os campos `None`."""
out: dict = {"t": self.t, "present": round(self.present, 3)} out: dict = {"t": self.t, "present": round(self.present, 3)}
for name in SECOND_FIELDS: for name in SECOND_FIELDS + EXTRA_SECOND_FIELDS:
value = getattr(self, name) value = getattr(self, name)
if value is not None: if value is not None:
out[name] = round(value, 3) out[name] = round(value, 1 if name in _ONE_DECIMAL else 3)
return out return out
@classmethod @classmethod
def from_json(cls, data: dict) -> FaceSecond: def from_json(cls, data: dict) -> FaceSecond:
return cls(int(data["t"]), float(data.get("present", 0.0)), return cls(int(data["t"]), float(data.get("present", 0.0)),
**{n: (float(data[n]) if data.get(n) is not None else None) for n in SECOND_FIELDS}) **{n: (float(data[n]) if data.get(n) is not None else None)
for n in SECOND_FIELDS + EXTRA_SECOND_FIELDS})
@dataclass @dataclass
@@ -177,13 +265,102 @@ def _channels(blend: dict[str, float]) -> dict[str, float]:
} }
def per_second(samples: list[FaceSample], duration_s: float, start_s: float = 0.0) -> list[FaceSecond]: def _extra_channels(blend: dict[str, float]) -> dict[str, float]:
"""Blendshapes do MediaPipe → expressões novas do mapa (EXTRA_EXPRESSION_CHANNELS), 0..1."""
def g(name: str) -> float:
return float(blend.get(name, 0.0))
return {
"brow_inner": g("browInnerUp"),
"mouth_frown": (g("mouthFrownLeft") + g("mouthFrownRight")) / 2,
"squint": (g("eyeSquintLeft") + g("eyeSquintRight")) / 2,
"press": (g("mouthPressLeft") + g("mouthPressRight")) / 2,
"stretch": (g("mouthStretchLeft") + g("mouthStretchRight")) / 2,
"upper_lip": (g("mouthUpperUpLeft") + g("mouthUpperUpRight")) / 2,
"pucker": max(g("mouthPucker"), g("mouthFunnel")),
}
def zigzag_legs(values: list[float], delta: float) -> list[float]:
"""Pernas de um zigue-zague com histerese `delta`: cada ida ou volta de pelo menos `delta` (amplitude).
Cabeça parada com tremida < `delta` → nenhuma perna; olhar para o lado e voltar → 2; balançar → 3 ou mais.
"""
legs: list[float] = []
if not values:
return legs
start = extreme = values[0]
direction = 0
for v in values[1:]:
if direction == 0:
if abs(v - start) >= delta:
direction, extreme = (1 if v > start else -1), v
legs.append(abs(v - start))
continue
if (v - extreme) * direction > 0: # continua na mesma direção: a perna cresce
legs[-1] += abs(v - extreme)
extreme = v
elif abs(v - extreme) >= delta: # virou com folga: perna nova
legs.append(abs(v - extreme))
direction, extreme = -direction, v
return legs
def _body_fields(out: list[FaceSecond], samples: list[FaceSample], first: int, p: ReactionParams) -> None:
"""Preenche pose, balanço/aceno e cabeça (EXTRA: série antiga não tem nada disto)."""
ordered = sorted(samples, key=lambda s: s.t)
posed = [s for s in ordered if s.present and s.pose is not None]
posed_t = [s.t for s in posed]
# Movimento da cabeça: passos entre quadros vizinhos da MESMA fonte (pontos × caixa do detector têm tamanhos
# diferentes), sem buraco de quadro perdido no meio e com o passo limitado: o "pulo" da reaquisição do rosto era o
# maior pico de movimento da live real.
visible = [s for s in ordered if (s.present or s.head) and s.size > 0]
paths = [0.0] * len(out)
for a, b in zip(visible, visible[1:]):
i = int(math.floor(b.t)) - first
if 0 <= i < len(out) and a.present == b.present and b.t - a.t <= 0.4:
step = (math.hypot(b.cx - a.cx, b.cy - a.cy) + abs(b.size - a.size)) / max(1e-6, (a.size + b.size) / 2)
paths[i] += min(step, p.head_max_step)
buckets: list[list[FaceSample]] = [[] for _ in out]
for s in ordered:
i = int(math.floor(s.t)) - first
if 0 <= i < len(out):
buckets[i].append(s)
for i, second in enumerate(out):
bucket = buckets[i]
if not bucket:
continue
seen = [s for s in bucket if (s.present or s.head) and s.size > 0]
second.head = len(seen) / len(bucket)
if seen:
second.head_motion = paths[i]
boxes = [s for s in seen if not s.present]
if boxes:
second.hsize = _mean([s.size for s in boxes])
poses = [s.pose for s in bucket if s.present and s.pose is not None]
if not poses:
continue
second.yaw, second.pitch, second.roll = (_mean([q[k] for q in poses]) for k in range(3))
# Janela de 2 s a partir de 0,5 s antes: um balanço de ~2 Hz a 6 qps tem 1–2 quadros por perna.
lo = bisect.bisect_left(posed_t, second.t - 0.5)
hi = bisect.bisect_left(posed_t, second.t + 1.5)
window = posed[lo:hi]
gaps = [b.t - a.t for a, b in zip(window, window[1:])]
if len(window) >= 6 and (not gaps or max(gaps) <= 0.4):
second.shake = float(len(zigzag_legs([s.pose[0] for s in window], p.shake_deg)))
second.nod = float(len(zigzag_legs([s.pose[1] for s in window], p.nod_deg)))
def per_second(samples: list[FaceSample], duration_s: float, start_s: float = 0.0,
params: ReactionParams | None = None) -> list[FaceSecond]:
"""Agrupa os quadros por segundo em [start_s, start_s + duration_s). """Agrupa os quadros por segundo em [start_s, start_s + duration_s).
Posição/tamanho/piscar = média; expressões = máximo do segundo (a reação dura menos que 1 s às vezes); Posição/tamanho/piscar = média; expressões = máximo do segundo (a reação dura menos que 1 s às vezes);
`motion` = caminho percorrido pelo centro (mais a variação de tamanho, quem se joga para a câmera) dividido `motion` = caminho percorrido pelo centro (mais a variação de tamanho, quem se joga para a câmera) dividido
pelo tamanho do rosto, ou seja, em "rostos por segundo" — independe do zoom da câmera. pelo tamanho do rosto, ou seja, em "rostos por segundo" — independe do zoom da câmera.
Mapa de expressões: expressões novas (máximo), pose (média), balanço/aceno e cabeça — ver `_body_fields`.
""" """
p = params or ReactionParams()
n = max(0, int(math.ceil(duration_s))) n = max(0, int(math.ceil(duration_s)))
first = int(math.floor(start_s)) first = int(math.floor(start_s))
buckets: list[list[FaceSample]] = [[] for _ in range(n)] buckets: list[list[FaceSample]] = [[] for _ in range(n)]
@@ -204,6 +381,10 @@ def per_second(samples: list[FaceSample], duration_s: float, start_s: float = 0.
second.size = _mean([s.size for s in faces]) second.size = _mean([s.size for s in faces])
for name in ("smile", "jaw", "surprise", "frown", "brow"): for name in ("smile", "jaw", "surprise", "frown", "brow"):
setattr(second, name, max(c[name] for c in channels)) setattr(second, name, max(c[name] for c in channels))
if any(s.blend for s in faces): # plano B (sem blendshapes) não inventa expressão nova
extra = [_extra_channels(s.blend) for s in faces]
for name in EXTRA_EXPRESSION_CHANNELS:
setattr(second, name, max(c[name] for c in extra))
second.blink = _mean([c["blink"] for c in channels]) second.blink = _mean([c["blink"] for c in channels])
path = 0.0 path = 0.0
for s in faces: for s in faces:
@@ -213,6 +394,7 @@ def per_second(samples: list[FaceSample], duration_s: float, start_s: float = 0.
previous = s previous = s
second.motion = path second.motion = path
out.append(second) out.append(second)
_body_fields(out, samples, first, p)
return out return out
@@ -262,13 +444,71 @@ def channel_z(seconds: list[FaceSecond], params: ReactionParams | None = None) -
if second.present < p.motion_min_present: if second.present < p.motion_min_present:
z["motion"] = 0.0 z["motion"] = 0.0
out.append(z) out.append(z)
_extra_z(seconds, face_idx, out, p)
return out return out
def rolling_baseline(seconds: list[FaceSecond], idx: list[int], name: str, floor: float,
p: ReactionParams) -> dict[int, tuple[float, float]]:
"""(mediana, desvio robusto) do campo `name` no neutro recente, para cada índice de `idx` (que já deve conter só
segundos com o campo). Mesma janela do `channel_z`; com menos de `min_baseline_n` segundos na série inteira,
devolve {} — canal novo numa série que mal começou a tê-lo não vira pico."""
if len(idx) < p.min_baseline_n:
return {}
values = [float(getattr(seconds[i], name)) for i in idx]
cache: dict[tuple[int, int], tuple[float, float]] = {}
out: dict[int, tuple[float, float]] = {}
for i in idx:
anchor = i - i % BASELINE_STEP_S
lo = bisect.bisect_left(idx, anchor - p.baseline_s)
hi = bisect.bisect_left(idx, anchor - p.exclude_recent_s)
if hi - lo < p.min_baseline_n:
lo, hi = 0, len(idx)
if (lo, hi) not in cache:
cache[(lo, hi)] = _robust(values[lo:hi], floor)
out[i] = cache[(lo, hi)]
return out
def _extra_z(seconds: list[FaceSecond], face_idx: list[int], out: list[dict[str, float] | None],
p: ReactionParams) -> None:
"""z das expressões novas e "cabeça para trás" (graus acima do neutro), no mesmo dict do `channel_z`.
Ao contrário dos canais antigos, o neutro de um canal novo usa SÓ os segundos que têm o campo: numa sessão em
que o serviço foi atualizado no meio, os segundos antigos (sem o campo) não podem virar um neutro de zeros.
"""
for name in EXTRA_EXPRESSION_CHANNELS:
idx = [i for i in face_idx if getattr(seconds[i], name) is not None]
base = rolling_baseline(seconds, idx, name, p.extra_floors.get(name, p.mad_floor), p)
for i in face_idx:
z = out[i]
if z is None:
continue
value = getattr(seconds[i], name)
if i in base and value is not None:
median, spread = base[i]
z[name] = (value - median) / spread
else:
z[name] = 0.0
# Pitch diminui quando a cabeça vai para trás (olhar para cima): "head_back" = neutro − pitch, em graus.
idx = [i for i in face_idx if seconds[i].pitch is not None]
base = rolling_baseline(seconds, idx, "pitch", 1.0, p)
for i in face_idx:
z = out[i]
if z is not None:
pitch = seconds[i].pitch
z["head_back"] = (base[i][0] - pitch) if (i in base and pitch is not None) else 0.0
def _signal_from_z(z: dict[str, float] | None, p: ReactionParams) -> float | None: def _signal_from_z(z: dict[str, float] | None, p: ReactionParams) -> float | None:
if z is None: if z is None:
return None return None
return max(0.0, max(p.weights.get(name, 1.0) * z[name] for name in EXPRESSION_CHANNELS)) signal = max(p.weights.get(name, 1.0) * z[name] for name in EXPRESSION_CHANNELS)
for name in EXTRA_EXPRESSION_CHANNELS:
weight = p.extra_weights.get(name, 0.0)
if weight > 0:
signal = max(signal, weight * z.get(name, 0.0))
return max(0.0, signal)
def reaction_signal(seconds: list[FaceSecond], baseline_s: int | None = None, def reaction_signal(seconds: list[FaceSecond], baseline_s: int | None = None,
@@ -285,42 +525,75 @@ def reaction_signal(seconds: list[FaceSecond], baseline_s: int | None = None,
def label(second: FaceSecond, z: dict[str, float] | None = None, params: ReactionParams | None = None) -> str: def label(second: FaceSecond, z: dict[str, float] | None = None, params: ReactionParams | None = None) -> str:
"""Rótulo da expressão: risada, grito, susto, choque, confuso, raiva ou neutro. """Rótulo da expressão do segundo (um de `EXPRESSION_LABELS`; bocejo e alegria precisam de contexto e saem de
`yawn_seconds`/`expression_map`).
Com `z` (de `channel_z`), um canal está "ligado" quando sobe acima do neutro do streamer; sem `z`, usa limiares Com `z` (de `channel_z`), um canal está "ligado" quando sobe acima do neutro do streamer; sem `z`, usa limiares
absolutos (`raw_thresholds`). absolutos (`raw_thresholds`, `extra_raw`).
Regras (calibradas na live real, doc/FACE_BAKEOFF.md): Regras (calibradas na live real, doc/FACE_BAKEOFF.md e doc/clipador/EXPRESSOES.md), na ordem:
- **risada** = sorriso subindo (sem exigir boca aberta: o streamer da bancada ri de boca quase fechada, - **risada** = sorriso subindo (sem exigir boca aberta: o streamer da bancada ri de boca quase fechada,
jawOpen ≤ 0,1); sorriso alto em valor absoluto também conta quando outro canal de rosto sobe junto (no jawOpen ≤ 0,1); sorriso alto em valor absoluto também conta quando outro canal de rosto sobe junto (no
streamer que já sorri o tempo todo o sorriso não tem para onde subir); streamer que já sorri o tempo todo o sorriso não tem para onde subir); com a cabeça jogada para trás =
- **grito** = boca aberta sem sorriso, ou sobrancelha franzida com a boca ao menos entreaberta (no grito real: **gargalhada**;
browDown 0,61 + jawOpen 0,42 num segundo); franzida de boca fechada = **raiva**;
- **susto** = sobrancelha levantada ou olho arregalado + movimento da cabeça; - **susto** = sobrancelha levantada ou olho arregalado + movimento da cabeça;
- **medo** = sobrancelha interna levantada + boca esticada para os lados (ou olho arregalado com a sobrancelha
descendo) — sem isso, olho arregalado é choque;
- **grito** = boca aberta sem sorriso, ou sobrancelha franzida com a boca ao menos entreaberta (no grito real:
browDown 0,61 + jawOpen 0,42 num segundo); franzida de boca fechada = **raiva**; olhos semicerrados + lábios
apertados com a sobrancelha descendo também é raiva; lábio de cima subindo com o sorriso já alto é risada;
- **nojo** = lábio de cima levantado sem sorriso e de boca fechada (`noseSneer` não funciona no MediaPipe);
- **tristeza** = cantos da boca para baixo + sobrancelha interna levantada, sem bico nem boca esticada (mão na
boca faz os dois);
- **espanto** = boca em "O" com a sobrancelha levantada ou a boca abrindo;
- **choque** = olho arregalado parado; - **choque** = olho arregalado parado;
- **confuso** = sobrancelha levantada parada, sem sorriso (cara de "ué?" no lag: browInnerUp 0,27 de média - **confuso** = sobrancelha levantada parada, sem sorriso (cara de "ué?" no lag: browInnerUp 0,27 de média
contra 0,02 no calmo). contra 0,02 no calmo);
- **tenso** = lábios apertados + olhos semicerrados, sem sorriso (foco, tensão).
""" """
p = params or ReactionParams() p = params or ReactionParams()
if second.smile is None: if second.smile is None:
return "neutro" return "neutro"
if z is not None: if z is not None:
on = {name: z.get(name, 0.0) >= p.label_z for name in SIGNAL_CHANNELS} on = {name: z.get(name, 0.0) >= p.label_z for name in SIGNAL_CHANNELS + EXTRA_EXPRESSION_CHANNELS}
half = {name: z.get(name, 0.0) >= p.label_z / 2 for name in SIGNAL_CHANNELS + EXTRA_EXPRESSION_CHANNELS}
head_back = z.get("head_back", 0.0) >= p.head_back_deg
else: else:
on = {name: (getattr(second, name) or 0.0) >= p.raw_thresholds[name] for name in SIGNAL_CHANNELS} on = {name: (getattr(second, name) or 0.0) >= p.raw_thresholds[name] for name in SIGNAL_CHANNELS}
on |= {name: (getattr(second, name) or 0.0) >= p.extra_raw[name] for name in EXTRA_EXPRESSION_CHANNELS}
half = {name: on[name] for name in on}
head_back = False
smiling_raw = second.smile >= p.smile_raw smiling_raw = second.smile >= p.smile_raw
if on["smile"] or (smiling_raw and (on["jaw"] or on["frown"] or on["brow"])): jaw = second.jaw or 0.0
return "risada" # Lábio de cima subindo com o sorriso já alto = rindo mostrando os dentes (sessão 8: 0,6–0,8 nas risadas).
if on["smile"] or (smiling_raw and (on["jaw"] or on["frown"] or on["brow"] or on["upper_lip"])):
return "gargalhada" if head_back else "risada"
if (on["surprise"] or on["brow"]) and on["motion"]: if (on["surprise"] or on["brow"]) and on["motion"]:
return "susto" return "susto"
# Medo × choque (FACS): os dois levantam a sobrancelha e arregalam o olho; o medo estica a boca para os lados
# (AU20) ou junta a sobrancelha descendo (AU4).
if on["brow_inner"] and (on["stretch"] or (on["surprise"] and half["frown"])):
return "medo"
if on["jaw"]: if on["jaw"]:
return "grito" return "grito"
if on["frown"]: if on["frown"]:
return "grito" if (second.jaw or 0.0) >= p.shout_jaw_raw else "raiva" return "grito" if jaw >= p.shout_jaw_raw else "raiva"
if on["squint"] and on["press"] and half["frown"]:
return "raiva"
# Nojo só sem sorriso: o lábio de cima sobe junto em toda risada de dentes à mostra.
if on["upper_lip"] and not half["jaw"] and second.smile < p.disgust_smile_max:
return "nojo"
# Mão na boca (tique comum: queixo apoiado, coçar o nariz) faz bico e estica a boca: aí não é tristeza.
if on["mouth_frown"] and half["brow_inner"] and not on["pucker"] and not on["stretch"]:
return "tristeza"
if on["pucker"] and (on["brow"] or half["jaw"]):
return "espanto"
if on["surprise"]: if on["surprise"]:
return "choque" return "choque"
if on["brow"]: if on["brow"]:
return "confuso" return "confuso"
if on["press"] and on["squint"]:
return "tenso"
return "neutro" return "neutro"
@@ -351,9 +624,10 @@ def reaction_moments(seconds: list[FaceSecond], params: ReactionParams | None =
run[i] = current run[i] = current
candidates = sorted((i for i, v in enumerate(values) if v >= p.threshold), key=lambda i: -values[i]) candidates = sorted((i for i, v in enumerate(values) if v >= p.threshold), key=lambda i: -values[i])
chosen: list[tuple[int, str]] = [] chosen: list[tuple[int, str]] = []
yawns = yawn_seconds(seconds, zs, p)
for peak in candidates: for peak in candidates:
name = _peak_label(seconds, zs, peak, p) name = _peak_label(seconds, zs, peak, p, yawns)
if name == "neutro" and not p.keep_neutral: if name in NOT_REACTION and not p.keep_neutral:
continue continue
# Perto demais de um pico maior, ou mesma reação no mesmo trecho contínuo → é o mesmo momento. # Perto demais de um pico maior, ou mesma reação no mesmo trecho contínuo → é o mesmo momento.
if any(abs(peak - j) < p.min_gap_s or (run[peak] == run[j] and name == other) for j, other in chosen): if any(abs(peak - j) < p.min_gap_s or (run[peak] == run[j] and name == other) for j, other in chosen):
@@ -372,12 +646,32 @@ def reaction_moments(seconds: list[FaceSecond], params: ReactionParams | None =
return moments return moments
def _peak_label(seconds: list[FaceSecond], zs: list[dict[str, float] | None], peak: int, p: ReactionParams) -> str: def yawn_seconds(seconds: list[FaceSecond], zs: list[dict[str, float] | None], p: ReactionParams) -> set[int]:
"""Índices dos segundos de bocejo: boca muito aberta (jawOpen ≥ `yawn_jaw_raw`) por ≥ `yawn_min_s` segundos
seguidos, com os olhos apertando (z do `squint` ≥ `yawn_squint_z`) em algum deles.
Sessão 8 (skipnho, fim de live): os 5 trechos com jawOpen ≥ 0,6 por 3 s eram todos bocejos (olhos fechados,
braços esticando) e eram os maiores "gritos" da sessão (z 12–16); os gritos e exclamações de verdade abriram a
boca assim por 1 s só. O bocejo também levanta o "sorriso" (cantos esticados): por isso vem antes da risada.
"""
wide = [(s.jaw or 0.0) >= p.yawn_jaw_raw and zs[i] is not None for i, s in enumerate(seconds)]
out: set[int] = set()
for i, j in _runs(wide, 0):
if j - i + 1 >= p.yawn_min_s and any((zs[k] or {}).get("squint", 0.0) >= p.yawn_squint_z
for k in range(i, j + 1)):
out.update(range(i, j + 1))
return out
def _peak_label(seconds: list[FaceSecond], zs: list[dict[str, float] | None], peak: int, p: ReactionParams,
yawns: set[int] | None = None) -> str:
if yawns and peak in yawns:
return "bocejo"
name = label(seconds[peak], zs[peak], p) name = label(seconds[peak], zs[peak], p)
if name == "neutro": if name == "neutro":
for j in (peak - 1, peak + 1): for j in (peak - 1, peak + 1):
if 0 <= j < len(seconds) and zs[j] is not None: if 0 <= j < len(seconds) and zs[j] is not None:
other = label(seconds[j], zs[j], p) other = "bocejo" if yawns and j in yawns else label(seconds[j], zs[j], p)
if other != "neutro": if other != "neutro":
return other return other
return name return name
@@ -385,32 +679,199 @@ def _peak_label(seconds: list[FaceSecond], zs: list[dict[str, float] | None], pe
def summarize(seconds: list[FaceSecond], start_s: float = 0.0, end_s: float | None = None, def summarize(seconds: list[FaceSecond], start_s: float = 0.0, end_s: float | None = None,
params: ReactionParams | None = None, max_items: int = 4, params: ReactionParams | None = None, max_items: int = 4,
moments: list[ReactionMoment] | None = None, relative: bool = True) -> str: moments: list[ReactionMoment] | None = None, relative: bool = True,
body: list[BodyMoment] | None = None) -> str:
"""Texto curto para o juiz sobre o rosto no trecho [start_s, end_s], com tempos relativos ao início do trecho. """Texto curto para o juiz sobre o rosto no trecho [start_s, end_s], com tempos relativos ao início do trecho.
Passe a série inteira (ou bem mais que o trecho): o neutro do streamer vem do que veio antes. Passe a série inteira (ou bem mais que o trecho): o neutro do streamer vem do que veio antes.
Ex.: "risada forte em 12 s; susto em 15 s". `moments` (opcional): picos já calculados com `reaction_moments` Ex.: "risada forte em 12 s; susto em 15 s". `moments` (opcional): picos já calculados com `reaction_moments`
sobre a série inteira — evita recalcular a live toda a cada corte (~1 s por hora de live). sobre a série inteira — evita recalcular a live toda a cada corte (~1 s por hora de live).
`relative=False`: tempos da gravação ("risada forte em 1628s"), como o resto do prompt do juiz. `relative=False`: tempos da gravação ("risada forte em 1628s"), como o resto do prompt do juiz.
Corpo/cabeça (`body_moments`, ou `body` já calculado) entra no fim: "balançando a cabeça em 15 s". Com a cabeça
visível mas sem expressão legível (de perfil, longe), o texto diz isso e traz só o corpo.
""" """
p = params or ReactionParams() p = params or ReactionParams()
end = end_s if end_s is not None else (seconds[-1].t + 1 if seconds else start_s) end = end_s if end_s is not None else (seconds[-1].t + 1 if seconds else start_s)
inside = [s for s in seconds if start_s <= s.t <= end] inside = [s for s in seconds if start_s <= s.t <= end]
def when(t: float) -> str:
return f"{int(round(t - start_s))} s" if relative else f"{t:.0f}s"
body_parts = [f"{BODY_TEXT.get(b.label, b.label)} em {when(b.peak_s)}"
for b in (body if body is not None else body_moments(seconds, p)) if start_s <= b.peak_s <= end]
with_face = [s for s in inside if _has_face(s, p)] with_face = [s for s in inside if _has_face(s, p)]
if not with_face: if not with_face:
return "rosto do streamer não aparece no trecho" heads = [s for s in inside if (s.head or 0.0) >= p.min_present]
if not inside or len(heads) < max(1, len(inside) // 3):
return "rosto do streamer não aparece no trecho"
text = (f"rosto sem expressão legível (de perfil ou longe; cabeça visível em "
f"{int(round(100 * len(heads) / len(inside)))}% do trecho)")
return text + ("; " + "; ".join(body_parts[:max_items]) if body_parts else "; sem movimento marcante")
parts = [] parts = []
for m in (moments if moments is not None else reaction_moments(seconds, p)): for m in (moments if moments is not None else reaction_moments(seconds, p)):
if start_s <= m.peak_s <= end: if start_s <= m.peak_s <= end:
when = f"{int(round(m.peak_s - start_s))} s" if relative else f"{m.peak_s:.0f}s" parts.append(f"{m.label}{' forte' if m.strong else ''} em {when(m.peak_s)}")
parts.append(f"{m.label}{' forte' if m.strong else ''} em {when}")
presence = len(with_face) / len(inside) presence = len(with_face) / len(inside)
text = "; ".join(parts[:max_items]) if parts else "sem reação marcante no rosto" text = "; ".join(parts[:max_items]) if parts else "sem reação marcante no rosto"
if body_parts:
text += "; " + "; ".join(body_parts[:2])
if presence < 0.7: if presence < 0.7:
text += f" (rosto visível em {int(round(presence * 100))}% do trecho)" text += f" (rosto visível em {int(round(presence * 100))}% do trecho)"
return text return text
# ---------------------------------------------------------------------------------------------------------------
# Corpo/cabeça e mapa de expressões
# Texto de cada rótulo de corpo no resumo do juiz.
BODY_TEXT: dict[str, str] = {
"balançando": "balançando a cabeça", "acenando": "acenando com a cabeça", "agitado": "agitado na cadeira",
"chegou perto": "chegou perto da câmera", "saiu do quadro": "saiu do quadro",
}
BODY_PRIORITY: tuple[str, ...] = ("saiu do quadro", "chegou perto", "agitado", "balançando", "acenando")
@dataclass
class BodyMoment:
"""Movimento da cabeça/corpo num trecho (mesmo sem expressão no rosto)."""
start_s: int
end_s: int
peak_s: int
label: str # balançando | acenando | agitado | chegou perto | saiu do quadro
value: float # pernas do balanço, z do movimento, razão do tamanho ou segundos fora, conforme o rótulo
def to_json(self) -> dict:
return {"startS": self.start_s, "endS": self.end_s, "peakS": self.peak_s, "label": self.label,
"value": round(self.value, 2)}
def _head_ok(second: FaceSecond, p: ReactionParams) -> bool:
"""Cabeça bem visível no segundo inteiro (rastreio sem pulos). Série antiga: usa o rosto."""
if second.head is not None:
return second.head >= p.head_min
return second.present >= p.motion_min_present
def _runs(flags: list[bool], max_gap: int = 1) -> list[tuple[int, int]]:
"""Trechos [i, j] de índices ligados, juntando buracos de até `max_gap` segundos."""
out: list[tuple[int, int]] = []
for i, on in enumerate(flags):
if not on:
continue
if out and i - out[-1][1] <= max_gap + 1:
out[-1] = (out[-1][0], i)
else:
out.append((i, i))
return out
def body_moments(seconds: list[FaceSecond], params: ReactionParams | None = None) -> list[BodyMoment]:
"""Balanço, aceno, agitação, chegar perto e sair do quadro — relativos ao normal do próprio streamer.
Rastreio perdido nunca vira movimento: só contam segundos com a cabeça em ≥ `head_min` dos quadros, o passo
entre quadros é limitado (`head_max_step`) e a agitação exige a janela inteira com a cabeça visível.
"""
p = params or ReactionParams()
n = len(seconds)
ok = [_head_ok(s, p) for s in seconds]
out: list[BodyMoment] = []
def add(name: str, i: int, j: int, values: list[float]) -> None:
k = max(range(i, j + 1), key=lambda x: values[x])
out.append(BodyMoment(seconds[i].t, seconds[j].t, seconds[k].t, name, values[k]))
shake = [(s.shake or 0.0) if ok[i] else 0.0 for i, s in enumerate(seconds)]
nod = [(s.nod or 0.0) if ok[i] else 0.0 for i, s in enumerate(seconds)]
for i, j in _runs([v >= p.osc_legs for v in shake], 0):
add("balançando", i, j, shake)
for i, j in _runs([nod[k] >= p.osc_legs and shake[k] < p.osc_legs for k in range(n)], 0):
add("acenando", i, j, nod)
# Agitação: movimento da cabeça bem acima do normal dele em vários segundos de uma janela sem rastreio perdido.
idx = [i for i, s in enumerate(seconds) if ok[i] and s.head_motion is not None]
base = rolling_baseline(seconds, idx, "head_motion", p.extra_floors.get("head_motion", 0.15), p)
motion_z = [0.0] * n
for i in idx:
if i in base:
median, spread = base[i]
motion_z[i] = ((seconds[i].head_motion or 0.0) - median) / spread
hot = [False] * n
w = p.agitation_window_s
for i in range(0, max(0, n - w + 1)):
window = range(i, i + w)
if all(ok[k] for k in window) and sum(motion_z[k] >= p.agitation_z for k in window) >= p.agitation_min_s:
for k in window:
hot[k] = hot[k] or motion_z[k] >= p.agitation_z
for i, j in _runs(hot, 1):
add("agitado", i, j, motion_z)
# Chegou perto: cabeça bem maior que o tamanho normal dele (rosto com pontos e caixa do detector têm escalas
# diferentes: cada um contra o próprio neutro).
ratio = [0.0] * n
sources = (("size", lambda s: s.present >= p.motion_min_present and bool(s.size)),
("hsize", lambda s: s.hsize is not None and s.present < p.min_present))
for name, has in sources:
idx = [i for i, s in enumerate(seconds) if ok[i] and has(s)]
base = rolling_baseline(seconds, idx, name, 1e-6, p)
for i in idx:
if i in base and base[i][0] > 0:
ratio[i] = float(getattr(seconds[i], name)) / base[i][0]
for i, j in _runs([r >= p.lean_ratio for r in ratio], 0):
if j - i + 1 >= p.lean_min_s:
add("chegou perto", i, j, ratio)
# Saiu do quadro: só com o campo `head` (a caixa do detector segue a cabeça de perfil; sem ele, o MediaPipe
# perdendo o rosto pareceria saída). Segundo sem dado nenhum (bloco não rastreado) não conta como fora.
# Levantar e sair leva 1–2 s com a cabeça só em parte do segundo (sessão 15: "++" antes do vazio): até
# `leave_transition_s` segundos parciais entre o "visível" e o "fora" contam como a saída.
gone = [s.head is not None and s.head <= p.leave_gone_max for s in seconds]
for i, j in _runs(gone, 0):
if j - i + 1 < p.leave_gone_s:
continue
start = i
while (start > 0 and i - start < p.leave_transition_s and seconds[start - 1].head is not None
and p.leave_gone_max < (seconds[start - 1].head or 0.0) < p.head_min):
start -= 1
before = range(max(0, start - p.leave_before_s), start)
if len(before) == p.leave_before_s and all(
seconds[k].head is not None and (seconds[k].head or 0.0) >= p.head_min for k in before):
out.append(BodyMoment(seconds[start].t, seconds[j].t, seconds[start].t, "saiu do quadro",
float(j - i + 1)))
return sorted(out, key=lambda b: (b.start_s, BODY_PRIORITY.index(b.label)))
def expression_map(seconds: list[FaceSecond], params: ReactionParams | None = None,
body: list[BodyMoment] | None = None) -> list[dict]:
"""Mapa de expressões: por segundo, a expressão dominante (`expr`) e o movimento do corpo (`body`).
`expr`: `None` sem rosto; senão o rótulo do segundo (`label` com o z do neutro do streamer). Sorriso que não chega
a pico (sinal < `threshold`) é **alegria**, não risada. `body`: rótulo do `body_moments` que cobre o segundo
(prioridade: saiu do quadro > chegou perto > agitado > balançando > acenando) ou `None`.
"""
p = params or ReactionParams()
zs = channel_z(seconds, p)
yawns = yawn_seconds(seconds, zs, p)
out = []
for i, (second, z) in enumerate(zip(seconds, zs)):
expr = None
if z is not None:
expr = "bocejo" if i in yawns else label(second, z, p)
# Sorriso sem pico e sem boca abrindo/dentes à mostra = alegria; rindo de dentes à mostra continua risada.
if (expr == "risada" and (_signal_from_z(z, p) or 0.0) < p.threshold
and z.get("jaw", 0.0) < p.label_z and z.get("upper_lip", 0.0) < p.label_z):
expr = "alegria"
out.append({"t": second.t, "expr": expr, "body": None})
first = seconds[0].t if seconds else 0
for b in sorted(body if body is not None else body_moments(seconds, p),
key=lambda b: -BODY_PRIORITY.index(b.label)): # o mais importante escreve por último
for t in range(b.start_s, b.end_s + 1):
i = t - first
if 0 <= i < len(out):
out[i]["body"] = b.label
return out
# --------------------------------------------------------------------------------------------------------------- # ---------------------------------------------------------------------------------------------------------------
# Onde está a câmera # Onde está a câmera
+3
View File
@@ -90,6 +90,9 @@ class Word:
start: float start: float
end: float end: float
word: str word: str
# Quem falou (doc/clipador/FALANTES.md): "" ou "streamer" = o streamer; "other1", "other2"… = outra pessoa (colega no
# Discord, voz do jogo). Vazio = não atribuído — conta como streamer (o comportamento de antes).
speaker: str = ""
@dataclass @dataclass
+498
View File
@@ -0,0 +1,498 @@
"""Quem fala cada palavra: o streamer ou outra pessoa (colega no Discord, voz do jogo). Doc: doc/clipador/FALANTES.md.
Pedido do dono (18/11/2026): "está atribuindo ao streamer a fala de outro jogador". O áudio da live é um canal só
(microfone do streamer + Discord + jogo misturados) e o Whisper devolve as palavras sem dizer de quem são.
Como decide (medido na sessão 15, tfue com dois colegas no Discord):
1. **Voz** (`index_block`, na análise de cada bloco, logo depois do Whisper): a fala vira trechos curtos (palavras
seguidas, ≤ 3 s) e cada trecho ≥ 0,5 s vira uma impressão de voz (WeSpeaker ResNet34-LM, `voiceprint.py`) +
o volume (dBFS). Fica na tabela `voice_chunks`.
2. **Vozes da sessão** (`model`, sob demanda, em cache): agrupa os trechos ≥ 1 s pela voz (aglomerativo, cosseno ≥
0,5 entre centros); grupo com ≥ 15 s de fala é uma "voz". Na sessão 15 saíram 3 vozes (263 s, 237 s, 201 s).
3. **Qual voz é o streamer** (`pick_streamer`): a que mexe mais a boca na webcam (série `mouth` de `face.py`, soma de
muitos trechos; t ≥ 3 contra a segunda) — ou, sem câmera/sem certeza, a mais alta no áudio (o microfone dele vem
mais forte que o Discord: +4,6 dB na sessão 15) se a diferença for ≥ 3 dB. Nenhum dos dois decide → ninguém vira
"outro": tudo fica `streamer` (o comportamento de antes).
4. **Cada trecho** vai para a voz mais parecida; só vira `otherN` com folga (≥ 0,10 de cosseno a mais que o
streamer e ≥ 0,30 com a outra voz; +0,05 nos dois para trecho < 1 s). Trecho curto sem impressão herda o vizinho mais próximo (≤ 1 s); senão, streamer.
Palavra que já chega com `speaker` (4º elemento do `words_json`) fica como está.
"""
from __future__ import annotations
import base64
import bisect
import json
import logging
import math
import threading
import time
from collections.abc import Callable, Iterable
from dataclasses import dataclass, field, replace
from typing import TYPE_CHECKING, Any
from .db import loads, now
from .scoring import Word
if TYPE_CHECKING: # pragma: no cover
from .worker import Engine
log = logging.getLogger("cenaforge_clipper.speakers")
STREAMER = "streamer"
MODEL_ID = "wespeaker_r34" # entrada do models.lock.json
CHUNK_GAP_S = 0.25 # vão entre palavras que fecha o trecho
CHUNK_MAX_S = 3.0 # trecho mais longo que isto é partido
EMBED_MIN_S = 0.5 # trecho mais curto não vira impressão de voz (herda o vizinho)
EMBED_PAD_S = 0.1 # folga de áudio em volta do trecho
CLUSTER_MIN_S = 1.0 # só trechos ≥ 1 s formam as vozes (os curtos só são atribuídos)
MERGE_SIM = 0.5 # cosseno mínimo entre centros para juntar dois grupos (sessão 15: vozes diferentes a 0,26–0,33)
VOICE_MIN_S = 15.0 # grupo com menos fala que isso não é uma voz (ruído, risada, voz do jogo solta)
CLUSTER_CAP = 600 # trechos usados no agrupamento (o resto só é atribuído): custo O(n²)
# "Outro" só com folga de cosseno sobre o streamer E parecido o bastante com a outra voz. Calibrado na sessão 15:
# trecho curto (0,5–1 s) de colega dá cosseno 0,3–0,45 com a voz dele e ~0 com a do streamer; com 0,45 fixo, 150
# trechos assim ficavam como do streamer. Trecho curto pede um pouco mais dos dois.
OTHER_MARGIN = 0.10
OTHER_MIN_SIM = 0.30
SHORT_EXTRA = 0.05
NEIGHBOR_S = 1.0 # trecho curto herda o rótulo do vizinho até esta distância
EMBEDDER_RETRY_S = 300 # modelo de voz que falhou ao carregar: espera isto antes de tentar de novo
MOUTH_MIN_FRAMES = 3 # quadros com rosto para o trecho contar na boca
MOUTH_MIN_CHUNKS = 8 # trechos por voz para comparar a boca
MOUTH_MIN_T = 3.0 # t de Welch mínimo (melhor × segunda voz); sinal fraco por trecho, ver `pick_streamer`
LOUD_MIN_DB = 3.0 # diferença mínima de volume (mediana) para decidir pelo áudio
def is_other(speaker: str | None) -> bool:
return bool(speaker) and speaker != STREAMER
def parse_words(raw: str | None) -> list[Word]:
"""`words_json` → palavras. Aceita [início, fim, texto] (antigo) e [início, fim, texto, falante]."""
out = []
for item in loads(raw, []) or []:
if not isinstance(item, (list, tuple)) or len(item) < 3:
continue
speaker = str(item[3]) if len(item) > 3 and item[3] else ""
out.append(Word(float(item[0]), float(item[1]), str(item[2]), speaker))
return out
def dump_words(words: Iterable[Word]) -> str:
"""Palavras → `words_json` (4º elemento só quando há falante: o formato antigo continua igual)."""
return json.dumps([[w.start, w.end, w.word, w.speaker] if w.speaker else [w.start, w.end, w.word] for w in words],
ensure_ascii=False)
# ---------------------------------------------------------------------------------------------------------------
# Trechos de fala
def speech_chunks(words: list[Word], gap_s: float = CHUNK_GAP_S, max_s: float = CHUNK_MAX_S) -> list[tuple[float, float]]:
"""(início, fim) de cada trecho de fala contínua: palavras seguidas com vão ≤ `gap_s`, até `max_s`. Também fecha
no fim de frase (. ? !) com o trecho já ≥ `EMBED_MIN_S`: numa conversa a vez troca quase sempre ali, mesmo sem
pausa (sessão 15: "…you should bring two. | I got one code tablet completed." vinham num trecho só)."""
out: list[tuple[float, float]] = []
cur: tuple[float, float] | None = None
closed = False
for w in sorted((w for w in words if w.word.strip()), key=lambda w: w.start):
if cur and not closed and w.start - cur[1] <= gap_s and max(cur[1], w.end) - cur[0] <= max_s:
cur = (cur[0], max(cur[1], w.end))
else:
if cur:
out.append(cur)
cur = (w.start, max(w.end, w.start))
closed = w.word.rstrip().endswith((".", "?", "!")) and cur[1] - cur[0] >= EMBED_MIN_S
if cur:
out.append(cur)
return out
@dataclass
class VoiceChunk:
start: float
end: float
db: float | None = None
vec: Any = None # numpy (256,) com norma 1, ou None (curto demais)
label: str = ""
@property
def length(self) -> float:
return self.end - self.start
def encode_vec(vec: list[float]) -> str:
import numpy as np
return base64.b64encode(np.asarray(vec, np.float16).tobytes()).decode("ascii")
def decode_vec(raw: str) -> Any:
import numpy as np
v = np.frombuffer(base64.b64decode(raw), np.float16).astype(np.float32)
n = float(np.linalg.norm(v))
return v / n if n > 0 else None
# ---------------------------------------------------------------------------------------------------------------
# Agrupamento e decisão (numpy, sem E/S)
def cluster(vectors: Any, threshold: float = MERGE_SIM) -> list[list[int]]:
"""Aglomerativo pelo centro (cosseno entre as médias normalizadas): junta o par mais parecido até nenhum par
passar de `threshold`. Devolve os índices de cada grupo."""
import numpy as np
n = len(vectors)
if n == 0:
return []
sums = np.array(vectors, np.float64)
members: list[list[int] | None] = [[i] for i in range(n)]
cent = sums / np.linalg.norm(sums, axis=1, keepdims=True)
sim = cent @ cent.T
np.fill_diagonal(sim, -np.inf)
alive = np.ones(n, bool)
while True:
flat = int(np.argmax(sim))
i, j = divmod(flat, n)
if not np.isfinite(sim[i, j]) or sim[i, j] < threshold:
break
members[i] = (members[i] or []) + (members[j] or [])
members[j] = None
alive[j] = False
sums[i] += sums[j]
cent[i] = sums[i] / np.linalg.norm(sums[i])
row = cent @ cent[i]
row[~alive] = -np.inf
row[i] = -np.inf
sim[i, :] = row
sim[:, i] = row
sim[j, :] = -np.inf
sim[:, j] = -np.inf
return [m for m in members if m]
@dataclass
class Voice:
label: str
centroid: Any
speech_s: float
db: float | None
mouth: list[float] = field(default_factory=list)
def to_json(self) -> dict:
m = self.mouth
return {"label": self.label, "speechS": round(self.speech_s, 1),
"db": None if self.db is None else round(self.db, 1),
"mouth": round(sum(m) / len(m), 4) if m else None, "mouthChunks": len(m)}
def _welch_t(a: list[float], b: list[float]) -> float:
if len(a) < 2 or len(b) < 2:
return 0.0
ma, mb = sum(a) / len(a), sum(b) / len(b)
va = sum((x - ma) ** 2 for x in a) / (len(a) - 1)
vb = sum((x - mb) ** 2 for x in b) / (len(b) - 1)
se = math.sqrt(va / len(a) + vb / len(b))
return (ma - mb) / se if se > 0 else 0.0
def pick_streamer(voices: list[Voice]) -> tuple[int | None, str]:
"""Índice da voz do streamer e o porquê. Duas provas: a boca na webcam (a voz que mais mexe a boca dele) e o
volume (o microfone dele vem mais forte que o Discord). Concordam ou só uma decide → ela; discordam → None
(ninguém vira "outro"). Na sessão 15 (rosto de perfil) a boca nunca decidiu e chegou a apontar a voz errada nos
10 primeiros minutos (t < 2): por isso o limiar da boca é alto."""
if len(voices) < 2:
return (0 if voices else None), "uma voz só"
idx = range(len(voices))
with_mouth = sorted((i for i in idx if len(voices[i].mouth) >= MOUTH_MIN_CHUNKS),
key=lambda i: -sum(voices[i].mouth) / len(voices[i].mouth))
by_mouth, why_mouth = None, ""
if len(with_mouth) >= 2:
t = _welch_t(voices[with_mouth[0]].mouth, voices[with_mouth[1]].mouth)
if t >= MOUTH_MIN_T:
by_mouth, why_mouth = with_mouth[0], f"boca (t={t:.1f})"
loud = sorted((i for i in idx if voices[i].db is not None), key=lambda i: -(voices[i].db or 0.0))
by_loud, why_loud = None, ""
if len(loud) >= 2:
gap = (voices[loud[0]].db or 0.0) - (voices[loud[1]].db or 0.0)
if gap >= LOUD_MIN_DB:
by_loud, why_loud = loud[0], f"volume (+{gap:.1f} dB)"
if by_mouth is not None and by_loud is not None and by_mouth != by_loud:
return None, f"{why_mouth} e {why_loud} apontam vozes diferentes"
if by_mouth is not None:
return by_mouth, why_mouth + (f" e {why_loud}" if by_loud is not None else "")
if by_loud is not None:
return by_loud, why_loud
return None, "sem prova de qual voz é o streamer (boca e volume empatados)"
@dataclass
class SpeakerModel:
voices: list[Voice]
streamer: int | None
reason: str
chunks: list[VoiceChunk] # todos os trechos da sessão, em ordem, já com `label`
@property
def active(self) -> bool:
return self.streamer is not None and len(self.voices) >= 2
def assign(self, vec: Any, length: float) -> str:
if not self.active or vec is None:
return STREAMER
sims = [float(v.centroid @ vec) for v in self.voices]
s_streamer = sims[self.streamer] # type: ignore[index]
best = max(range(len(sims)), key=lambda i: sims[i])
extra = SHORT_EXTRA if length < CLUSTER_MIN_S else 0.0 # trecho curto: prova mais forte
if (best != self.streamer and sims[best] >= OTHER_MIN_SIM + extra
and sims[best] - s_streamer >= OTHER_MARGIN + extra):
return self.voices[best].label
return STREAMER
def to_json(self) -> dict:
counts: dict[str, float] = {}
for c in self.chunks:
counts[c.label or STREAMER] = counts.get(c.label or STREAMER, 0.0) + c.length
return {"active": self.active, "reason": self.reason,
"streamer": None if self.streamer is None else self.voices[self.streamer].label,
"voices": [v.to_json() for v in self.voices],
"chunks": len(self.chunks), "speechByLabel": {k: round(v, 1) for k, v in counts.items()}}
def build_model(chunks: list[VoiceChunk], mouth_of: Callable[[float, float], float | None] | None = None) -> SpeakerModel:
"""Vozes da sessão, qual é o streamer e o rótulo de cada trecho."""
import numpy as np
chunks = sorted(chunks, key=lambda c: c.start)
strong = [c for c in chunks if c.vec is not None and c.length >= CLUSTER_MIN_S]
if len(strong) > CLUSTER_CAP: # amostra espalhada (os mais longos de cada faixa de tempo)
step = len(strong) / CLUSTER_CAP
strong = [max(strong[int(k * step): max(int(k * step) + 1, int((k + 1) * step))], key=lambda c: c.length)
for k in range(CLUSTER_CAP)]
groups = cluster(np.array([c.vec for c in strong])) if strong else []
voices: list[Voice] = []
for g in sorted(groups, key=lambda g: -sum(strong[i].length for i in g)):
speech = sum(strong[i].length for i in g)
if speech < VOICE_MIN_S:
continue
cent = np.mean([strong[i].vec for i in g], axis=0)
dbs = sorted(strong[i].db for i in g if strong[i].db is not None)
mouth = []
if mouth_of is not None:
for i in g:
m = mouth_of(strong[i].start, strong[i].end)
if m is not None:
mouth.append(m)
voices.append(Voice("", cent / np.linalg.norm(cent), speech, dbs[len(dbs) // 2] if dbs else None, mouth))
streamer, reason = pick_streamer(voices)
k = 0
for i, v in enumerate(voices):
if i == streamer:
v.label = STREAMER
else:
k += 1
v.label = f"other{k}"
model = SpeakerModel(voices, streamer, reason, chunks)
for c in chunks:
c.label = model.assign(c.vec, c.length) if c.vec is not None else ""
return model
def label_words(words: list[Word], chunks: list[VoiceChunk]) -> list[Word]:
"""Rótulo de cada palavra pelo trecho que cobre o meio dela; trecho sem impressão (curto) herda o trecho
rotulado mais próximo (≤ `NEIGHBOR_S`); nada perto → streamer. Palavra com `speaker` já preenchido fica."""
labeled = [c for c in sorted(chunks, key=lambda c: c.start) if c.label]
if not any(is_other(c.label) for c in labeled):
return words # ninguém além do streamer: palavras como vieram (vazio = streamer)
starts = [c.start for c in labeled]
out = []
for w in words:
if w.speaker:
out.append(w)
continue
mid = (w.start + w.end) / 2
k = bisect.bisect_right(starts, mid) - 1
best, dist = None, NEIGHBOR_S
for j in (k, k + 1):
if 0 <= j < len(labeled):
c = labeled[j]
d = 0.0 if c.start <= mid <= c.end else min(abs(mid - c.start), abs(mid - c.end))
if d <= dist:
best, dist = c, d
if d == 0.0:
break
out.append(replace(w, speaker=best.label if best else STREAMER))
return out
def transfer(new_words: list[Word], labeled: list[Word]) -> list[Word]:
"""Falante de palavras novas (re-transcrição de um trecho) pelo das palavras antigas no mesmo tempo."""
marks = sorted((w for w in labeled if w.speaker), key=lambda w: w.start)
if not marks:
return new_words
starts = [w.start for w in marks]
out = []
for w in new_words:
mid = (w.start + w.end) / 2
k = bisect.bisect_right(starts, mid) - 1
near = [marks[j] for j in (k, k + 1) if 0 <= j < len(marks)]
best = min(near, key=lambda m: 0.0 if m.start <= mid <= m.end else min(abs(mid - m.start), abs(mid - m.end)))
out.append(w if w.speaker else replace(w, speaker=best.speaker))
return out
def mouth_activity(series: list[float | None], fps: float, block_start: float, a: float, b: float) -> list[float]:
"""Valores da série da boca (quadro i = `block_start` + i/fps) dentro de [a, b]."""
lo = max(0, int(math.ceil((a - block_start) * fps)))
hi = min(len(series), int(math.floor((b - block_start) * fps)) + 1)
return [v for v in series[lo:hi] if v is not None]
# ---------------------------------------------------------------------------------------------------------------
# Serviço (E/S: banco, modelo de voz)
# A tabela `voice_chunks` é criada pela migração v15 (db.py).
class SpeakerService:
"""Uma instância por motor (`Engine.speakers`)."""
def __init__(self, engine: Engine, embedder_factory: Callable[[], Any] | None = None):
self.e = engine
self._embedder_factory = embedder_factory or self._default_embedder
self._embedder: Any = None
self._embedder_retry_at = 0.0 # modelo de voz falhou (download/onnx): nova tentativa só depois disto
self._lock = threading.Lock()
self._cache: dict[int, tuple[tuple, SpeakerModel]] = {}
self.last_error: str | None = None
@property
def enabled(self) -> bool:
return bool(self.e.intel.opts.get("speakers", True))
def _default_embedder(self) -> Any:
from .voiceprint import Voiceprint
return Voiceprint(self.e.face.store.path(MODEL_ID))
def embedder(self) -> Any:
"""Modelo de voz (carregado no 1º bloco). Falhou → sobe o erro (a análise registra e segue) e só tenta de novo
daqui a `EMBEDDER_RETRY_S`: sem rede, não baixa 26 MB a cada bloco."""
with self._lock:
if self._embedder is None:
if time.monotonic() < self._embedder_retry_at:
raise RuntimeError(f"modelo de voz indisponível (nova tentativa em até {EMBEDDER_RETRY_S} s)")
try:
self._embedder = self._embedder_factory()
except Exception:
self._embedder_retry_at = time.monotonic() + EMBEDDER_RETRY_S
raise
return self._embedder
# ---------- por bloco (thread da análise)
def index_block(self, segment: dict, pcm: bytes, words: list[Word]) -> int:
"""Impressões de voz dos trechos de fala do bloco → `voice_chunks`. Devolve quantos trechos gravou."""
if not self.enabled:
return 0
import numpy as np
samples = np.frombuffer(pcm[: len(pcm) - len(pcm) % 2], np.int16)
base = float(segment["start_s"])
sr = 16_000
items = []
embedder = self.embedder() if words else None
for a, b in speech_chunks(words):
item: dict = {"s": round(a, 3), "e": round(b, 3)}
lo, hi = max(0, int((a - base - EMBED_PAD_S) * sr)), min(len(samples), int((b - base + EMBED_PAD_S) * sr))
part = samples[lo:hi]
if len(part) >= sr * 0.1:
rms = float(np.sqrt(np.mean(part.astype(np.float64) ** 2)))
item["db"] = round(20 * math.log10(rms / 32768), 1) if rms > 0 else None
if b - a >= EMBED_MIN_S and embedder is not None:
vec = embedder.embed(part)
if vec is not None:
item["v"] = encode_vec(vec)
items.append(item)
data = {"model": MODEL_ID, "chunks": items}
self.e.db.run("INSERT INTO voice_chunks (session_id, idx, data_json, updated_at) VALUES (?, ?, ?, ?)"
" ON CONFLICT (session_id, idx) DO UPDATE SET data_json = excluded.data_json,"
" updated_at = excluded.updated_at",
segment["session_id"], segment["idx"], json.dumps(data), now())
self.invalidate(segment["session_id"])
return len(items)
# ---------- sessão
def invalidate(self, session_id: int) -> None:
with self._lock:
self._cache.pop(session_id, None)
def _key(self, session_id: int) -> tuple:
row = self.e.db.get("SELECT COUNT(*) AS n, MAX(updated_at) AS u FROM voice_chunks WHERE session_id = ?", session_id)
face = self.e.db.get("SELECT COUNT(*) AS n, MAX(updated_at) AS u FROM face_track WHERE session_id = ?", session_id)
return (row["n"], row["u"], face["n"], face["u"])
def model(self, session_id: int) -> SpeakerModel | None:
"""Vozes da sessão (em cache até chegar bloco novo de voz ou de rosto). None = nada indexado."""
key = self._key(session_id)
if key[0] == 0:
return None
with self._lock:
hit = self._cache.get(session_id)
if hit and hit[0] == key:
return hit[1]
model = self._build(session_id)
with self._lock:
self._cache[session_id] = (key, model)
return model
def _build(self, session_id: int) -> SpeakerModel:
chunks = []
for row in self.e.db.all("SELECT data_json FROM voice_chunks WHERE session_id = ? ORDER BY idx", session_id):
for item in loads(row["data_json"], {}).get("chunks", []):
vec = decode_vec(item["v"]) if item.get("v") else None
chunks.append(VoiceChunk(float(item["s"]), float(item["e"]), item.get("db"), vec))
blocks = []
for row in self.e.db.all(
"SELECT s.start_s, f.data_json FROM face_track f JOIN segments s ON s.session_id = f.session_id"
" AND s.idx = f.idx WHERE f.session_id = ? AND f.status = 'done' ORDER BY s.start_s", session_id):
data = loads(row["data_json"], {})
if data.get("mouth"):
blocks.append((float(row["start_s"]), float(data.get("fps") or 6), data["mouth"]))
starts = [b[0] for b in blocks]
def mouth_of(a: float, b: float) -> float | None:
k = bisect.bisect_right(starts, a) - 1
values: list[float] = []
for j in (k, k + 1):
if 0 <= j < len(blocks):
values += mouth_activity(blocks[j][2], blocks[j][1], blocks[j][0], a, b)
return sum(values) / len(values) if len(values) >= MOUTH_MIN_FRAMES else None
model = build_model(chunks, mouth_of if blocks else None)
log.info("sessão %s: %d vozes, streamer = %s (%s)", session_id, len(model.voices),
model.voices[model.streamer].label if model.streamer is not None and model.voices else "—", model.reason)
return model
def label(self, session_id: int, words: list[Word]) -> list[Word]:
"""Palavras com falante. Sem sessão indexada, sem certeza ou desligado → como vieram (contam como streamer)."""
if not words or not self.enabled:
return words
try:
model = self.model(session_id)
except Exception as exc: # noqa: BLE001 - atribuição nunca derruba a leitura da linha do tempo
self.last_error = str(exc)[:300]
log.warning("falantes da sessão %s: %s", session_id, exc)
return words
if model is None or not model.active:
return words
return label_words(words, model.chunks)
def view(self, session_id: int) -> dict:
"""Estado para a API: vozes, qual é o streamer e por quê."""
model = self.model(session_id) if self.enabled else None
return {"enabled": self.enabled, "lastError": self.last_error,
**(model.to_json() if model else {"active": False, "reason": "nada indexado ainda", "voices": []})}
+106 -29
View File
@@ -15,12 +15,23 @@ ativos ao mesmo tempo. Agora (usado pelo render do worker e pelo do editor):
para o bloco não piscar; para o bloco não piscar;
- `caption_blocks`: o fim de cada bloco é cortado no início do seguinte — nunca dois blocos na tela. O início do - `caption_blocks`: o fim de cada bloco é cortado no início do seguinte — nunca dois blocos na tela. O início do
bloco é sempre o início da 1ª palavra (a legenda não atrasa em relação ao áudio). bloco é sempre o início da 1ª palavra (a legenda não atrasa em relação ao áudio).
Dois falantes (pedido do dono, 18/11/2026: "a legenda do streamer em cima e a de outra pessoa abaixo, com outra cor,
como se fossem duas pessoas conversando"; doc/clipador/FALANTES.md): cada palavra tem `speaker` e a legenda tem duas
FAIXAS — a do streamer (posição normal) e a de outra pessoa (logo abaixo, `caption.otherColor`/`otherSize`). Um bloco
nunca mistura falantes; o "nunca dois blocos na tela" vale DENTRO de cada faixa, então quando os dois falam ao mesmo
tempo aparecem as duas linhas, cada uma no seu lugar (posição fixa por `pos`: o libass não empilha).
""" """
from __future__ import annotations from __future__ import annotations
from . import layout from . import layout
from .scoring import Word from .scoring import Word
from .speakers import STREAMER, is_other
STREAMER_LANE, OTHER_LANE = "streamer", "other"
OTHER_SIZE_RATIO = 0.85 # tamanho automático da fala de outra pessoa (fração do tamanho da legenda)
LINE_GAP_PX = 10 # vão entre a linha do streamer e a de outra pessoa
WIDTH, HEIGHT = layout.W, layout.H # quadro do vertical (compatibilidade); o formato real vem da configuração WIDTH, HEIGHT = layout.W, layout.H # quadro do vertical (compatibilidade); o formato real vem da configuração
MAX_WORDS, MAX_CHARS, MAX_GAP_S = 3, 18, 0.6 MAX_WORDS, MAX_CHARS, MAX_GAP_S = 3, 18, 0.6
@@ -58,20 +69,34 @@ def clean_words(words: list[Word]) -> list[Word]:
end = max(w.end, round(start + MIN_WORD_S, 3)) end = max(w.end, round(start + MIN_WORD_S, 3))
if out and out[-1].end > start + 1e-9: if out and out[-1].end > start + 1e-9:
prev = out[-1] prev = out[-1]
out[-1] = Word(prev.start, start, prev.word) out[-1] = Word(prev.start, start, prev.word, prev.speaker)
text = w.word.strip() text = w.word.strip()
same = abs(start - w.start) < 1e-9 and abs(end - w.end) < 1e-9 and text == w.word same = abs(start - w.start) < 1e-9 and abs(end - w.end) < 1e-9 and text == w.word
out.append(w if same else Word(start, end, text)) out.append(w if same else Word(start, end, text, w.speaker))
return out return out
def lane(speaker: str | None) -> str:
"""Faixa da legenda: `streamer` (vazio também) ou `other` (qualquer outra pessoa)."""
return OTHER_LANE if is_other(speaker) else STREAMER_LANE
def same_speaker(a: Word, b: Word) -> bool:
return (a.speaker or STREAMER) == (b.speaker or STREAMER)
def has_other(words: list[Word]) -> bool:
return any(is_other(w.speaker) for w in words)
def group_words(words: list[Word], max_words: int = MAX_WORDS) -> list[list[Word]]: def group_words(words: list[Word], max_words: int = MAX_WORDS) -> list[list[Word]]:
"""Blocos da legenda (palavras já saneadas por `clean_words`).""" """Blocos da legenda (palavras já saneadas por `clean_words`)."""
max_chars = MAX_CHARS + 6 * max(0, max_words - MAX_WORDS) max_chars = MAX_CHARS + 6 * max(0, max_words - MAX_WORDS)
groups: list[list[Word]] = [] groups: list[list[Word]] = []
for word in clean_words(words): for word in clean_words(words):
current = groups[-1] if groups else None current = groups[-1] if groups else None
if current and word.start - current[-1].end <= MAX_GAP_S and word.end - current[0].start <= MAX_BLOCK_S: if (current and same_speaker(current[-1], word) and word.start - current[-1].end <= MAX_GAP_S
and word.end - current[0].start <= MAX_BLOCK_S):
fits = len(" ".join(w.word for w in current + [word])) <= max_chars fits = len(" ".join(w.word for w in current + [word])) <= max_chars
room = len(current) < max_words or ( room = len(current) < max_words or (
# Fala rápida: o bloco cheio passaria voando; uma palavra a mais (se couber) dá tempo de ler. # Fala rápida: o bloco cheio passaria voando; uma palavra a mais (se couber) dá tempo de ler.
@@ -84,36 +109,74 @@ def group_words(words: list[Word], max_words: int = MAX_WORDS) -> list[list[Word
def caption_blocks(words: list[Word], max_words: int = MAX_WORDS) -> list[tuple[list[Word], float]]: def caption_blocks(words: list[Word], max_words: int = MAX_WORDS) -> list[tuple[list[Word], float]]:
"""(palavras do bloco, fim do bloco). O fim nunca passa do início do bloco seguinte: dois eventos de legenda """(palavras do bloco, fim do bloco), em ordem de início. Cada faixa (streamer / outra pessoa; ver `lane`) é
ativos ao mesmo tempo seriam empilhados pelo libass (um em cima do outro).""" agrupada sozinha e um bloco nunca mistura falantes. O fim nunca passa do início do bloco seguinte DA MESMA FAIXA:
groups = group_words(words, max_words) dois eventos no mesmo lugar ao mesmo tempo ficariam um em cima do outro. Blocos de faixas diferentes podem se
sobrepor (os dois falando juntos): cada um vai para a sua linha."""
out = [] out = []
for k, group in enumerate(groups): for name in (STREAMER_LANE, OTHER_LANE):
end = max(group[-1].end, group[-1].start + MIN_HOLD_S) groups = group_words([w for w in words if lane(w.speaker) == name], max_words)
if k + 1 < len(groups): for k, group in enumerate(groups):
end = min(end, groups[k + 1][0].start) end = max(group[-1].end, group[-1].start + MIN_HOLD_S)
out.append((group, round(end, 3))) if k + 1 < len(groups):
end = min(end, groups[k + 1][0].start)
out.append((group, round(end, 3)))
out.sort(key=lambda item: (item[0][0].start, lane(item[0][0].speaker)))
return out return out
def other_size(cap: dict) -> int:
"""Tamanho da fala de outra pessoa: `caption.otherSize` ou, vazio, 85 % do tamanho da legenda."""
chosen = cap.get("otherSize")
return int(chosen) if chosen else max(30, int(round(int(cap["size"]) * OTHER_SIZE_RATIO)))
def other_color(cap: dict) -> str:
return str(cap.get("otherColor") or layout.DEFAULTS["caption"]["otherColor"])
def other_offset(size: int, osize: int, extra: int = 0) -> int:
"""Distância (px) do centro da linha do streamer ao centro da linha de outra pessoa (logo abaixo). `extra` =
espaço a mais entre as duas (a tradução de desenvolvimento do streamer fica nele)."""
return int(round(0.6 * size + 0.6 * osize)) + LINE_GAP_PX + extra
def other_y(y: int, offset: int, osize: int, canvas_h: int) -> int:
"""Centro da linha de outra pessoa: abaixo da do streamer; sem espaço até a borda, acima dela."""
below = y + offset
return below if below + int(0.6 * osize) <= canvas_h - 8 else max(int(0.6 * osize), y - offset)
PHRASE_GAP_S, PHRASE_MAX_S, PHRASE_MAX_WORDS = 0.7, 6.0, 16 PHRASE_GAP_S, PHRASE_MAX_S, PHRASE_MAX_WORDS = 0.7, 6.0, 16
_SENTENCE_END = (".", "?", "!") _SENTENCE_END = (".", "?", "!")
def phrases(words: list[Word]) -> list[tuple[float, float, str]]: def phrases(words: list[Word], with_speaker: bool = False) -> list[tuple]:
"""Fala em frases curtas com tempo (início, fim, texto) para traduzir: quebra em pausa > 0,7 s, fim de frase """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.""" (. ? !) 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]] = [] Uma frase nunca mistura falantes (quem fala junto vira frase própria). `with_speaker` = devolve
current: list[Word] = [] (início, fim, texto, falante), com falante "streamer" ou "otherN"."""
for w in clean_words(words): out: list[tuple] = []
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 def flush(current: list[Word]) -> None:
or (current[-1].word.endswith(_SENTENCE_END) and len(current) >= 4)): item = (current[0].start, current[-1].end, " ".join(x.word for x in current))
out.append((current[0].start, current[-1].end, " ".join(x.word for x in current))) out.append(item + (current[0].speaker or STREAMER,) if with_speaker else item)
current = []
current.append(w) by_speaker: dict[str, list[Word]] = {}
if current: for w in words:
out.append((current[0].start, current[-1].end, " ".join(x.word for x in current))) by_speaker.setdefault(w.speaker or STREAMER, []).append(w)
for speaker_words in by_speaker.values():
current: list[Word] = []
for w in clean_words(speaker_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)):
flush(current)
current = []
current.append(w)
if current:
flush(current)
out.sort(key=lambda item: item[0])
return out return out
@@ -123,13 +186,19 @@ def build_ass(words: list[Word], clip_start: float, clip_end: float, credit: str
cap, cred = cfg["caption"], cfg["credit"] cap, cred = cfg["caption"], cfg["credit"]
duration = clip_end - clip_start duration = clip_end - clip_start
inside = [ inside = [
Word(max(0.0, w.start - clip_start), min(duration, w.end - clip_start), w.word.strip()) Word(max(0.0, w.start - clip_start), min(duration, w.end - clip_start), w.word.strip(), w.speaker)
for w in words for w in words
if w.end > clip_start and w.start < clip_end if w.end > clip_start and w.start < clip_end
] ]
base, high, outline = layout.ass_color(cap["color"]), layout.ass_color(cap["highlight"]), layout.ass_color(cap["outline"]) base, high, outline = layout.ass_color(cap["color"]), layout.ass_color(cap["highlight"]), layout.ass_color(cap["outline"])
credit_align, credit_side, credit_margin = layout.credit_placement(cfg) credit_align, credit_side, credit_margin = layout.credit_placement(cfg)
width, height = layout.canvas_size(cfg) width, height = layout.canvas_size(cfg)
two = cap["enabled"] and has_other(inside)
osize = other_size(cap)
# Estilo da fala de outra pessoa só quando há outra pessoa: o ASS de um corte só com o streamer fica igual.
other_style = (f"Style: CaptionOther,{cap['font']},{osize},{layout.ass_color(other_color(cap))},"
f"{layout.ass_color(other_color(cap))},{outline},&H80000000,-1,0,0,0,100,100,0,0,1,"
f"{max(2, int(cap['outlineWidth']) * osize // int(cap['size']))},3,5,60,60,0,1\n") if two else ""
header = f"""[Script Info] header = f"""[Script Info]
ScriptType: v4.00+ ScriptType: v4.00+
PlayResX: {width} PlayResX: {width}
@@ -140,7 +209,7 @@ ScaledBorderAndShadow: yes
[V4+ Styles] [V4+ Styles]
Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding
Style: Caption,{cap['font']},{cap['size']},{base},{base},{outline},&H80000000,-1,0,0,0,100,100,0,0,1,{cap['outlineWidth']},3,5,60,60,0,1 Style: Caption,{cap['font']},{cap['size']},{base},{base},{outline},&H80000000,-1,0,0,0,100,100,0,0,1,{cap['outlineWidth']},3,5,60,60,0,1
Style: Credit,Arial,{cred['size']},&H00FFFFFF,&H00FFFFFF,&H00000000,&H80000000,-1,0,0,0,100,100,0,0,1,3,1,{credit_align},{credit_side},{credit_side},{credit_margin},1 {other_style}Style: Credit,Arial,{cred['size']},&H00FFFFFF,&H00FFFFFF,&H00000000,&H80000000,-1,0,0,0,100,100,0,0,1,3,1,{credit_align},{credit_side},{credit_side},{credit_margin},1
[Events] [Events]
Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text
@@ -149,9 +218,17 @@ Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text
if credit and cred["enabled"]: if credit and cred["enabled"]:
lines.append(f"Dialogue: 1,{_ts(0)},{_ts(duration)},Credit,,0,0,0,,{_escape(credit)}") lines.append(f"Dialogue: 1,{_ts(0)},{_ts(duration)},Credit,,0,0,0,,{_escape(credit)}")
if cap["enabled"]: if cap["enabled"]:
pos = f"{{\\pos({width // 2},{layout.caption_y(cfg)})}}" y = layout.caption_y(cfg)
high, base = layout.ass_inline_color(cap["highlight"]), layout.ass_inline_color(cap["color"]) offset = other_offset(int(cap["size"]), osize)
if two: # sem espaço embaixo para a outra pessoa, a linha do streamer sobe (a ordem nunca inverte)
y = min(y, height - 8 - offset - int(0.6 * osize))
oy = other_y(y, offset, osize, height)
high = layout.ass_inline_color(cap["highlight"])
for group, g_end in caption_blocks(inside, cap["maxWords"]): for group, g_end in caption_blocks(inside, cap["maxWords"]):
other = lane(group[0].speaker) == OTHER_LANE
pos = f"{{\\pos({width // 2},{oy if other else y})}}"
style = "CaptionOther" if other else "Caption"
base = layout.ass_inline_color(other_color(cap) if other else cap["color"])
for i, word in enumerate(group): for i, word in enumerate(group):
# Cada palavra tem seu tempo na tela; o bloco inteiro aparece com a palavra atual destacada. # Cada palavra tem seu tempo na tela; o bloco inteiro aparece com a palavra atual destacada.
start = word.start start = word.start
@@ -163,5 +240,5 @@ Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text
for j, w in enumerate(group): for j, w in enumerate(group):
text = _escape(w.word.upper() if cap["uppercase"] else w.word) text = _escape(w.word.upper() if cap["uppercase"] else w.word)
parts.append(f"{{\\c{high}}}{text}{{\\c{base}}}" if j == i else text) parts.append(f"{{\\c{high}}}{text}{{\\c{base}}}" if j == i else text)
lines.append(f"Dialogue: 0,{_ts(start)},{_ts(end)},Caption,,0,0,0,,{pos}{' '.join(parts)}") lines.append(f"Dialogue: 0,{_ts(start)},{_ts(end)},{style},,0,0,0,,{pos}{' '.join(parts)}")
return header + "\n".join(lines) + "\n" return header + "\n".join(lines) + "\n"
+100
View File
@@ -0,0 +1,100 @@
"""Impressão de voz (embedding de falante) para o Clipador: fbank no estilo Kaldi em numpy + WeSpeaker ResNet34-LM
(ONNX, CC-BY-4.0) no onnxruntime. Só E/S de modelo e conta numérica; a decisão de quem fala mora em `speakers.py`.
- Modelo: `voxceleb_resnet34_LM.onnx` do repositório Wespeaker/wespeaker-voxceleb-resnet34-LM (Hugging Face, commit
fixo no `models.lock.json`, licença CC-BY-4.0 — uso comercial permitido com atribuição; ver doc/clipador/FALANTES.md).
- Entrada do modelo: fbank 80 bandas, janela 25 ms / passo 10 ms, 16 kHz, com a média de cada trecho subtraída (CMN),
igual ao `compute_fbank` do WeSpeaker. Saída: vetor de 256, normalizado aqui (comparação por cosseno).
Nada daqui importa numpy/onnxruntime na carga do módulo: o serviço sobe (e os testes rodam) sem eles.
"""
from __future__ import annotations
import math
import threading
from pathlib import Path
from typing import Any
SAMPLE_RATE = 16_000
FRAME_LEN, FRAME_SHIFT, N_FFT, N_MELS = 400, 160, 512, 80
PREEMPH = 0.97
MIN_SAMPLES = FRAME_LEN + FRAME_SHIFT * 20 # ~0,2 s: menos que isso não vira vetor
class VoiceprintUnavailable(RuntimeError):
"""numpy/onnxruntime ou o modelo faltando: a atribuição de falante fica de fora (tudo `streamer`)."""
_mel_cache: dict[int, Any] = {}
def _mel_banks(np: Any) -> Any:
"""Banco de filtros triangulares na escala mel do Kaldi (20 Hz até Nyquist), 80 × 257."""
if N_MELS in _mel_cache:
return _mel_cache[N_MELS]
def mel(f: Any) -> Any:
return 1127.0 * np.log(1.0 + f / 700.0)
lo, hi = mel(np.float64(20.0)), mel(np.float64(SAMPLE_RATE / 2))
centers = np.linspace(lo, hi, N_MELS + 2)
bins = mel(np.arange(N_FFT // 2 + 1) * SAMPLE_RATE / N_FFT)
banks = np.zeros((N_MELS, N_FFT // 2 + 1), np.float32)
for m in range(N_MELS):
left, center, right = centers[m], centers[m + 1], centers[m + 2]
up = (bins - left) / (center - left)
down = (right - bins) / (right - center)
banks[m] = np.maximum(0.0, np.minimum(up, down))
_mel_cache[N_MELS] = banks
return banks
def fbank(samples: Any) -> Any:
"""Fbank Kaldi (snip_edges, janela povey, pré-ênfase 0,97, sem dither) de amostras int16/float na escala int16.
Devolve (quadros × 80) float32 já com a média subtraída (CMN), como o WeSpeaker espera."""
import numpy as np
x = np.asarray(samples, dtype=np.float64)
n = 1 + (len(x) - FRAME_LEN) // FRAME_SHIFT
if n < 1:
return np.zeros((0, N_MELS), np.float32)
idx = np.arange(FRAME_LEN)[None, :] + FRAME_SHIFT * np.arange(n)[:, None]
frames = x[idx]
frames = frames - frames.mean(axis=1, keepdims=True) # tira o nível DC
frames = np.concatenate([frames[:, :1] * (1 - PREEMPH), frames[:, 1:] - PREEMPH * frames[:, :-1]], axis=1)
window = (0.5 - 0.5 * np.cos(2 * math.pi * np.arange(FRAME_LEN) / (FRAME_LEN - 1))) ** 0.85 # povey
spec = np.abs(np.fft.rfft(frames * window, N_FFT)) ** 2
feats = np.log(np.maximum(spec @ _mel_banks(np).T.astype(np.float64), np.finfo(np.float32).eps))
feats = feats - feats.mean(axis=0, keepdims=True)
return feats.astype(np.float32)
class Voiceprint:
"""Sessão ONNX do WeSpeaker. Um por motor; `embed` é seguro entre threads (trinco)."""
def __init__(self, model_path: Path, threads: int = 2):
try:
import numpy as np
import onnxruntime as ort
except ImportError as exc: # pragma: no cover - depende da instalação
raise VoiceprintUnavailable("numpy/onnxruntime não instalados (rode o setup.bat)") from exc
if not Path(model_path).is_file():
raise VoiceprintUnavailable(f"modelo de voz ausente: {model_path}")
opts = ort.SessionOptions()
opts.intra_op_num_threads, opts.inter_op_num_threads = threads, 1
self._np = np
self._sess = ort.InferenceSession(str(model_path), sess_options=opts, providers=["CPUExecutionProvider"])
self._input = self._sess.get_inputs()[0].name
self._lock = threading.Lock()
def embed(self, samples: Any) -> list[float] | None:
"""Vetor de 256 (norma 1) de um trecho de fala; None se curto demais."""
np = self._np
if len(samples) < MIN_SAMPLES:
return None
feats = fbank(samples)
with self._lock:
out = self._sess.run(None, {self._input: feats[None]})[0][0]
norm = float(np.linalg.norm(out))
return (out / norm).astype(np.float32).tolist() if norm > 0 else None
+119 -10
View File
@@ -40,6 +40,7 @@ from .intel import Intel
from .judge import Judge, JudgeError, analysis_block, build_prompt from .judge import Judge, JudgeError, analysis_block, build_prompt
from .scoring import ChatMessage, Params, Word, find_moments, overlaps from .scoring import ChatMessage, Params, Word, find_moments, overlaps
from .sources import Source, parse_source from .sources import Source, parse_source
from .speakers import SpeakerService, dump_words, parse_words
from .subtitles import build_ass, phrases from .subtitles import build_ass, phrases
log = logging.getLogger("cenaforge_clipper") log = logging.getLogger("cenaforge_clipper")
@@ -353,6 +354,7 @@ class Engine:
self._threads: list[threading.Thread] = [] self._threads: list[threading.Thread] = []
self.intel = Intel(self) self.intel = Intel(self)
self.face = FaceService(self) # rastreio do rosto do streamer (face.py); não carrega modelo aqui self.face = FaceService(self) # rastreio do rosto do streamer (face.py); não carrega modelo aqui
self.speakers = SpeakerService(self) # quem fala cada palavra (speakers.py); modelo de voz só no 1º bloco
self.resume_delays: tuple[float, ...] = RESUME_DELAYS_S # os testes encurtam self.resume_delays: tuple[float, ...] = RESUME_DELAYS_S # os testes encurtam
self._recovering: set[int] = set() # sessões com uma thread de retomada em andamento self._recovering: set[int] = set() # sessões com uma thread de retomada em andamento
self._rendering: set[int] = set() # cortes que ESTE processo está renderizando agora self._rendering: set[int] = set() # cortes que ESTE processo está renderizando agora
@@ -754,12 +756,18 @@ class Engine:
for w in rel_words] for w in rel_words]
except Exception as exc: # noqa: BLE001 - sem voz o corte segue pelo chat except Exception as exc: # noqa: BLE001 - sem voz o corte segue pelo chat
error = str(exc)[:300] error = str(exc)[:300]
if words:
try:
# Impressão de voz de cada trecho de fala (doc/clipador/FALANTES.md): ~0,2 s de CPU por bloco.
self.speakers.index_block(segment, pcm, words)
except Exception as exc: # noqa: BLE001 - sem falantes a legenda segue toda como do streamer
self.speakers.last_error = str(exc)[:300]
log.warning("falantes do bloco %s/%s: %s", segment["session_id"], segment["idx"], exc)
except media.MediaError as exc: except media.MediaError as exc:
error = f"áudio: {exc}"[:300] error = f"áudio: {exc}"[:300]
self.db.run( self.db.run(
"UPDATE segments SET analyzed = 1, loudness_json = ?, words_json = ?, transcript_error = ? WHERE session_id = ? AND idx = ?", "UPDATE segments SET analyzed = 1, loudness_json = ?, words_json = ?, transcript_error = ? WHERE session_id = ? AND idx = ?",
json.dumps(loudness), json.dumps([[w.start, w.end, w.word] for w in words], ensure_ascii=False), error, json.dumps(loudness), dump_words(words), error, segment["session_id"], segment["idx"])
segment["session_id"], segment["idx"])
# ---------- linha do tempo de uma sessão # ---------- linha do tempo de uma sessão
def load_timeline(self, session_id: int, since_s: float = 0.0) -> dict: def load_timeline(self, session_id: int, since_s: float = 0.0) -> dict:
@@ -775,7 +783,7 @@ class Engine:
if seg["analyzed"]: if seg["analyzed"]:
if analyzed_until >= seg["start_s"] - 0.01: # só o trecho contínuo desde o início conta if analyzed_until >= seg["start_s"] - 0.01: # só o trecho contínuo desde o início conta
analyzed_until = seg["end_s"] analyzed_until = seg["end_s"]
words.extend(Word(a, b, c) for a, b, c in loads(seg["words_json"], [])) words.extend(parse_words(seg["words_json"]))
chat = [] chat = []
if segments: if segments:
first_wall = segments[0]["wall_end"] - (segments[0]["end_s"] - segments[0]["start_s"]) first_wall = segments[0]["wall_end"] - (segments[0]["end_s"] - segments[0]["start_s"])
@@ -789,9 +797,17 @@ class Engine:
continue continue
emotes = tuple(loads(r["emotes"], [])) emotes = tuple(loads(r["emotes"], []))
chat.append(ChatMessage(t, r["text"], r["user"], emotes, self.intel.bonus(list(emotes), key))) chat.append(ChatMessage(t, r["text"], r["user"], emotes, self.intel.bonus(list(emotes), key)))
# Quem fala cada palavra (streamer × outra pessoa): juízes, tradução e legenda leem daqui.
words = self.speakers.label(session_id, words)
return {"segments": segments, "duration": duration, "loudness": loudness, "words": words, "chat": chat, return {"segments": segments, "duration": duration, "loudness": loudness, "words": words, "chat": chat,
"analyzedUntil": analyzed_until} "analyzedUntil": analyzed_until}
def words_between(self, session_id: int, lo: float, hi: float) -> list[Word]:
"""Palavras dos blocos que tocam [lo, hi] (sem filtrar o tempo de cada palavra), já com o falante."""
rows = self.db.all("SELECT words_json FROM segments WHERE session_id = ? AND end_s > ? AND start_s < ? ORDER BY idx",
session_id, lo, hi)
return self.speakers.label(session_id, [w for r in rows for w in parse_words(r["words_json"])])
# ---------- cortes # ---------- cortes
def _clip_loop(self) -> None: def _clip_loop(self) -> None:
while not self.stop_event.is_set(): while not self.stop_event.is_set():
@@ -816,7 +832,7 @@ class Engine:
return 0 return 0
offset = int(since) offset = int(since)
chat = [replace(m, t=m.t - offset) for m in tl["chat"] if m.t >= offset] chat = [replace(m, t=m.t - offset) for m in tl["chat"] if m.t >= offset]
words = [Word(w.start - offset, w.end - offset, w.word) for w in tl["words"] if w.start >= offset] words = [replace(w, start=w.start - offset, end=w.end - offset) for w in tl["words"] if w.start >= offset]
face, face_until = self.face.for_scoring(session, offset, tl["duration"]) # None = sem câmera/rastreio face, face_until = self.face.for_scoring(session, offset, tl["duration"]) # None = sem câmera/rastreio
# O candidato já nasce na duração da configuração do corte desta sessão (padrão 60–90 s). # O candidato já nasce na duração da configuração do corte desta sessão (padrão 60–90 s).
dur = self.intel.settings_for(session)["duration"] dur = self.intel.settings_for(session)["duration"]
@@ -980,26 +996,35 @@ class Engine:
hi = clip["end_s"] if hi is None else hi hi = clip["end_s"] if hi is None else hi
current = loads(clip.get("translation_json"), None) current = loads(clip.get("translation_json"), None)
if (isinstance(current, dict) and not force and current.get("startS", 1e12) <= lo + 0.5 if (isinstance(current, dict) and not force and current.get("startS", 1e12) <= lo + 0.5
and current.get("endS", -1) >= hi - 0.5): and current.get("endS", -1) >= hi - 0.5
and all("speaker" in line for line in current.get("lines") or [])): # antiga, sem falante: refaz
return current return current
tl = self.load_timeline(session["id"], max(0.0, lo - 30)) 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]) # Frases que nunca misturam falantes (doc/clipador/FALANTES.md); cada linha diz quem fala (`speaker`:
# "streamer" ou "otherN") — a legenda de desenvolvimento e a dublagem escolhem posição e voz por ela.
items = phrases([w for w in tl["words"] if lo - 0.3 <= w.start <= hi], with_speaker=True)
if not items: if not items:
return None return None
try: try:
pt = self.judge.translate_lines([text for _, _, text in items]) pt = self.judge.translate_lines([text for _, _, text, _ in items])
except (JudgeError, json.JSONDecodeError, KeyError, ValueError) as exc: except (JudgeError, json.JSONDecodeError, KeyError, ValueError) as exc:
log.warning("tradução da fala do corte %s falhou: %s", clip_id, exc) log.warning("tradução da fala do corte %s falhou: %s", clip_id, exc)
return None return None
data = {"language": "pt-BR", "startS": round(lo, 2), "endS": round(hi, 2), "model": self.judge.responder(), 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} "lines": [{"s": round(s, 3), "e": round(e, 3), "text": text, "pt": tr, "speaker": speaker}
for (s, e, text), tr in zip(items, pt)]} for (s, e, text, speaker), tr in zip(items, pt)]}
self.db.run("UPDATE clips SET translation_json = ? WHERE id = ?", json.dumps(data, ensure_ascii=False), clip_id) self.db.run("UPDATE clips SET translation_json = ? WHERE id = ?", json.dumps(data, ensure_ascii=False), clip_id)
return data return data
def render_pending(self) -> None: def render_pending(self) -> None:
self.recover_orphan_renders() self.recover_orphan_renders()
self.discard_pending_duplicates() self.discard_pending_duplicates()
# Vídeos finais primeiro: o corte já foi aprovado e a publicação está esperando por ele (REVISAO.md).
for clip in self.db.all("SELECT * FROM clips WHERE final_status = 'pending' AND status IN ('approved', 'published')"
" ORDER BY updated_at, id LIMIT 3"):
if self.stop_event.is_set():
return
self.render_final(clip)
for clip in self.db.all("SELECT * FROM clips WHERE status = 'pending' ORDER BY score DESC, id LIMIT 3"): for clip in self.db.all("SELECT * FROM clips WHERE status = 'pending' ORDER BY score DESC, id LIMIT 3"):
if self.stop_event.is_set(): if self.stop_event.is_set():
return return
@@ -1105,8 +1130,87 @@ class Engine:
self.db.run("UPDATE edits SET cover = ? WHERE clip_id = ?", cover, clip["id"]) self.db.run("UPDATE edits SET cover = ? WHERE clip_id = ?", cover, clip["id"])
self.db.run("UPDATE clips SET status = 'ready', file = ?, thumb = ?, error = NULL, updated_at = ? WHERE id = ?", self.db.run("UPDATE clips SET status = 'ready', file = ?, thumb = ?, error = NULL, updated_at = ? WHERE id = ?",
rel(out), rel(thumb), now(), clip["id"]) rel(out), rel(thumb), now(), clip["id"])
self.drop_final(clip["id"]) # vídeo de revisão novo = conteúdo novo: o final antigo deixa de valer
self._render_attempts.pop(clip["id"], None) self._render_attempts.pop(clip["id"], None)
# ---------- vídeo final (doc/clipador/REVISAO.md)
def queue_final(self, clip_id: int) -> str | None:
"""Corte aprovado: pede o vídeo FINAL (sem camadas de desenvolvimento). Se o vídeo de revisão não teve nenhuma
camada `dev` (`review_dev_json` = []), ele já é o final: reaproveita sem renderizar. Devolve o `final_status`."""
with self.db.lock:
clip = self.db.get("SELECT c.*, e.cover AS edit_cover FROM clips c LEFT JOIN edits e ON e.clip_id = c.id"
" WHERE c.id = ?", clip_id)
if not clip or clip["status"] not in ("approved", "published"):
return None
if loads(clip["review_dev_json"], None) == [] and clip["file"]:
self.db.run("UPDATE clips SET final_status = 'ready', final_file = ?, final_thumb = ?, final_cover = ?,"
" final_error = NULL, final_at = ? WHERE id = ?",
clip["file"], clip["thumb"], clip["edit_cover"], now(), clip_id)
return "ready"
self.db.run("UPDATE clips SET final_status = 'pending', final_file = NULL, final_thumb = NULL, final_cover = NULL,"
" final_error = NULL, final_at = NULL WHERE id = ?", clip_id)
self.wake_clips.set()
return "pending"
def drop_final(self, clip_id: int) -> None:
"""O final deixa de valer (aprovação desfeita, corte editado ou renderizado de novo). O arquivo fica no disco
até o próximo final (mesmo nome) ou até apagar o corte; nada mais aponta para ele."""
self.db.run("UPDATE clips SET final_status = NULL, final_file = NULL, final_thumb = NULL, final_cover = NULL,"
" final_error = NULL, final_at = NULL WHERE id = ?", clip_id)
def render_final(self, clip: dict) -> None:
"""Renderiza o vídeo final de um corte aprovado. Falha vira `final_status = 'error'` (o corte continua
aprovado; "tentar de novo" no painel = POST /v1/clips/{id}/final)."""
with self.lock:
# Apagado depois de a fila ler a lista, ou já em render: não começa (clip_delete recusa enquanto estiver aqui).
if clip["id"] in self._rendering or not self.db.get("SELECT 1 FROM clips WHERE id = ?", clip["id"]):
return
self._rendering.add(clip["id"])
try:
self._render_final(clip)
except Exception as exc: # noqa: BLE001 - nunca fica preso em 'rendering'
log.exception("vídeo final do corte %s falhou", clip["id"])
self._final_error(clip["id"], f"falha inesperada no render final: {type(exc).__name__}: {exc}")
finally:
with self.lock:
self._rendering.discard(clip["id"])
def _render_final(self, clip: dict) -> None:
taken = self.db.run("UPDATE clips SET final_status = 'rendering', final_error = NULL WHERE id = ? AND final_status = 'pending'"
" AND status IN ('approved', 'published')", clip["id"]).rowcount
if not taken:
return
session = self.db.get("SELECT * FROM sessions WHERE id = ?", clip["session_id"])
if not session:
self._final_error(clip["id"], "sessão do corte não existe mais")
return
segments = self.db.all("SELECT deleted FROM segments WHERE session_id = ? AND end_s > ? AND start_s < ?",
clip["session_id"], clip["start_s"], clip["end_s"])
if not segments or any(s["deleted"] for s in segments):
self._final_error(clip["id"], "os blocos gravados deste trecho já foram apagados")
return
out_dir = self.settings.clips_dir / str(clip["session_id"])
out = out_dir / f"clip-{clip['id']}-final.mp4"
thumb = out_dir / f"clip-{clip['id']}-final.jpg"
from . import editor, editor_api # import tardio (ver _render_clip)
t = time.monotonic()
try:
edit = editor_api.ensure_edit(self, clip, session)
cover = editor_api.render_clip_edit(self, clip, session, edit, out, thumb, dev=False)
except (media.MediaError, editor.EditError) as exc:
self._final_error(clip["id"], str(exc))
return
# Só grava se ninguém desfez a aprovação (ou editou) durante o render: aí `final_status` já não é 'rendering'.
done = self.db.run("UPDATE clips SET final_status = 'ready', final_file = ?, final_thumb = ?, final_cover = ?, final_error = NULL,"
" final_at = ? WHERE id = ? AND final_status = 'rendering'",
rel(out), rel(thumb), cover, now(), clip["id"]).rowcount
log.info("vídeo final do corte %s em %.1f s%s", clip["id"], time.monotonic() - t,
"" if done else " (descartado: o corte mudou durante o render)")
def _final_error(self, clip_id: int, message: str) -> None:
self.db.run("UPDATE clips SET final_status = 'error', final_error = ? WHERE id = ? AND final_status IN ('pending', 'rendering')",
message[:500], clip_id)
def _clip_error(self, clip_id: int, message: str) -> None: def _clip_error(self, clip_id: int, message: str) -> None:
self.db.run("UPDATE clips SET status = 'error', error = ?, updated_at = ? WHERE id = ?", message[:500], now(), clip_id) self.db.run("UPDATE clips SET status = 'error', error = ?, updated_at = ? WHERE id = ?", message[:500], now(), clip_id)
@@ -1128,8 +1232,13 @@ class Engine:
return return
limit = time.time() - self.settings.keep_hours * 3600 limit = time.time() - self.settings.keep_hours * 3600
for seg in self.db.all("SELECT * FROM segments WHERE deleted = 0 AND analyzed = 1 AND wall_end < ? LIMIT 200", limit): for seg in self.db.all("SELECT * FROM segments WHERE deleted = 0 AND analyzed = 1 AND wall_end < ? LIMIT 200", limit):
# Também guarda o trecho de quem ainda vai precisar do vídeo final: aprovado com final por fazer ou com erro, e
# pronto para aprovar cujo vídeo de revisão tem camadas de desenvolvimento (ou não se sabe) — REVISAO.md.
needed = self.db.get( needed = self.db.get(
"SELECT 1 FROM clips WHERE session_id = ? AND status IN ('candidate', 'pending', 'rendering') AND start_s < ? AND end_s > ?", "SELECT 1 FROM clips WHERE session_id = ? AND start_s < ? AND end_s > ? AND ("
"status IN ('candidate', 'pending', 'rendering')"
" OR (status IN ('approved', 'published') AND final_status IN ('pending', 'rendering', 'error'))"
" OR (status = 'ready' AND COALESCE(review_dev_json, '') != '[]'))",
seg["session_id"], seg["end_s"], seg["start_s"]) seg["session_id"], seg["end_s"], seg["start_s"])
if needed: if needed:
continue continue
+11 -1
View File
@@ -1,5 +1,5 @@
{ {
"_comment": "Pesos do rastreio de reação do Clipador. Baixados para data/clipper/models/ pelo scripts/setup.ps1 (passo 6b) e conferidos pelo sha256. URLs imutáveis (commit fixo ou caminho versionado). Bancada: doc/FACE_BAKEOFF.md.", "_comment": "Pesos do rastreio de reação e da atribuição de falante do Clipador. Baixados para data/clipper/models/ pelo scripts/setup.ps1 (passo 6b) e conferidos pelo sha256. URLs imutáveis (commit fixo ou caminho versionado). Bancada: doc/FACE_BAKEOFF.md. Falantes: doc/clipador/FALANTES.md.",
"dir": "data/clipper/models", "dir": "data/clipper/models",
"models": [ "models": [
{ {
@@ -41,6 +41,16 @@
"size": 568302, "size": 568302,
"license": "BSD-2-Clause", "license": "BSD-2-Clause",
"source": "github.com/emilianavt/OpenSeeFace@50c09741897010faad721a218b2bbe14ecad6251" "source": "github.com/emilianavt/OpenSeeFace@50c09741897010faad721a218b2bbe14ecad6251"
},
{
"id": "wespeaker_r34",
"file": "wespeaker_voxceleb_resnet34_LM.onnx",
"role": "impressão de voz (falante): fbank 80 → vetor de 256 (WeSpeaker ResNet34-LM, VoxCeleb); quem fala cada palavra",
"url": "https://huggingface.co/Wespeaker/wespeaker-voxceleb-resnet34-LM/resolve/f0c48c298fd835726c27956a5d617bad7115627e/voxceleb_resnet34_LM.onnx",
"sha256": "7bb2f06e9df17cdf1ef14ee8a15ab08ed28e8d0ef5054ee135741560df2ec068",
"size": 26530309,
"license": "CC-BY-4.0",
"source": "huggingface.co/Wespeaker/wespeaker-voxceleb-resnet34-LM@f0c48c298fd835726c27956a5d617bad7115627e (atribuição: WeSpeaker, wenet-e2e)"
} }
] ]
} }
+337
View File
@@ -0,0 +1,337 @@
"""Dublagem em português (camada de desenvolvimento, doc/clipador/DUBLAGEM.md) — sempre com TTS falso."""
import io
import math
import shutil
import struct
import wave
from array import array
from pathlib import Path
import pytest
from app import dub, editor, editor_render, layout, media
FFMPEG = shutil.which("ffmpeg")
CUTS = [{"start": 10.0, "end": 20.0, "mode": None}, {"start": 25.0, "end": 40.0, "mode": None}] # 25 s de saída
def fake_wav(seconds: float, rate: int = 24000, freq: float = 440.0) -> bytes:
"""WAV mono 16 bits com um seno (o "TTS" dos testes)."""
n = int(seconds * rate)
buf = io.BytesIO()
with wave.open(buf, "wb") as w:
w.setnchannels(1)
w.setsampwidth(2)
w.setframerate(rate)
w.writeframes(b"".join(struct.pack("<h", int(12000 * math.sin(2 * math.pi * freq * i / rate))) for i in range(n)))
return buf.getvalue()
class FakeSynth:
"""Duração da fala proporcional ao texto (0,08 s por letra); registra cada chamada."""
def __init__(self, per_char: float = 0.08, fail_voices: tuple[str, ...] = ()):
self.per_char, self.fail_voices, self.calls = per_char, fail_voices, []
def __call__(self, text: str, voice: str) -> bytes:
self.calls.append((voice, text))
if voice in self.fail_voices:
raise dub.DubError(f"voz {voice} respondeu 502")
return fake_wav(max(0.2, len(text) * self.per_char))
def opts(**over):
return {**dub.options(layout.merge({"dev": {"dub": True}})), **over}
# ---------------------------------------------------------------- plano no tempo de saída
def test_lines_go_to_output_time_and_skip_removed_parts():
lines = [
{"s": 11.0, "e": 12.0, "text": "a", "pt": "primeira"},
{"s": 21.0, "e": 23.0, "text": "b", "pt": "no trecho removido"}, # 20–25 foi cortado
{"s": 26.0, "e": 27.0, "text": "c", "pt": " depois do corte "},
{"s": 30.0, "e": 31.0, "text": "d", "pt": ""}, # sem tradução: não dubla
]
plan = dub.plan_lines(lines, CUTS, opts())
assert [(p.at, p.text) for p in plan] == [(1.0, "primeira"), (11.0, "depois do corte")]
assert all(p.voice == layout.DUB_VOICE for p in plan)
def test_speaker_other_uses_second_voice_and_missing_falls_back():
lines = [{"s": 11, "e": 12, "pt": "eu"}, {"s": 13, "e": 14, "pt": "outro", "speaker": "other"},
{"s": 15, "e": 16, "pt": "eu de novo", "speaker": "streamer"}, {"s": 17, "e": 18, "pt": "?", "speaker": "x"}]
plan = dub.plan_lines(lines, CUTS, opts(voice="pt-br-antonio", voiceOther="pt-br-cadu"))
assert [p.voice for p in plan] == ["pt-br-antonio", "pt-br-cadu", "pt-br-antonio", "pt-br-antonio"]
assert plan[1].speaker == "other"
# Sem `dubVoiceOther` na configuração salva: a padrão do Clipador; vazio = a mesma voz do streamer.
assert dub.options(layout.merge({}))["voiceOther"] == layout.DUB_VOICE_OTHER
assert dub.options({"dev": {"dubVoice": "pt-br-faber", "dubVoiceOther": ""}})["voiceOther"] == "pt-br-faber"
# ---------------------------------------------------------------- encaixe
def _line(at: float) -> dub.DubLine:
return dub.DubLine(at, "x", "v")
def test_fit_prefers_natural_speed_spills_over_and_never_overlaps_or_drifts():
lines = [_line(0.0), _line(2.0), _line(4.0), _line(5.0), _line(8.0), _line(9.0), _line(10.0)]
durations = [1.5, 2.6, 3.0, 0.9, 5.0, 0.5, 0.5]
cues = dub.fit(lines, durations, total=14.0)
by = {c.index: c for c in cues}
assert by[0].tempo == 1.0 and by[0].length == 1.5 and not by[0].cut # cabe: natural
assert by[1].tempo == 1.0 and by[1].at + by[1].length > 4.0 # escorre além da próxima frase, sem acelerar
assert by[2].at > 4.0 and by[2].at <= 4.0 + dub.MAX_LATE_S # começa depois da anterior, perto da original
# 3 s sem espaço nem escorrendo: acelera pouco (no máximo MAX_TEMPO) e corta com fade.
assert 1.0 < by[2].tempo <= dub.MAX_TEMPO and by[2].cut
for c in cues: # o atraso de cada fala é limitado pela PRÓPRIA frase original: não acumula
assert lines[c.index].at <= c.at <= lines[c.index].at + dub.MAX_LATE_S
assert c.tempo <= dub.MAX_TEMPO and c.at + c.length <= 14.0
ordered = sorted(cues, key=lambda c: c.at)
for a, b in zip(ordered, ordered[1:]):
assert a.at + a.length + dub.GAP_S <= b.at + 1e-6
def test_phrase_split_mid_sentence_is_joined():
lines = [{"s": 11.0, "e": 12.8, "pt": "se a gente fizer rápido deve dar"}, {"s": 12.9, "e": 13.1, "pt": "tudo certo."},
{"s": 13.2, "e": 13.6, "pt": "Beleza."}, # frase completa antes: não junta
{"s": 13.7, "e": 14.0, "pt": "Como assim"}, {"s": 14.1, "e": 14.5, "pt": "mano?", "speaker": "other"}]
plan = dub.plan_lines(lines, CUTS, opts())
assert [(p.at, p.text) for p in plan] == [(1.0, "se a gente fizer rápido deve dar tudo certo."), (3.2, "Beleza."),
(3.7, "Como assim"), (4.1, "mano?")] # falante diferente: não junta
def test_fit_skips_phrase_without_room_or_audio():
cues = dub.fit([_line(0.0), _line(0.05), _line(3.0)], [2.0, 0.0, 1.0], total=3.2)
assert [c.index for c in cues] == [0] # 1 falhou (não limita a 0); 2 com 0,2 s até o fim: não dá para entender
# Frase fora do trecho (None): não toca, mas segura a anterior no lugar dela.
cues = dub.fit([_line(0.0), _line(1.0)], [2.0, None], total=5.0)
assert [c.index for c in cues] == [0] and cues[0].at + cues[0].length <= 1.0 + dub.MAX_LATE_S
def test_duck_spans_merge_short_gaps_and_ramp_expression():
cues = [dub.Cue(1.0, 1.0, 1.0, False, 0), dub.Cue(2.3, 1.0, 1.0, False, 1), dub.Cue(6.0, 1.0, 1.0, False, 2)]
spans = dub.duck_spans(cues)
assert spans == [(1.0, 3.3), (6.0, 7.0)]
factors = dub.duck_factors(spans, 0.25)
env = {"clip": lambda x, lo, hi: max(lo, min(hi, x)), "min": min}
def gain(t: float) -> float:
value = 1.0
for f in factors:
value *= eval(f, env, {"t": t}) # noqa: S307 — expressão gerada pelo próprio teste
return value
assert gain(0.0) == 1.0 and gain(5.0) == 1.0 and gain(9.0) == 1.0 # fora das falas: normal
assert gain(2.0) == pytest.approx(0.25) and gain(6.5) == pytest.approx(0.25)
assert 0.25 < gain(1.0 - dub.RAMP_S / 2) < 1.0 # rampa antes de começar
assert dub.duck_factors(spans, 1.0) == []
def test_gain_follows_original_level():
assert dub.gain_for(None) == 0.0
assert dub.gain_for(-32.0) == pytest.approx(-32.0 + dub.LEVEL_OVER_ORIGINAL_DB - dub.TTS_LEVEL_DB) # live baixa
assert dub.gain_for(-5.0) == dub.GAIN_RANGE_DB[1] and dub.gain_for(-90.0) == dub.GAIN_RANGE_DB[0]
# ---------------------------------------------------------------- cache
def test_cache_synthesizes_once_per_voice_and_text(tmp_path):
synth = FakeSynth()
cache = dub.TtsCache(tmp_path / "dub", synth, ffmpeg=None)
f1, d1 = cache.get("pt-br-antonio", "olha isso")
f2, d2 = cache.get("pt-br-antonio", "olha isso")
assert f1 == f2 and d1 == d2 == pytest.approx(len("olha isso") * 0.08, abs=0.01)
assert len(synth.calls) == 1
cache.get("pt-br-cadu", "olha isso")
assert len(synth.calls) == 2 and len(list((tmp_path / "dub").glob("*.wav"))) == 2
# Outro processo (render da fila depois da prévia) acha o mesmo arquivo.
again = dub.TtsCache(tmp_path / "dub", FakeSynth(), ffmpeg=None)
assert again.get("pt-br-antonio", "olha isso")[0] == f1 and again.synth_calls == 0
# Limpeza: só o que está sem uso há mais de 30 dias.
import os
import time
old = cache.path("pt-br-cadu", "olha isso")
os.utime(old, (time.time() - 40 * 86400,) * 2)
assert cache.prune() == 1 and not old.exists() and f1.exists()
def test_voice_failure_falls_back_to_offline_voice(tmp_path):
synth = FakeSynth(fail_voices=("pt-br-antonio",))
dubber = dub.Dubber(dub.TtsCache(tmp_path, synth, ffmpeg=None), ffmpeg=None)
path, _ = dubber._speech(dub.DubLine(0.0, "oi", "pt-br-antonio"))
assert synth.calls[-1] == (dub.FALLBACK_VOICE, "oi") and path.is_file()
def test_engine_without_voice_service_builds_nothing(tmp_path):
synth = dub.voice_synth(None, None)
with pytest.raises(dub.DubError):
synth("oi", "pt-br-antonio")
dubber = dub.Dubber(dub.TtsCache(tmp_path, synth, ffmpeg="ffmpeg"), ffmpeg="ffmpeg")
cfg = layout.merge({"dev": {"dub": True}})
assert dubber.build([{"s": 11, "e": 12, "pt": "oi"}], CUTS, cfg, 0, 25, tmp_path, "x") is None
# ---------------------------------------------------------------- configuração
def test_dev_group_validates_new_keys():
ok = layout.validate({"dev": {"dub": True, "dubVoice": "pt-br-faber", "dubVoiceOther": "kokoro-pm-alex", "dubDuck": 0.3}})
assert ok["dev"] == {"dub": True, "dubVoice": "pt-br-faber", "dubVoiceOther": "kokoro-pm-alex", "dubDuck": 0.3}
for bad in ({"dubVoice": "../x"}, {"dubVoiceOther": ""}, {"dubDuck": 1.5}, {"dubDuck": "alto"}):
with pytest.raises(layout.LayoutError):
layout.validate({"dev": bad})
merged = layout.merge({"dev": {"dub": True, "dubDuck": 0.1}})
assert merged["dev"]["dubDuck"] == 0.1 and merged["dev"]["dubVoice"] == layout.DUB_VOICE
assert layout.dev_flags(merged, dev=False) == {"translation": False, "dub": False}
# ---------------------------------------------------------------- render: só no vídeo de revisão
class SpyDubber:
def __init__(self):
self.calls, self.level = 0, None
def build(self, translation, cuts, cfg, t0, t1, work, stem, level_db=None):
self.calls, self.level = self.calls + 1, level_db
file = work / f"{stem}.dub.wav"
file.write_bytes(fake_wav(0.5))
return dub.DubTrack(file, [(1.0, 2.0)], 0.25, 1, 0.1, 1)
def _validated(tmp_path: Path) -> dict:
data = {"schema": 1, "source": {"sessionId": 1, "lo": 0, "hi": 60}, "settings": {}, "cuts": CUTS,
"captions": {"enabled": False, "preset": "pop", "style": {}, "emphColor": "#22E36B", "words": []},
"overlays": [], "progress": {"enabled": False, "color": "#FF7A1A", "height": 12},
"audio": {"volume": 1, "narration": [], "music": None, "sfx": []}, "cover": {"enabled": False, "t": 12, "text": ""}}
return editor.validate_project(data, session_id=1, session_duration=100, repo_root=tmp_path, tts_dir=tmp_path / "tts",
assets_dir=tmp_path / "assets")
@pytest.mark.parametrize("dev_render", [True, False])
def test_render_mixes_dub_only_in_review_video(tmp_path, monkeypatch, dev_render):
seen: list[list[str]] = []
def fake_run(args, timeout, cwd=None):
seen.append(args)
(Path(cwd) / args[-1]).write_bytes(b"mp4")
return b""
monkeypatch.setattr(media, "run", fake_run)
monkeypatch.setattr(editor_render, "mean_volume", lambda *a, **k: -32.0)
(tmp_path / "seg.ts").write_bytes(b"")
spy = SpyDubber()
lines = [{"s": 11.0, "e": 12.0, "text": "No way.", "pt": "Não acredito."}]
info = editor_render.render_project(
"ffmpeg", None, [], [(tmp_path / "seg.ts", 0.0, 100.0)], _validated(tmp_path),
layout.merge({"dev": {"dub": True}}), "x", tmp_path / "out" / "clip.mp4", tmp_path,
translation=lines, dev=dev_render, dubber=spy)
graph = seen[-1][seen[-1].index("-filter_complex") + 1]
if dev_render:
assert spy.calls == 1 and info["dub"]["cues"] == 1 and spy.level == -32.0 # nivelada pelo original
assert any(a.endswith("clip.dub.wav") for a in seen[-1]) and "0.750*clip(" in graph
assert not (tmp_path / "out" / "clip.dub.wav").exists() # faixa temporária apagada
else: # vídeo final (depois de aprovar): nada da dublagem
assert spy.calls == 0 and info["dub"] is None
assert "clip(" not in graph and not any("dub" in a for a in seen[-1])
def test_render_without_dub_flag_does_not_call_dubber(tmp_path, monkeypatch):
monkeypatch.setattr(media, "run", lambda args, timeout, cwd=None: (Path(cwd) / args[-1]).write_bytes(b"x") and b"")
(tmp_path / "seg.ts").write_bytes(b"")
spy = SpyDubber()
editor_render.render_project("ffmpeg", None, [], [(tmp_path / "seg.ts", 0.0, 100.0)], _validated(tmp_path),
layout.merge({}), "x", tmp_path / "out" / "c.mp4", tmp_path,
translation=[{"s": 11, "e": 12, "pt": "oi"}], dubber=spy)
assert spy.calls == 0
# ---------------------------------------------------------------- FFmpeg de verdade (faixa)
def _samples(file: Path) -> tuple[array, int, int]:
with wave.open(str(file)) as w:
data = array("h", w.readframes(w.getnframes()))
return data, w.getframerate(), w.getnchannels()
def _peak(data: array, rate: int, channels: int, a: float, b: float) -> int:
chunk = data[int(a * rate) * channels:int(b * rate) * channels]
return max((abs(x) for x in chunk), default=0)
@pytest.mark.skipif(not FFMPEG, reason="FFmpeg não instalado")
def test_track_places_speech_at_phrase_start_and_uses_cache(tmp_path):
synth = FakeSynth(per_char=0.1)
dubber = dub.Dubber(dub.TtsCache(tmp_path / "cache", synth, FFMPEG), FFMPEG)
cfg = layout.merge({"dev": {"dub": True}})
lines = [{"s": 11.0, "e": 12.0, "pt": "frase um"}, # saída 1,0 s; ~0,8 s de fala
{"s": 22.0, "e": 23.0, "pt": "removida"}, # trecho removido: não dubla
{"s": 27.0, "e": 28.0, "pt": "frase dois"}] # saída 12,0 s
track = dubber.build(lines, CUTS, cfg, 0.0, 25.0, tmp_path, "full")
assert track and track.cues == 2 and track.synthesized == 2
data, rate, channels = _samples(track.file)
assert channels == 2 and abs(len(data) / channels / rate - 25.0) < 0.05
assert _peak(data, rate, channels, 0.0, 0.95) < 200 # silêncio antes da 1ª frase
assert _peak(data, rate, channels, 1.1, 1.6) > 3000 # fala no lugar
assert _peak(data, rate, channels, 3.0, 11.9) < 200
assert _peak(data, rate, channels, 12.1, 12.6) > 3000
assert track.spans[0][0] == pytest.approx(1.0, abs=0.01)
# Prévia de 5 s a partir de 10 s: só a frase que toca ali; tudo do cache.
preview = dubber.build(lines, CUTS, cfg, 10.0, 15.0, tmp_path, "preview")
assert preview and preview.cues == 1 and preview.synthesized == 0 and len(synth.calls) == 2
data, rate, channels = _samples(preview.file)
assert abs(len(data) / channels / rate - 5.0) < 0.05 and _peak(data, rate, channels, 2.1, 2.6) > 3000
assert preview.spans[0][0] == pytest.approx(2.0, abs=0.01)
@pytest.mark.skipif(not FFMPEG, reason="FFmpeg não instalado")
def test_real_render_with_dub(tmp_path):
import subprocess
seg = tmp_path / "seg.ts"
subprocess.run([FFMPEG, "-y", "-v", "error", "-f", "lavfi", "-i", "testsrc2=s=640x360:r=30:d=8", "-f", "lavfi", "-i",
"sine=frequency=300:d=8", "-c:v", "libx264", "-preset", "ultrafast", "-c:a", "aac", "-shortest",
"-f", "mpegts", str(seg)], check=True, capture_output=True)
project = _validated(tmp_path)
project["cuts"] = [{"start": 0.0, "end": 3.0, "mode": None, "muted": False}, {"start": 5.0, "end": 8.0, "mode": None, "muted": False}]
dubber = dub.Dubber(dub.TtsCache(tmp_path / "cache", FakeSynth(), FFMPEG), FFMPEG)
out = tmp_path / "out" / "clip.mp4"
info = editor_render.render_project(
FFMPEG, shutil.which("ffprobe"), ["-c:v", "libx264", "-preset", "ultrafast"], [(seg, 0.0, 8.0)], project,
layout.merge({"dev": {"dub": True}}), "x", out, tmp_path, translation=[{"s": 1.0, "e": 2.0, "pt": "olha só"},
{"s": 5.5, "e": 6.5, "pt": "voltou"}],
dubber=dubber)
assert out.is_file() and info["dub"]["cues"] == 2
assert media.probe_duration(shutil.which("ffprobe"), out) == pytest.approx(6.0, abs=0.25)
assert not list((tmp_path / "out").glob("*.dub.wav"))
# ---------------------------------------------------------------- rotas: prévia do editor e render da fila
from .test_editor import _lavfi_segments, api # noqa: E402,F401 — fixture do editor (sessão, blocos, corte 7)
@pytest.mark.skipif(not FFMPEG, reason="FFmpeg não instalado")
def test_preview_and_queue_render_dub_the_same_way(api, monkeypatch):
from .test_sources_and_api import KEY
client, engine, root = api
_lavfi_segments(root / "data" / "s1")
h = {"X-Service-Key": KEY}
monkeypatch.setattr(engine.intel, "settings_for", lambda session: layout.merge({"dev": {"dub": True}}))
lines = [{"s": 3.0, "e": 4.0, "text": "No way.", "pt": "Não acredito."},
{"s": 6.0, "e": 7.0, "text": "Bro.", "pt": "Mano.", "speaker": "other"}]
monkeypatch.setattr(engine, "translate_clip", lambda clip_id, lo=None, hi=None, force=False: {"lines": lines})
synth = FakeSynth()
engine._dubber = dub.Dubber(dub.TtsCache(root / "data" / "dub", synth, FFMPEG), FFMPEG)
assert dub.for_engine(engine) is engine._dubber
project = client.get("/v1/clips/7/edit", headers=h).json()["project"]
assert client.put("/v1/clips/7/edit", headers=h, json={"project": project, "rev": 0}).status_code == 200
prev = client.post("/v1/clips/7/preview-render", headers=h, json={"fromS": 0, "durationS": 3})
assert prev.status_code == 200, prev.text
assert synth.calls == [(layout.DUB_VOICE, "Não acredito.")] # a prévia só sintetiza o que toca nela
client.post("/v1/clips/7/export", headers=h)
engine.render_pending()
clip = client.get("/v1/clips/7", headers=h).json()
assert clip["status"] == "ready", clip["error"]
# Fila: a 1ª fala veio do cache da prévia; a do "other" saiu com a segunda voz.
assert synth.calls == [(layout.DUB_VOICE, "Não acredito."), (layout.DUB_VOICE_OTHER, "Mano.")]
def test_numbered_other_speakers_use_the_second_voice():
"""Integração com FALANTES.md: a separação entrega `other1`, `other2`…; todas usam a segunda voz."""
from app.dub import voice_for
opts = {"voice": "a", "voiceOther": "b"}
assert voice_for({"speaker": "other1"}, opts) == "b" and voice_for({"speaker": "other2"}, opts) == "b"
assert voice_for({"speaker": "streamer"}, opts) == "a" and voice_for({}, opts) == "a"
+1 -1
View File
@@ -152,7 +152,7 @@ def test_voice_language_maps_audience_codes_to_whisper_codes():
def test_dev_layers_never_reach_the_final_render(tmp_path): def test_dev_layers_never_reach_the_final_render(tmp_path):
"""Contrato `dev` (18/11/2026): camadas de desenvolvimento só no vídeo de revisão; `dev=False` = vídeo final limpo.""" """Contrato `dev` (18/11/2026): camadas de desenvolvimento só no vídeo de revisão; `dev=False` = vídeo final limpo."""
assert layout.DEFAULTS["dev"] == {"translation": False, "dub": False} assert {k: layout.DEFAULTS["dev"][k] for k in ("translation", "dub")} == {"translation": False, "dub": False}
assert layout.validate({"dev": {"translation": True, "dub": True, "x": 1}})["dev"] == {"translation": True, "dub": True} assert layout.validate({"dev": {"translation": True, "dub": True, "x": 1}})["dev"] == {"translation": True, "dub": True}
cfg = layout.merge({"dev": {"translation": True, "dub": True}}) cfg = layout.merge({"dev": {"translation": True, "dub": True}})
assert layout.dev_flags(cfg) == {"translation": True, "dub": True} assert layout.dev_flags(cfg) == {"translation": True, "dub": True}
+309
View File
@@ -0,0 +1,309 @@
"""Mapa de expressões (reaction.py + face.py): expressões novas, pose/corpo e compatibilidade com a série antiga.
Séries sintéticas no formato da live real (doc/clipador/EXPRESSOES.md): neutro com ruído pequeno e eventos injetados.
"""
import json
import math
import random
import numpy as np
import pytest
from app import face as face_mod
from app.reaction import (
EXTRA_SECOND_FIELDS, FaceSample, FaceSecond, ReactionParams, body_moments, channel_z, expression_map, label,
per_second, reaction_moments, seconds_from_json, seconds_to_json, summarize, yawn_seconds, zigzag_legs,
)
from tests.test_face import CAM, make_service, set_cam
from tests.test_sources_and_api import auth, env, seed_session # noqa: F401 - fixture reaproveitada
FPS = 6
def calm(n: int = 300, seed: int = 1, head: bool = True) -> list[FaceSecond]:
"""Neutro como o do skipnho (sessão 8): sorriso baixo, olhos semicerrados ~0,45, lábios um pouco apertados."""
rng = random.Random(seed)
out = []
for t in range(n):
s = FaceSecond(t, 1.0, 0.5, 0.4, 0.3, smile=rng.uniform(0.02, 0.22), jaw=rng.uniform(0.0, 0.02),
surprise=rng.uniform(0.0, 0.004), frown=rng.uniform(0.01, 0.07), brow=rng.uniform(0.02, 0.1),
blink=0.5, motion=rng.uniform(0.02, 0.15))
s.brow_inner = rng.uniform(0.02, 0.1)
s.mouth_frown = rng.uniform(0.0, 0.01)
s.squint = rng.uniform(0.4, 0.5)
s.press = rng.uniform(0.05, 0.12)
s.stretch = rng.uniform(0.0, 0.03)
s.upper_lip = rng.uniform(0.0, 0.02)
s.pucker = rng.uniform(0.0, 0.05)
s.yaw, s.pitch, s.roll = rng.uniform(-3, 3), 12 + rng.uniform(-2, 2), rng.uniform(-2, 2)
s.shake, s.nod = float(rng.choice([0, 0, 1])), float(rng.choice([0, 0, 1]))
if head:
s.head, s.head_motion = 1.0, rng.uniform(0.05, 0.3)
out.append(s)
return out
def expr_at(seconds: list[FaceSecond], t: int) -> str | None:
return expression_map(seconds)[t]["expr"]
# --- expressões novas -------------------------------------------------------------------------------------------
@pytest.mark.parametrize("name,changes", [
("medo", {"brow_inner": 0.7, "brow": 0.7, "stretch": 0.4}),
("tristeza", {"mouth_frown": 0.35, "brow_inner": 0.3}),
("nojo", {"upper_lip": 0.6}),
("espanto", {"pucker": 0.7, "brow": 0.6}),
("tenso", {"press": 0.5, "squint": 0.75}),
("raiva", {"press": 0.5, "squint": 0.75, "frown": 0.15}),
])
def test_each_new_expression_fires_on_its_pattern(name, changes):
seconds = calm()
for key, value in changes.items():
setattr(seconds[200], key, value)
assert expr_at(seconds, 200) == name
# Os vizinhos continuam neutros.
assert expr_at(seconds, 190) == "neutro" and expr_at(seconds, 210) == "neutro"
def test_neutral_has_no_new_expression_nor_body():
emap = expression_map(calm(600, seed=4))
assert {e["expr"] for e in emap} <= {"neutro"}
assert all(e["body"] is None for e in emap)
def test_upper_lip_with_big_smile_is_laughing_not_disgust():
# Sessão 8: todo "nojo" da 1ª rodada era risada de dentes à mostra (sorriso 0,9 já normal dele, lábio de cima 0,4–0,8).
seconds = calm()
for s in seconds:
s.smile = 0.9 + (s.t % 3) * 0.02
seconds[200].upper_lip = 0.6
assert expr_at(seconds, 200) == "risada"
def test_laugh_with_head_thrown_back_is_gargalhada_and_small_smile_is_alegria():
seconds = calm()
seconds[200].smile, seconds[200].pitch = 0.9, -15.0 # 27° acima do neutro dele (+12°)
seconds[250].smile = 0.9
seconds[280].smile = 0.33 # sorriso acima do neutro, mas sem chegar a pico
emap = expression_map(seconds)
assert emap[200]["expr"] == "gargalhada" and emap[250]["expr"] == "risada" and emap[280]["expr"] == "alegria"
def test_yawn_is_not_a_scream_and_never_a_peak():
# Sessão 8: os 5 trechos de jawOpen ≥ 0,6 por 3 s eram bocejos e eram os maiores "gritos" (z 12–16).
seconds = calm()
for t in range(150, 153):
seconds[t].jaw, seconds[t].squint = 0.75, 0.7
seconds[250].jaw = 0.75 # boca escancarada por 1 s: grito
zs = channel_z(seconds)
assert yawn_seconds(seconds, zs, ReactionParams()) == {150, 151, 152}
assert expr_at(seconds, 151) == "bocejo"
assert [(m.peak_s, m.label) for m in reaction_moments(seconds)] == [(250, "grito")]
def test_new_channels_only_label_unless_weighted():
# Peso 0 (padrão): tristeza aparece no mapa, mas não vira pico; com peso, vira.
seconds = calm()
seconds[200].mouth_frown, seconds[200].brow_inner = 0.4, 0.3
assert reaction_moments(seconds) == []
weighted = ReactionParams(extra_weights={"mouth_frown": 1.0})
assert [(m.peak_s, m.label) for m in reaction_moments(seconds, weighted)] == [(200, "tristeza")]
def test_label_without_z_uses_raw_thresholds_for_new_channels():
second = calm(1)[0]
second.upper_lip = 0.6
assert label(second) == "nojo"
# --- corpo / cabeça pela pose -----------------------------------------------------------------------------------
def posed(duration: int, yaw=lambda t: 0.0, pitch=lambda t: 12.0, size=lambda t: 0.3, cx=lambda t: 0.5,
present=lambda t: True, head=lambda t: False) -> list[FaceSample]:
rng = random.Random(7)
out = []
for i in range(duration * FPS):
t = i / FPS
if present(t):
blend = {"mouthSmileLeft": 0.05, "mouthSmileRight": 0.05, "jawOpen": 0.01}
pose = (yaw(t) + rng.uniform(-1, 1), pitch(t) + rng.uniform(-1, 1), rng.uniform(-1, 1))
out.append(FaceSample(t, True, cx(t) + rng.uniform(-0.003, 0.003), 0.4, size(t), blend, pose))
elif head(t):
out.append(FaceSample(t, False, cx(t), 0.4, size(t), head=True))
else:
out.append(FaceSample(t, False))
return out
def window(lo: float, hi: float, fn, rest=0.0):
return lambda t: fn(t) if lo <= t < hi else rest
def test_zigzag_counts_back_and_forth():
assert zigzag_legs([0, 1, -1, 2, 0], 8) == []
assert len(zigzag_legs([0, 20, 0], 8)) == 2 # olhou para o lado e voltou
assert len(zigzag_legs([0, 15, -15, 15, -15], 8)) == 4
def test_head_shake_and_nod_from_pose():
shake = window(100, 103, lambda t: 15 * math.sin(2 * math.pi * 1.2 * t))
nod = window(200, 203, lambda t: 12 + 10 * math.sin(2 * math.pi * 1.2 * t), 12.0)
glance = window(250, 251.5, lambda t: 30 * math.sin(math.pi * (t - 250) / 1.5)) # vira e volta uma vez
seconds = per_second(posed(300, yaw=lambda t: shake(t) + glance(t), pitch=nod), 300)
labels = [(b.label, b.start_s) for b in body_moments(seconds)]
assert any(name == "balançando" and 99 <= s <= 101 for name, s in labels)
assert any(name == "acenando" and 199 <= s <= 202 for name, s in labels)
assert not any(name == "balançando" and 248 <= s <= 252 for name, s in labels)
assert seconds[50].yaw is not None and abs(seconds[50].pitch - 12) < 2
def test_lost_face_is_not_agitation_but_real_movement_is():
# Rastreio piscando: rosto some e volta noutro lugar a cada meio segundo (o "pico" de movimento da live real).
flicker = lambda t: not (100 <= t < 110 and int(t * 2) % 2 == 1) # noqa: E731
jump = window(100, 110, lambda t: 0.3 * (int(t * 2) % 4 == 0), 0.0)
moving = window(200, 206, lambda t: 0.12 * math.sin(2 * math.pi * 2.5 * t))
seconds = per_second(posed(300, present=flicker, cx=lambda t: 0.5 + jump(t) + moving(t)), 300)
agitated = [b for b in body_moments(seconds) if b.label == "agitado"]
assert agitated and all(199 <= b.start_s and b.end_s <= 206 for b in agitated)
def test_leaving_the_frame_and_leaning_in():
gone = lambda t: not (150 <= t < 170) # noqa: E731
seconds = per_second(posed(300, present=gone, size=window(80, 83, lambda t: 0.42, 0.3)), 300)
labels = {(b.label, b.start_s) for b in body_moments(seconds)}
assert ("saiu do quadro", 150) in labels
assert any(name == "chegou perto" and 80 <= s <= 82 for name, s in labels)
def test_head_box_keeps_the_body_when_the_face_is_in_profile():
# Sessão 15 (tfue de perfil): MediaPipe em 10 % dos quadros, YuNet em 100 %. A caixa da cabeça não é "rosto".
in_profile = lambda t: t < 30 # noqa: E731
out = lambda t: not (150 <= t < 160) # noqa: E731
samples = posed(300, present=in_profile, head=out)
seconds = per_second(samples, 300)
assert seconds[100].present == 0.0 and seconds[100].smile is None and seconds[100].head == 1.0
assert seconds[100].hsize == pytest.approx(0.3) and seconds[155].head == 0.0
assert ("saiu do quadro", 150) in {(b.label, b.start_s) for b in body_moments(seconds)}
text = summarize(seconds, 140, 170)
assert text.startswith("rosto sem expressão legível") and "saiu do quadro em 10 s" in text
# --- compatibilidade --------------------------------------------------------------------------------------------
def test_old_series_without_new_fields_still_works():
seconds = calm()
seconds[200].smile = 0.9
data = seconds_to_json(seconds)
for d in data:
for name in EXTRA_SECOND_FIELDS:
d.pop(name, None)
old = seconds_from_json(json.loads(json.dumps(data)))
assert old[0].brow_inner is None and old[0].head is None
assert [m.label for m in reaction_moments(old)] == ["risada"]
assert body_moments(old) == [] # sem `head` não há "saiu do quadro"; sem pose, nem balanço
assert {e["expr"] for e in expression_map(old)} <= {"neutro", "risada"}
def test_service_updated_mid_session_does_not_fake_new_expressions():
# Primeira metade gravada antes (sem os campos novos), segunda com eles: o neutro do canal novo usa só a segunda.
seconds = calm(400)
for s in seconds[:200]:
for name in EXTRA_SECOND_FIELDS:
setattr(s, name, None)
emap = expression_map(seconds)
assert {e["expr"] for e in emap} <= {"neutro"}
assert body_moments(seconds) == []
def test_new_fields_roundtrip_compact():
s = calm(1)[0]
data = s.to_json()
assert set(EXTRA_SECOND_FIELDS) - {"hsize"} <= set(data)
assert data["yaw"] == round(s.yaw, 1) and len(str(data["squint"]).split(".")[-1]) <= 3
back = FaceSecond.from_json(json.loads(json.dumps(data)))
assert back.hsize is None and abs(back.squint - s.squint) < 1e-3
# --- face.py ----------------------------------------------------------------------------------------------------
def test_pose_from_matrix():
a = math.radians(20)
rx = [[1, 0, 0, 0], [0, math.cos(a), -math.sin(a), 0], [0, math.sin(a), math.cos(a), 0], [0, 0, 0, 1]]
yaw, pitch, roll = face_mod.pose_from_matrix(rx)
assert pitch == pytest.approx(20) and abs(yaw) < 1e-6 and abs(roll) < 1e-6
ry = [[math.cos(a), 0, math.sin(a), 0], [0, 1, 0, 0], [-math.sin(a), 0, math.cos(a), 0], [0, 0, 0, 1]]
assert face_mod.pose_from_matrix(ry)[0] == pytest.approx(20)
class FakeDetector:
def __init__(self, result=None, error=None):
self.result, self.error, self.calls = result or [], error, 0
def detect(self, bgr):
self.calls += 1
assert bgr.shape == (40, 80, 3)
if self.error:
raise self.error
return self.result
def tracker_with(detector):
tracker = object.__new__(face_mod.MediaPipeTracker) # sem carregar o MediaPipe: só o caminho da caixa da cabeça
tracker._np, tracker._detector = np, detector
return tracker
def test_tracker_head_box_when_mediapipe_loses_the_face():
rgb = np.zeros((40, 80, 3), np.uint8)
sample = tracker_with(FakeDetector([(10, 4, 20, 20, 0.7), (40, 10, 16, 20, 0.9)]))._head_only(1.5, rgb)
assert sample.present is False and sample.head is True and sample.blend == {}
assert sample.cx == pytest.approx(0.6) and sample.cy == pytest.approx(0.5) and sample.size == pytest.approx(0.5)
assert tracker_with(FakeDetector([]))._head_only(1.5, rgb) == FaceSample(1.5, False)
assert tracker_with(FakeDetector(error=RuntimeError("cv2")))._head_only(1.5, rgb) == FaceSample(1.5, False)
assert tracker_with(None)._head_only(1.5, rgb) == FaceSample(1.5, False)
def test_to_frame_converts_head_size():
second = FaceSecond(0, 0.0, hsize=0.5)
assert face_mod.to_frame([second], CAM)[0].hsize == pytest.approx(0.25)
class PosedTracker:
"""Rosto com pose: sorriso alto em `laughs`; balanço da cabeça em `shakes`."""
name = "fake"
def __init__(self, laughs=(), shakes=()):
self.laughs, self.shakes = set(laughs), set(shakes)
def process(self, t, rgb):
smile = 0.9 if int(t) in self.laughs else 0.05 + 0.05 * ((int(t * 6) % 3) / 2)
yaw = 15 * math.sin(2 * math.pi * 1.2 * t) if int(t) in self.shakes else 0.0
return FaceSample(t, True, 0.5, 0.4, 0.3, {"mouthSmileLeft": smile, "mouthSmileRight": smile},
(yaw, 12.0, 0.0))
def close(self):
pass
def test_face_api_has_the_expression_map_and_body(env): # noqa: F811
client, engine = env
service = make_service(engine, tracker_factory=lambda _b=None: PosedTracker(range(300, 306), range(310, 313)))
sid = seed_session(engine)
set_cam(engine, sid)
while service.step():
pass
body = client.get(f"/v1/sessions/{sid}/face?from=290&to=320", headers=auth()).json()
by_t = {s["t"]: s for s in body["seconds"]}
assert by_t[302]["expr"] == "risada" and by_t[295]["expr"] == "neutro"
assert by_t[311]["body"] == "balançando" and "body" not in by_t[295]
assert "yaw" in by_t[295] and by_t[295]["head"] == 1.0
assert [b["label"] for b in body["body"]] == ["balançando"]
line = service.summary(engine.db.get("SELECT * FROM sessions WHERE id = ?", sid), 295, 315)
assert "risada" in line and "balançando a cabeça em 3" in line
+285
View File
@@ -0,0 +1,285 @@
"""Vídeo de revisão × vídeo final (doc/clipador/REVISAO.md, pedido do dono 18/11/2026): "quando o clipe está ali para
a gente aprovar, a legenda é só de dev. Quando a gente aprovar, ele vai renderizar o vídeo de novo, removendo as coisas
de dev". O render da fila é o de revisão (dev=True); aprovar enfileira o final (dev=False); publicar só usa o final."""
import json
import sqlite3
from pathlib import Path
import app.db as db_module
import app.editor_api as editor_api
import app.worker as worker_module
from app import layout
from app.db import Database
from .test_sources_and_api import auth, env, seed_session # noqa: F401 - fixture reaproveitada
def add_ready_clip(engine, sid, cid=1, layers: list[str] | None = None, status="ready"):
engine.db.run(
"INSERT INTO clips (id, session_id, peak_s, start_s, end_s, score, source, status, title, file, thumb, review_dev_json,"
" created_at, updated_at) VALUES (?, ?, 100, 90, 160, 8, 'chat', ?, 't', ?, ?, ?, 'x', 'x')",
cid, sid, status, f"output/clipper/{sid}/clip-{cid}.mp4", f"output/clipper/{sid}/clip-{cid}.jpg",
None if layers is None else json.dumps(layers))
class RenderSpy:
"""Troca o render de verdade: guarda com que `dev` e para qual arquivo cada render foi pedido."""
def __init__(self, monkeypatch, engine, fail: bool = False):
self.calls: list[dict] = []
self.fail = fail
monkeypatch.setattr(worker_module, "REPO_ROOT", engine.settings.data_dir.parent) # caminhos relativos do teste
monkeypatch.setattr(editor_api, "ensure_edit", lambda eng, clip, session: {"project": {}})
monkeypatch.setattr(editor_api, "render_clip_edit", self)
def __call__(self, engine, clip, session, edit, out: Path, thumb: Path, dev: bool = True):
self.calls.append({"clip": clip["id"], "out": out.name, "thumb": thumb.name, "dev": dev})
if self.fail:
from app import media
raise media.MediaError("ffmpeg caiu")
return f"output/clipper/{clip['session_id']}/{out.stem}-cover.jpg"
def view(client, cid=1) -> dict:
return client.get(f"/v1/clips/{cid}", headers=auth()).json()
def approve(client, cid=1, status="approved") -> dict:
r = client.patch(f"/v1/clips/{cid}", json={"status": status}, headers=auth())
assert r.status_code == 200, r.text
return r.json()
# ---------------------------------------------------------------- aprovar → final com dev=False
def test_approve_queues_final_render_without_dev_layers(env, monkeypatch): # noqa: F811
client, engine = env
sid = seed_session(engine)
add_ready_clip(engine, sid, layers=["translation"])
spy = RenderSpy(monkeypatch, engine)
before = view(client)
assert before["review"]["devLayers"] == ["translation"] and before["final"] is None and before["publishFile"] is None
body = approve(client)
assert body["status"] == "approved"
assert body["final"]["status"] == "pending" and body["publishFile"] is None # nada publicável ainda
assert engine.wake_clips.is_set()
engine.render_pending()
assert spy.calls == [{"clip": 1, "out": "clip-1-final.mp4", "thumb": "clip-1-final.jpg", "dev": False}]
after = view(client)
final = after["final"]
assert final["status"] == "ready" and not final["reused"] and final["error"] is None
assert final["file"].endswith("clip-1-final.mp4") and final["thumb"].endswith("clip-1-final.jpg")
assert final["cover"].endswith("clip-1-final-cover.jpg")
assert after["publishFile"] == final["file"] != after["file"] # o de revisão continua sendo `file`
engine.render_pending()
assert len(spy.calls) == 1 # pronto não renderiza de novo
def test_review_render_of_the_queue_stays_dev_true(env, monkeypatch): # noqa: F811
client, engine = env
monkeypatch.setattr(worker_module, "REPO_ROOT", engine.settings.data_dir.parent)
sid = seed_session(engine)
add_ready_clip(engine, sid, layers=None, status="pending")
spy = RenderSpy(monkeypatch, engine)
engine.render_pending()
assert spy.calls == [{"clip": 1, "out": "clip-1.mp4", "thumb": "clip-1.jpg", "dev": True}]
assert view(client)["status"] == "ready" and view(client)["final"] is None
def test_unknown_layers_render_final(env, monkeypatch): # noqa: F811
"""Sem saber o que entrou no vídeo de revisão (`review_dev_json` NULL), o final é renderizado por cautela."""
client, engine = env
sid = seed_session(engine)
add_ready_clip(engine, sid, layers=None)
spy = RenderSpy(monkeypatch, engine)
assert approve(client)["final"]["status"] == "pending"
engine.render_pending()
assert [c["dev"] for c in spy.calls] == [False]
# ---------------------------------------------------------------- sem camadas dev: reaproveita
def test_without_dev_layers_review_is_already_final(env, monkeypatch): # noqa: F811
client, engine = env
sid = seed_session(engine)
add_ready_clip(engine, sid, layers=[])
engine.db.run("INSERT INTO edits (clip_id, project_json, created_at, updated_at, cover) VALUES (1, '{}', 'x', 'x', ?)",
f"output/clipper/{sid}/clip-1-cover.jpg")
spy = RenderSpy(monkeypatch, engine)
body = approve(client)
assert body["final"]["status"] == "ready" and body["final"]["reused"]
assert body["publishFile"] == body["file"] and body["final"]["cover"].endswith("clip-1-cover.jpg")
engine.render_pending()
assert spy.calls == [] # não renderizou de novo
# ---------------------------------------------------------------- publicação nunca pega o de revisão
def test_publish_file_is_never_the_review_video(env, monkeypatch): # noqa: F811
client, engine = env
sid = seed_session(engine)
add_ready_clip(engine, sid, 1, layers=["translation"])
add_ready_clip(engine, sid, 2, layers=["dub", "translation"])
spy = RenderSpy(monkeypatch, engine, fail=True)
def publishable() -> dict[int, str | None]:
clips = client.get("/v1/clips?status=ready,approved,published", headers=auth()).json()["clips"]
return {c["id"]: c["publishFile"] for c in clips}
assert publishable() == {1: None, 2: None} # pronto para aprovar = só revisão
approve(client, 1)
approve(client, 2, status="published") # marcado publicado direto também pede o final
assert publishable() == {1: None, 2: None} # final na fila
engine.render_pending() # o render final falha
for cid in (1, 2):
v = view(client, cid)
assert v["final"]["status"] == "error" and "ffmpeg caiu" in v["final"]["error"]
assert v["publishFile"] is None and v["status"] in ("approved", "published") # erro não vira revisão publicável
# "Tentar de novo" (POST /final): volta à fila e, desta vez, sai.
spy.fail = False
assert client.post("/v1/clips/1/final", headers=auth()).json()["final"]["status"] == "pending"
engine.render_pending()
v = view(client, 1)
assert v["publishFile"] and v["publishFile"] != v["file"] and v["publishFile"].endswith("-final.mp4")
assert all(f is None or f.endswith("-final.mp4") for f in publishable().values())
# Só corte aprovado tem final.
client.patch("/v1/clips/2", json={"status": "ready"}, headers=auth())
assert client.post("/v1/clips/2/final", headers=auth()).status_code == 409
# ---------------------------------------------------------------- desaprovar / editar
def test_unapprove_edit_and_rerender_drop_the_final(env, monkeypatch): # noqa: F811
client, engine = env
monkeypatch.setattr(worker_module, "REPO_ROOT", engine.settings.data_dir.parent)
sid = seed_session(engine)
add_ready_clip(engine, sid, layers=["translation"])
spy = RenderSpy(monkeypatch, engine)
approve(client)
engine.render_pending()
assert view(client)["publishFile"]
# Desaprovar (voltar para pronto) ou rejeitar: o final deixa de valer.
body = client.patch("/v1/clips/1", json={"status": "ready"}, headers=auth()).json()
assert body["final"] is None and body["publishFile"] is None
approve(client)
assert view(client)["final"]["status"] == "pending" # aprovar de novo = final novo
engine.render_pending()
# Mudar o trecho de um aprovado: volta a ser revisão (renderiza de novo) e o final some.
body = client.patch("/v1/clips/1", json={"startS": 95, "endS": 160}, headers=auth()).json()
assert body["status"] == "pending" and body["final"] is None and body["publishFile"] is None
# Render de revisão novo também derruba qualquer final (ex.: export do editor).
engine.db.run("UPDATE clips SET status = 'approved', final_status = 'ready', final_file = 'x-final.mp4' WHERE id = 1")
engine.render_pending() # o final está pronto; nada pendente
engine.db.run("UPDATE clips SET status = 'pending' WHERE id = 1")
engine.render_pending()
v = view(client)
assert v["status"] == "ready" and v["final"] is None and spy.calls[-1]["dev"] is True
# Pedir render de novo (botão) também.
approve(client)
engine.render_pending()
assert client.post("/v1/clips/1/render", headers=auth()).json()["final"] is None
def test_unapprove_during_final_render_discards_it(env, monkeypatch): # noqa: F811
client, engine = env
sid = seed_session(engine)
add_ready_clip(engine, sid, layers=["translation"])
approve(client)
def slow_render(eng, clip, session, edit, out, thumb, dev=True):
client.patch("/v1/clips/1", json={"status": "ready"}, headers=auth()) # desaprovou no meio do render
return None
monkeypatch.setattr(editor_api, "ensure_edit", lambda eng, clip, session: {"project": {}})
monkeypatch.setattr(editor_api, "render_clip_edit", slow_render)
engine.render_pending()
v = view(client)
assert v["final"] is None and v["publishFile"] is None and engine._rendering == set()
# ---------------------------------------------------------------- quais camadas entraram na revisão
def test_review_layers():
lines = [{"s": 0, "e": 1, "text": "hi", "pt": "oi"}]
on = layout.merge({"dev": {"translation": True}})
assert editor_api.review_layers(on, lines) == ["translation"]
assert editor_api.review_layers(on, None) == [] # fonte em português: nada desenhado
assert editor_api.review_layers(layout.merge(), lines) == []
# A dublagem sai das frases traduzidas: sem frase (fonte em português), não houve dublagem.
assert editor_api.review_layers(layout.merge({"dev": {"dub": True}}), None) == []
assert editor_api.review_layers(layout.merge({"dev": {"dub": True}}), lines) == ["dub"]
legacy = layout.merge({"caption": {"translation": True}})
assert editor_api.review_layers(legacy, lines) == ["translation"]
def test_render_clip_edit_passes_dev_and_records_layers(env, monkeypatch): # noqa: F811
"""render_clip_edit: dev=True grava as camadas da revisão; dev=False não pede tradução nem mexe no registro."""
_client, engine = env
sid = seed_session(engine)
add_ready_clip(engine, sid, layers=None)
seen: list[dict] = []
project = {"cover": {"enabled": False}, "cuts": [{"start": 90, "end": 150, "mode": None}]}
monkeypatch.setattr(editor_api, "validate_for", lambda eng, clip, session, data: project)
monkeypatch.setattr(editor_api.editor, "effective_settings", lambda base, p: layout.merge({"dev": {"translation": True}}))
monkeypatch.setattr(editor_api, "translation_for",
lambda eng, clip, p, base, dev=True: [{"s": 0, "e": 1, "text": "hi", "pt": "oi"}] if dev else None)
monkeypatch.setattr(editor_api.editor_render, "render_project",
lambda *a, **k: seen.append({"dev": k["dev"], "translation": k["translation"]}))
monkeypatch.setattr(editor_api.media, "thumbnail", lambda *a, **k: None)
monkeypatch.setattr(editor_api.media, "pick_encoder", lambda *a, **k: [])
session = engine.db.get("SELECT * FROM sessions WHERE id = ?", sid)
clip = engine.db.get("SELECT * FROM clips WHERE id = 1")
out = engine.settings.clips_dir / "clip-1.mp4"
editor_api.render_clip_edit(engine, clip, session, {"project": project}, out, out.with_suffix(".jpg"))
assert seen[-1]["dev"] is True and seen[-1]["translation"]
assert json.loads(engine.db.get("SELECT review_dev_json FROM clips WHERE id = 1")["review_dev_json"]) == ["translation"]
final = engine.settings.clips_dir / "clip-1-final.mp4"
editor_api.render_clip_edit(engine, clip, session, {"project": project}, final, final.with_suffix(".jpg"), dev=False)
assert seen[-1] == {"dev": False, "translation": None}
assert json.loads(engine.db.get("SELECT review_dev_json FROM clips WHERE id = 1")["review_dev_json"]) == ["translation"]
# ---------------------------------------------------------------- limpeza e migração
def test_prune_keeps_segments_that_the_final_still_needs(env, monkeypatch): # noqa: F811
_client, engine = env
monkeypatch.setattr(worker_module, "REPO_ROOT", engine.settings.data_dir.parent)
sid = seed_session(engine) # blocos de 30 s, todos "velhos" (wall_end ≈ 1970)
engine.db.run("INSERT INTO clips (id, session_id, peak_s, start_s, end_s, score, source, status, review_dev_json, created_at,"
" updated_at) VALUES (1, ?, 100, 90, 110, 8, 'chat', 'ready', '[\"translation\"]', 'x', 'x')", sid)
engine.db.run("INSERT INTO clips (id, session_id, peak_s, start_s, end_s, score, source, status, review_dev_json, created_at,"
" updated_at) VALUES (2, ?, 200, 190, 200, 8, 'chat', 'ready', '[]', 'x', 'x')", sid)
engine.db.run("INSERT INTO clips (id, session_id, peak_s, start_s, end_s, score, source, status, final_status, created_at,"
" updated_at) VALUES (3, ?, 400, 400, 410, 8, 'chat', 'approved', 'error', 'x', 'x')", sid)
engine.prune()
kept = {r["idx"] for r in engine.db.all("SELECT idx FROM segments WHERE session_id = ? AND deleted = 0", sid)}
assert kept == {3, 13} # 90–110 s (revisão com tradução) e 400–410 s (final com erro); o 190–200 s (limpo) saiu
def test_migration_v14_backfills_old_clips(tmp_path):
path = tmp_path / "clipper.db"
conn = sqlite3.connect(path) # banco como estava na v13
for script in db_module.SCHEMA[:13]:
for statement in db_module._split(script):
conn.execute(statement)
conn.execute("PRAGMA user_version = 13")
conn.execute("INSERT INTO sessions (id, platform, kind, url, status, dir, started_at) VALUES (1, 'twitch', 'live', 'u', 'done', '', 'x')")
rows = [(1, "approved", "a.mp4", None), (2, "approved", "b.mp4", '{"lines": []}'), (3, "published", "c.mp4", '{"lines": []}'),
(4, "ready", "d.mp4", None), (5, "published", "e.mp4", None), (6, "candidate", None, None)]
for cid, status, file, translation in rows:
conn.execute("INSERT INTO clips (id, session_id, peak_s, start_s, end_s, score, source, status, file, translation_json,"
" created_at, updated_at) VALUES (?, 1, 1, 0, 10, 1, 'chat', ?, ?, ?, 'x', 'u')", (cid, status, file, translation))
conn.commit()
conn.close()
db = Database(path)
got = {r["id"]: (r["review_dev_json"], r["final_status"], r["final_file"])
for r in db.all("SELECT id, review_dev_json, final_status, final_file FROM clips")}
db.close()
assert got == {
1: ("[]", "ready", "a.mp4"), # sem tradução: o arquivo já era limpo → é o final
2: (None, "pending", None), # com tradução e aprovado: renderiza o final
3: (None, None, None), # publicado (já saiu): só gera final se pedirem (POST /final)
4: ("[]", None, None),
5: ("[]", "ready", "e.mp4"),
6: (None, None, None),
}
+389
View File
@@ -0,0 +1,389 @@
"""Quem fala cada palavra (doc/clipador/FALANTES.md): atribuição por voz + boca/volume, legenda em duas linhas sem
misturar falantes, tradução com `speaker`, juiz com a fala marcada e compatibilidade com `words_json` antigo."""
import json
import re
import numpy as np
import pytest
from app import editor, editor_render, layout, subtitles
from app import speakers as spk
from app.face import FaceService
from app.judge import _transcript
from app.scoring import Word
from app.speakers import STREAMER, SpeakerService, VoiceChunk
from .test_editor import validate
from .test_english_source import EnglishJudge, _english_session
from .test_face import CAM, fake_reader, set_cam
from .test_face import FakeTracker
from .test_render_and_duplicates import add_clip
from .test_sources_and_api import env, seed_session # noqa: F401 - fixture reaproveitada
A, B, C = np.eye(256, dtype=np.float32)[0], np.eye(256, dtype=np.float32)[1], np.eye(256, dtype=np.float32)[2]
def _noisy(vec, k):
"""Vetor de voz com um pouco de ruído (a mesma voz nunca dá o mesmo vetor duas vezes)."""
rng = np.random.default_rng(k)
v = vec + rng.normal(0, 0.02, 256).astype(np.float32)
return v / np.linalg.norm(v)
def _conversation(n=12, length=2.0, db_streamer=-28.0, db_other=-36.0):
"""Trechos alternados: streamer (voz A) e colega (voz B), `n` de cada."""
out = []
for i in range(n):
out.append(VoiceChunk(i * 6.0, i * 6.0 + length, db_streamer, _noisy(A, i)))
out.append(VoiceChunk(i * 6.0 + 3.0, i * 6.0 + 3.0 + length, db_other, _noisy(B, 100 + i)))
return out
# ---------------------------------------------------------------- dados / compatibilidade
def test_words_json_old_and_new_format():
old = json.dumps([[1.0, 1.4, "olha"], [1.5, 1.9, "isso"]])
words = spk.parse_words(old)
assert words == [Word(1.0, 1.4, "olha"), Word(1.5, 1.9, "isso")] and words[0].speaker == ""
new = spk.parse_words(json.dumps([[1.0, 1.4, "olha", "streamer"], [2.0, 2.3, "bro", "other1"], [3, 3.1, "x", ""]]))
assert [w.speaker for w in new] == ["streamer", "other1", ""]
# Sem falante, o formato gravado continua o antigo (3 elementos); com falante, 4.
assert json.loads(spk.dump_words(words)) == [[1.0, 1.4, "olha"], [1.5, 1.9, "isso"]]
assert json.loads(spk.dump_words(new))[1] == [2.0, 2.3, "bro", "other1"]
assert spk.parse_words(None) == [] and spk.parse_words("[[1, 2]]") == []
def test_speech_chunks_split_on_pause_and_length():
words = [Word(0.0, 0.4, "a"), Word(0.5, 0.9, "b"), Word(1.5, 1.8, "c"), Word(1.85, 2.0, "d")]
assert spk.speech_chunks(words) == [(0.0, 0.9), (1.5, 2.0)]
long = [Word(i * 0.3, i * 0.3 + 0.28, "w") for i in range(20)] # 6 s de fala corrida
chunks = spk.speech_chunks(long)
assert len(chunks) == 2 and all(b - a <= spk.CHUNK_MAX_S for a, b in chunks)
# Fim de frase fecha o trecho (a vez costuma trocar ali, mesmo sem pausa); frase curtinha não.
turn = [Word(0.0, 0.3, "bring"), Word(0.32, 0.6, "two."), Word(0.62, 0.8, "Ok."), Word(0.82, 1.0, "yes")]
assert spk.speech_chunks(turn) == [(0.0, 0.6), (0.62, 1.0)]
# ---------------------------------------------------------------- atribuição (vetores sintéticos)
def test_two_voices_streamer_by_loudness():
model = spk.build_model(_conversation())
assert model.active and len(model.voices) == 2 and model.reason.startswith("volume")
labels = [c.label for c in model.chunks]
assert labels == ["streamer", "other1"] * 12
def test_mouth_series_picks_the_streamer_even_when_quieter():
# Colega mais ALTO que o streamer (volume enganaria), mas a boca do streamer mexe nos trechos dele.
chunks = _conversation(db_streamer=-36.0, db_other=-29.0)
mine = {round(c.start, 1) for c in chunks if c.vec[0] > 0.5}
def mouth_of(a, b):
rng = np.random.default_rng(int(a * 10))
return float(0.30 + rng.normal(0, 0.02)) if round(a, 1) in mine else float(0.12 + rng.normal(0, 0.02))
model = spk.build_model(chunks, mouth_of)
# Boca e volume discordam → ninguém vira "outro" (seguro: fica tudo como do streamer).
assert not model.active and "apontam vozes diferentes" in model.reason
assert {c.label for c in model.chunks} == {STREAMER}
# Sem volume (sem prova do áudio), a boca decide sozinha.
for c in chunks:
c.db = None
model = spk.build_model(chunks, mouth_of)
assert model.active and model.reason.startswith("boca")
assert [c.label for c in model.chunks] == ["streamer", "other1"] * 12
def test_no_proof_or_single_voice_keeps_everything_as_streamer():
flat = _conversation(db_streamer=-30.0, db_other=-31.0) # 1 dB de diferença e sem câmera
model = spk.build_model(flat)
assert not model.active and {c.label for c in model.chunks} == {STREAMER}
solo = [VoiceChunk(i * 3.0, i * 3.0 + 2.0, -30.0, _noisy(A, i)) for i in range(20)]
model = spk.build_model(solo)
assert len(model.voices) == 1 and not model.active
words = [Word(0.2, 0.5, "oi")]
assert spk.label_words(words, model.chunks) == words # nada muda
def test_three_voices_are_numbered_and_short_chunks_follow_the_neighbor():
chunks = _conversation()
chunks += [VoiceChunk(200 + i * 4.0, 202 + i * 4.0, -37.0, _noisy(C, 300 + i)) for i in range(10)]
chunks.append(VoiceChunk(5.2, 5.5, -36.0, None)) # curto (sem vetor), logo depois do colega (3–5 s)
model = spk.build_model(chunks)
assert [v.label for v in model.voices] == ["streamer", "other1", "other2"]
words = [Word(0.1, 0.5, "yo"), Word(3.2, 3.6, "bro"), Word(5.25, 5.45, "ok"), Word(201.0, 201.4, "hey"),
Word(150.0, 150.3, "longe")]
got = [w.speaker for w in spk.label_words(words, model.chunks)]
assert got == ["streamer", "other1", "other1", "other2", "streamer"]
# Palavra que já veio com falante (4º elemento) não é trocada.
assert spk.label_words([Word(3.2, 3.6, "bro", "streamer")], model.chunks)[0].speaker == "streamer"
def test_transfer_keeps_speaker_on_retranscription():
old = [Word(1.0, 1.5, "a", "streamer"), Word(3.0, 3.5, "b", "other1")]
new = spk.transfer([Word(1.1, 1.4, "A"), Word(3.1, 3.3, "B")], old)
assert [w.speaker for w in new] == ["streamer", "other1"]
# ---------------------------------------------------------------- serviço (banco + embedder falso)
class FakeEmbedder:
"""Voz pelo volume do trecho: alto = voz A (streamer), baixo = voz B (colega)."""
def embed(self, samples):
if len(samples) < 8000:
return None
loud = float(np.sqrt(np.mean(samples.astype(np.float64) ** 2)))
return _noisy(A if loud > 4000 else B, int(loud)).tolist()
def _block_audio(start_s):
"""30 s: streamer (amplitude 8000) em [i·6, i·6+2] e colega (2000) em [i·6+3, i·6+5]; palavras nos mesmos tempos."""
sr = 16000
pcm = np.zeros(30 * sr, np.int16)
words = []
rng = np.random.default_rng(int(start_s))
for i in range(5):
for off, amp, text in ((0.0, 8000, "me"), (3.0, 2000, "you")):
a = i * 6.0 + off
pcm[int(a * sr): int((a + 2.0) * sr)] = (rng.standard_normal(int(2.0 * sr)) * amp).astype(np.int16)
words += [Word(start_s + a + k * 0.4, start_s + a + k * 0.4 + 0.35, text) for k in range(5)]
return pcm.tobytes(), words
def test_service_indexes_blocks_and_labels_the_timeline(env): # noqa: F811
_client, engine = env
engine.speakers = SpeakerService(engine, embedder_factory=FakeEmbedder)
sid = seed_session(engine, duration=120)
assert engine.speakers.view(sid)["active"] is False # nada indexado ainda
for seg in engine.db.all("SELECT * FROM segments WHERE session_id = ? ORDER BY idx", sid):
pcm, words = _block_audio(seg["start_s"])
assert engine.speakers.index_block(seg, pcm, words) == 10
engine.db.run("UPDATE segments SET words_json = ? WHERE session_id = ? AND idx = ?",
spk.dump_words(words), sid, seg["idx"])
view = engine.speakers.view(sid)
assert view["active"] and view["streamer"] == "streamer" and len(view["voices"]) == 2
words = engine.load_timeline(sid)["words"]
assert {w.speaker for w in words if w.word == "me"} == {"streamer"}
assert {w.speaker for w in words if w.word == "you"} == {"other1"}
# O mesmo vale para as palavras que o editor lê.
between = engine.words_between(sid, 0, 30)
assert {w.speaker for w in between if w.word == "you"} == {"other1"}
# Desligado (opção `speakers`), tudo volta a ser como antes.
engine.intel.opts["speakers"] = False
assert {w.speaker for w in engine.load_timeline(sid)["words"]} == {""}
def test_face_block_stores_mouth_series(env): # noqa: F811
_client, engine = env
class Meter:
def feed(self, rgb):
return 0.2
service = FaceService(engine, store=object(), tracker_factory=lambda _b=None: FakeTracker(), detector_factory=None,
reader=fake_reader, grabber=None, sizer=lambda _f: (1280, 720), mouth_factory=Meter)
engine.face = service
sid = seed_session(engine, duration=60)
set_cam(engine, sid, CAM)
assert service.step() is True
data = json.loads(engine.db.get("SELECT data_json FROM face_track WHERE session_id = ? AND idx = 0", sid)["data_json"])
assert len(data["mouth"]) == 180 and data["mouth"][0] == 0.2
# Sem medidor (store falso, sem YuNet): o bloco sai igual ao de antes, sem `mouth`.
service._mouth_factory = lambda: (_ for _ in ()).throw(RuntimeError("sem yunet"))
assert service.step() is True
data = json.loads(engine.db.get("SELECT data_json FROM face_track WHERE session_id = ? AND idx = 1", sid)["data_json"])
assert "mouth" not in data and data["frames"] == 180
# ---------------------------------------------------------------- legenda
def _dialogue(ass: str) -> list[tuple[float, float, str, str]]:
out = []
for line in ass.splitlines():
if line.startswith("Dialogue: 0,"):
parts = line.split(",", 9)
h, m, s = parts[1].split(":")
a = int(h) * 3600 + int(m) * 60 + float(s)
h, m, s = parts[2].split(":")
b = int(h) * 3600 + int(m) * 60 + float(s)
out.append((a, b, parts[3], parts[9]))
return out
def _ypos(text: str) -> int:
return int(re.search(r"\\pos\(\d+,(\d+)\)", text).group(1))
TALK = [Word(1.0, 1.3, "olha"), Word(1.35, 1.6, "isso"), Word(1.62, 1.9, "mano"),
Word(1.7, 2.0, "for", "other1"), Word(2.05, 2.4, "real", "other1"), Word(2.5, 2.9, "bro", "other1"),
Word(3.0, 3.3, "caiu"), Word(3.35, 3.7, "aqui")]
def test_caption_blocks_never_mix_speakers_and_overlap_only_across_lanes():
blocks = subtitles.caption_blocks(TALK, 3)
for group, _end in blocks:
assert len({w.speaker or STREAMER for w in group}) == 1
lanes = {"streamer": [], "other": []}
for group, end in blocks:
lanes[subtitles.lane(group[0].speaker)].append((group[0].start, end))
for spans in lanes.values(): # dentro da faixa, nunca dois blocos ao mesmo tempo
assert all(a1 <= a2 and e1 <= a2 + 1e-9 for (a1, e1), (a2, _) in zip(spans, spans[1:]))
# As duas faixas se sobrepõem (os dois falando juntos em 1,7–1,9 s).
(s_a, s_e), (o_a, o_e) = lanes["streamer"][0], lanes["other"][0]
assert o_a < s_e
@pytest.mark.parametrize("aspect", ["vertical", "horizontal"])
def test_build_ass_puts_the_other_speaker_below_in_another_color(aspect):
cfg = layout.merge({"format": {"aspect": aspect}, "caption": {"otherColor": "#00FF00"}})
ass = subtitles.build_ass(TALK, 0.0, 6.0, "", cfg)
assert "Style: CaptionOther," in ass and "&H0000FF00&" in ass
events = _dialogue(ass)
mine = [e for e in events if e[2] == "Caption"]
other = [e for e in events if e[2] == "CaptionOther"]
assert mine and other
y, oy = _ypos(mine[0][3]), _ypos(other[0][3])
assert y == layout.caption_y(cfg) and oy > y # embaixo
assert all("FOR" in e[3] or "REAL" in e[3] or "BRO" in e[3] for e in other)
assert not any("OLHA" in e[3] for e in other) and not any("BRO" in e[3] for e in mine)
# Os dois na tela ao mesmo tempo (1,7–1,9 s), em alturas diferentes.
assert any(a < 1.85 < b for a, b, _, _ in mine) and any(a < 1.85 < b for a, b, _, _ in other)
# Só o streamer: o ASS é exatamente o de antes (sem o estilo novo).
solo = [Word(w.start, w.end, w.word) for w in TALK if not w.speaker]
assert "CaptionOther" not in subtitles.build_ass(solo, 0.0, 6.0, "", cfg)
def _project(tmp_path, words, **over):
p = {
"schema": 1, "source": {"sessionId": 1, "lo": 0, "hi": 60}, "settings": {},
"cuts": [{"start": 0, "end": 20, "mode": None}],
"captions": {"enabled": True, "preset": "pop", "style": {}, "emphColor": "#22E36B",
"words": [editor.word_item(w) for w in words]},
"overlays": [], "progress": {"enabled": False, "color": "#FF7A1A", "height": 12},
"audio": {"volume": 1, "narration": [], "music": None, "sfx": []},
"cover": {"enabled": False, "t": 1, "text": ""},
}
p.update(over)
return validate(p, tmp_path)
@pytest.mark.parametrize("preset", editor.CAPTION_PRESETS)
def test_project_ass_two_lines_for_every_preset(tmp_path, preset):
p = _project(tmp_path, TALK)
assert p["captions"]["words"][3]["sp"] == "other1" and "sp" not in p["captions"]["words"][0]
p["captions"]["preset"] = preset
cfg = editor.effective_settings(layout.merge(), p)
events = _dialogue(editor_render.build_project_ass(p, cfg, ""))
mine = [e for e in events if e[2] in ("Caption", "Karaoke")]
other = [e for e in events if e[2] in ("CaptionOther", "KaraokeOther")]
assert mine and other
assert min(_ypos(e[3]) for e in other) > max(_ypos(e[3]) for e in mine)
for group in (mine, other): # na mesma linha, nunca dois eventos ao mesmo tempo
spans = sorted((a, b) for a, b, _, _ in group)
assert all(b1 <= a2 + 0.011 for (_, b1), (a2, _) in zip(spans, spans[1:]))
def test_hook_dodge_moves_both_lines_and_translation_follows_speaker(tmp_path):
hook = {"id": "hook", "kind": "hook", "text": "NAO ACREDITO", "start": 0, "end": 3, "y": 0.74, "size": 70,
"color": "#FFFFFF", "box": "#E11D48", "anim": "pop"}
p = _project(tmp_path, TALK, overlays=[hook])
cfg = editor.effective_settings(layout.merge({"dev": {"translation": True}}), p)
lines = [{"s": 1.0, "e": 1.9, "text": "olha isso mano", "pt": "olha isso", "speaker": "streamer"},
{"s": 1.7, "e": 2.9, "text": "for real bro", "pt": "sério mano", "speaker": "other1"}]
events = _dialogue(editor_render.build_project_ass(p, cfg, "", translation=lines))
cap_y = layout.caption_y(cfg)
mine = [e for e in events if e[2] == "Caption"]
other = [e for e in events if e[2] == "CaptionOther"]
trans = {e[3].split("}")[-1]: _ypos(e[3]) for e in events if e[2] == "Trans"}
# Gancho em cima da legenda nos 3 primeiros segundos: as duas linhas desviam juntas, a do colega embaixo.
y, oy = _ypos(mine[0][3]), _ypos(other[0][3])
assert y != cap_y and oy > y
hook_top = int(1920 * 0.74) - int(70 * 0.9)
hook_bottom = int(1920 * 0.74) + int(70 * 0.9)
assert y - 84 >= hook_bottom or oy + 60 <= hook_top
# Tradução de cada um embaixo da linha de quem fala, entre as duas a do streamer.
assert y < trans["olha isso"] < oy < trans["sério mano"]
def test_old_project_without_speaker_renders_like_before(tmp_path):
words = [Word(w.start, w.end, w.word) for w in TALK]
p = _project(tmp_path, words)
ass = editor_render.build_project_ass(p, editor.effective_settings(layout.merge(), p), "")
assert "CaptionOther" not in ass
assert {_ypos(e[3]) for e in _dialogue(ass)} == {layout.caption_y(layout.merge())}
def test_layout_validates_other_color_and_size():
assert layout.DEFAULTS["caption"]["otherColor"] == "#5CE1FF" and layout.DEFAULTS["caption"]["otherSize"] is None
ok = layout.validate({"caption": {"otherColor": "#ff00aa", "otherSize": 60}})["caption"]
assert ok == {"otherColor": "#FF00AA", "otherSize": 60}
assert layout.validate({"caption": {"otherSize": None}})["caption"]["otherSize"] is None
with pytest.raises(layout.LayoutError):
layout.validate({"caption": {"otherColor": "azul"}})
with pytest.raises(layout.LayoutError):
layout.validate({"caption": {"otherSize": 10}})
cap = layout.merge()["caption"]
assert subtitles.other_size(cap) == round(84 * 0.85)
assert subtitles.other_size({**cap, "otherSize": 50}) == 50
def test_project_rejects_bad_speaker(tmp_path):
p = _project(tmp_path, TALK)
p["captions"]["words"][0]["sp"] = "ninguém; drop"
with pytest.raises(editor.EditError):
validate(p, tmp_path)
# ---------------------------------------------------------------- tradução e juízes
def test_phrases_never_mix_speakers():
got = subtitles.phrases(TALK, with_speaker=True)
assert got == [(1.0, 1.9, "olha isso mano", "streamer"), (1.7, 2.9, "for real bro", "other1"),
(3.0, 3.7, "caiu aqui", "streamer")]
assert subtitles.phrases(TALK)[0] == (1.0, 1.9, "olha isso mano") # formato antigo continua
def test_translation_lines_get_speaker(env): # noqa: F811
client, engine = env
engine.judge = EnglishJudge()
sid = _english_session(engine)
words = [[281.0, 281.3, "No", "streamer"], [281.3, 281.6, "way", "streamer"], [281.6, 282.0, "bro.", "streamer"],
[282.1, 282.5, "Told", "other1"], [282.5, 283.0, "you.", "other1"]]
engine.db.run("UPDATE segments SET words_json = ? WHERE session_id = ? AND idx = 9", json.dumps(words), sid)
add_clip(engine, sid, 1, "candidate", 285, 270, 340)
engine.judge_clip(engine.db.get("SELECT * FROM clips WHERE id = 1"))
lines = json.loads(engine.db.get("SELECT translation_json FROM clips WHERE id = 1")["translation_json"])["lines"]
assert [(x["text"], x["speaker"]) for x in lines] == [("No way bro.", "streamer"), ("Told you.", "other1")]
# O juiz viu quem fala.
prompt = engine.judge.seen["judge"][1]
assert "] No way bro." in prompt and "[other1] Told you." in prompt and "Never attribute to" in prompt
# Tradução antiga (sem `speaker`) é refeita na próxima vez.
engine.db.run("UPDATE clips SET translation_json = ? WHERE id = 1",
json.dumps({"startS": 0, "endS": 1e6, "lines": [{"s": 1, "e": 2, "text": "x", "pt": "y"}]}))
before = len(engine.judge.translated)
engine.translate_clip(1)
assert len(engine.judge.translated) == before + 1
def test_judge_transcript_tags_only_when_someone_else_speaks():
plain = [Word(10.0, 10.3, "olha"), Word(10.4, 10.8, "isso")]
assert _transcript(plain, 0, 60, "pt", "Tfue") == "[10s] olha isso"
mixed = plain + [Word(11.0, 11.3, "bro", "other1"), Word(11.4, 11.8, "nice", "other1"), Word(12.0, 12.2, "ok")]
out = _transcript(mixed, 0, 60, "en", "Tfue").splitlines()
assert out[0].startswith("Each line is tagged") and "[Tfue]" in out[0]
assert out[1:] == ["[10s] [Tfue] olha isso", "[11s] [other1] bro nice", "[12s] [Tfue] ok"]
def test_voice_model_failure_waits_before_retrying(env): # noqa: F811
_client, engine = env
calls = []
def broken():
calls.append(1)
raise RuntimeError("sem rede")
engine.speakers = SpeakerService(engine, embedder_factory=broken)
sid = seed_session(engine, duration=60)
seg = engine.db.get("SELECT * FROM segments WHERE session_id = ? AND idx = 0", sid)
pcm, words = _block_audio(0.0)
for _ in range(3):
with pytest.raises(RuntimeError):
engine.speakers.index_block(seg, pcm, words)
assert len(calls) == 1 # não baixa o modelo a cada bloco
assert engine.load_timeline(sid)["words"][0].speaker == "" # sem voz indexada: como antes
+52
View File
@@ -0,0 +1,52 @@
# Clipador — dublagem em português (só no vídeo de revisão)
Pedido do dono (18/11/2026), para fontes em inglês: "quando ele estiver falando, a gente dubla em português. Baixa o
áudio dele, deixa um pouco baixo para escutar o som do carro, do ambiente do jogo [...] Depois, quando aprovar, fica o
original." Não é dublagem de filme: serve para a equipe entender o contexto. **Sem sincronia labial.**
## Como liga
Configuração do corte → aba Legenda → **"Dublagem em português (teste)"** (grupo `dev`, padrão desligado):
| Chave | Padrão | O quê |
| --- | --- | --- |
| `dev.dub` | `false` | liga a dublagem no vídeo de revisão |
| `dev.dubVoice` | `pt-br-antonio` | voz do streamer (Edge, masculina, online) |
| `dev.dubVoiceOther` | `kokoro-pm-alex` | voz das falas com `speaker: "other"` (Kokoro, offline) |
| `dev.dubDuck` | `0.25` | volume do áudio original enquanto a dublagem toca (0–1) |
Com `dev=False` (vídeo final, depois de aprovar) nada disto entra (`layout.dev_flags`). Só **vozes TTS prontas**: nunca
clonar a voz do streamer (terceiro sem consentimento); o painel nem lista vozes clonadas.
## Como funciona (`clipper/app/dub.py`)
1. Frases de `clips.translation_json` (`{s, e, text, pt, speaker?}`, tempo da sessão) → tempo de saída
(`editor.to_output`; frase dentro de trecho removido some). Frase partida no meio ("…deve dar" + "tudo certo.") do
mesmo falante vira uma fala só.
2. Uma fala por frase no serviço de voz: `POST /v1/synthesize` (`format: "wav"`, `speed: 1.05`). Cache em
`data/clipper/dub/` por (voz, velocidade, texto), já sem silêncio nas pontas, −16 LUFS e 48 kHz mono; apagado
o que fica 30 dias sem uso. Voz que falha → `pt-br-faber` (Piper, offline).
3. Encaixe (`fit`): começa no início da frase original, **em velocidade natural**, e pode escorrer até 1,5 s depois do
começo da próxima frase (que espera). O atraso é contado de cada frase original: não acumula. Só se nem assim couber
acelera até 1,2× e, se ainda não couber, corta com fade. Nunca duas falas juntas (80 ms entre elas).
4. Uma faixa WAV do trecho; no `editor_render.render_project` o original abaixa para `dubDuck` com rampa de 0,15 s só
onde há dublagem (vãos < 0,6 s ficam baixos, sem "bombear"). Fora das falas o áudio fica igual.
5. Nível: a dublagem fica 6 dB acima do volume médio do próprio corte (`volumedetect`, ~0,1 s), entre −20 e +3 dB.
A prévia do editor (`preview-render`) e o render da fila passam pelo mesmo caminho (`dub.for_engine(engine)`); a prévia
só sintetiza as frases que tocam nela. Serviço de voz fora do ar → o vídeo sai sem dublagem (aviso no log).
## Custo medido (18/11/2026, corte 259 do tfue, 54,5 s, 25 frases, NVENC)
| Render | Tempo |
| --- | --- |
| sem dublagem | 5,8 s |
| com dublagem, 1ª vez (síntese) | +29 a +41 s (~1,6 s por frase; 3 em paralelo; 6 não ajudam) |
| com dublagem, cache pronto | +0,3 s |
| prévia de 5 s, cache pronto | 1,2 s |
Conversa densa: o português sai bem mais longo que o inglês (frase de 4 s vira 6–7 s); no corte 259 9 das 25 falas
terminam cortadas com fade (4 s perdidos ao todo; aceleração média 1,08×). Áudio: fora das falas, idêntico ao original (−47,7 dB nos dois);
nas falas, a dublagem fica no nível do streamer (−29 dB contra −26/−34 dB do original).
Testes: `clipper/tests/test_dub.py` (TTS falso).
+210
View File
@@ -0,0 +1,210 @@
# Mapa de expressões do streamer (Clipador)
Data: 18/11/2026. Código: `clipper/app/reaction.py` (lógica pura) e `clipper/app/face.py` (MediaPipe/YuNet, API);
painel: `panel/src/components/clipper-face-map.tsx`. Testes: `clipper/tests/test_expressions.py`. Base anterior:
[`doc/FACE_BAKEOFF.md`](../FACE_BAKEOFF.md) e a seção "Rastreio de reação" do `clipper/README.md`.
Pedido do dono: "Está muito pouco, tem que colocar mais expressões. Às vezes ele não tem expressão facial, mas a
gente pega ele balançando… raiva, medo, alegria — está faltando para deixar mais completo o mapa de expressões."
Antes: 8 dos 52 blendshapes do MediaPipe viravam 5 canais (`smile`, `jaw`, `surprise`, `frown`, `brow`) + `motion`,
e 6 rótulos (risada, grito, susto, choque, confuso, raiva). Sem pose da cabeça e sem nada quando o rosto some.
## O que mudou
1. **Expressões novas** a partir dos blendshapes que já vinham (custo zero).
2. **Pose da cabeça**: o Face Landmarker agora devolve a matriz de transformação facial
(`output_facial_transformation_matrixes=True`) → yaw/pitch/roll por quadro (`face.pose_from_matrix`).
3. **Cabeça sem rosto**: quando o MediaPipe não acha o rosto (streamer de perfil), o YuNet (já usado para achar a
câmera; mesma licença MIT) roda **só nesse quadro** e dá a caixa da cabeça → posição/tamanho para o corpo.
4. **Corpo**: balançando, acenando, agitado, chegou perto, saiu do quadro (`reaction.body_moments`).
5. **Mapa**: expressão dominante + corpo por segundo (`reaction.expression_map`), na API e no modal do corte.
Nada disso mexe na **intensidade** do rosto (o sinal que vira pico, bônus na nota e corte de fonte `face`): os
canais novos só **rotulam** (pesos `extra_weights` = 0; ver "Por que os canais novos não viram pico"). A única
mudança nos picos é o **bocejo**, que deixou de contar como grito.
## Canais por segundo (campos novos da série, todos opcionais)
Série antiga (gravada antes) não tem estes campos: tudo continua funcionando (canal ausente = parado). Sem
migração de banco — os campos vão no `data_json` de `face_track` que já existia.
| Campo | De onde vem | Agregação no segundo |
|---|---|---|
| `brow_inner` | `browInnerUp` | máximo |
| `mouth_frown` | média `mouthFrownLeft/Right` (cantos da boca para baixo) | máximo |
| `squint` | média `eyeSquintLeft/Right` (olhos semicerrados) | máximo |
| `press` | média `mouthPressLeft/Right` (lábios apertados) | máximo |
| `stretch` | média `mouthStretchLeft/Right` (boca esticada para os lados) | máximo |
| `upper_lip` | média `mouthUpperUpLeft/Right` (lábio de cima levantado) | máximo |
| `pucker` | maior entre `mouthPucker` e `mouthFunnel` (boca em "O") | máximo |
| `yaw`, `pitch`, `roll` | matriz de transformação facial, graus (1 casa) | média |
| `shake`, `nod` | pernas de zigue-zague do yaw/pitch (histerese 8°/6°) na janela [t−0,5; t+1,5) s | contagem |
| `head` | fração dos quadros com a cabeça visível (rosto com pontos **ou** caixa do YuNet) | fração |
| `head_motion` | caminho da cabeça em tamanhos de cabeça, só entre quadros vizinhos (≤ 0,4 s) da mesma fonte, passo limitado a 1 | soma |
| `hsize` | altura da caixa do YuNet nos quadros sem pontos (fração do quadro inteiro) | média |
Blendshapes **mortos** no modelo do MediaPipe (medido: máximo ≤ 0,001 em 4 sessões, ~45 mil segundos):
`noseSneerLeft/Right`, `cheekSquintLeft/Right`, `cheekPuff`. Por isso nojo e raiva **não** usam o nariz: o lábio de
cima (`upper_lip`) faz o papel.
O z de cada canal novo é o mesmo esquema do `channel_z` (mediana + 1,4826 × MAD dos últimos 180 s do próprio
streamer, sem os últimos 10 s), mas o neutro usa **só os segundos que têm o campo**: numa sessão em que o serviço
foi atualizado no meio, os segundos antigos não viram um "neutro de zeros" (teste
`test_service_updated_mid_session_does_not_fake_new_expressions`). Menos de 30 segundos com o campo → z 0. Pisos
do desvio (`extra_floors`): `brow_inner` 0,10, `mouth_frown` 0,05, `squint` 0,06, `press` 0,08, `stretch` 0,06,
`upper_lip` 0,10, `pucker` 0,12, `head_motion` 0,15.
## Rótulos de expressão (`label`, `yawn_seconds`, `expression_map`)
"Ligado" = z ≥ 2 (`label_z`); "meio" = z ≥ 1. Ordem de decisão:
| Rótulo | Regra | Observação |
|---|---|---|
| **bocejo** | jawOpen ≥ 0,5 por ≥ 2 s seguidos e `squint` z ≥ 1 em algum deles | contexto (`yawn_seconds`); **não é reação**: o pico sai |
| **risada** | sorriso ligado; ou sorriso ≥ 0,5 com boca, franzido, sobrancelha **ou lábio de cima** ligado | lábio de cima: novo |
| **gargalhada** | risada com a cabeça ≥ 20° para trás do neutro dele (`head_back_deg`) | novo |
| **alegria** | (só no mapa) risada sem pico (sinal < 3), sem boca abrindo e sem dentes à mostra | novo |
| **susto** | sobrancelha ou olho arregalado + movimento | igual |
| **medo** | `brow_inner` ligado + `stretch` ligado (ou olho arregalado com a sobrancelha descendo) | novo; FACS AU1+AU20 |
| **grito** | boca ligada; ou franzido com a boca ≥ 0,2 | igual |
| **raiva** | franzido de boca fechada; **ou** `squint` + `press` ligados com o franzido "meio" | 2ª forma: nova |
| **nojo** | `upper_lip` ligado, boca abaixo de "meio" e sorriso < 0,3 | novo |
| **tristeza** | `mouth_frown` ligado + `brow_inner` "meio", sem `pucker` nem `stretch` ligados | novo |
| **espanto** | `pucker` ligado + sobrancelha ligada ou boca "meio" | novo |
| **choque** | olho arregalado parado | igual |
| **confuso** | sobrancelha levantada parada | igual |
| **tenso** | `press` + `squint` ligados (sem franzido) | novo (painel: "tensão") |
## Corpo/cabeça (`body_moments`)
Só contam segundos com a cabeça em ≥ 80 % dos quadros (`head_min`; série antiga: o rosto). Rastreio perdido
nunca vira movimento (achado do FACE_BAKEOFF: os maiores "picos" de movimento eram o rosto sumindo e voltando): o
passo entre quadros é limitado, quadros com buraco > 0,4 s entre eles não somam, pontos e caixa do YuNet não se
misturam, e a agitação exige a janela inteira com a cabeça visível (teste `test_lost_face_is_not_agitation…`).
| Rótulo | Regra |
|---|---|
| **balançando** | `shake` ≥ 3 pernas (vai-volta-vai de ≥ 8° no yaw em 2 s). Olhar para o lado e voltar = 2: não conta |
| **acenando** | `nod` ≥ 3 pernas (≥ 6° no pitch) sem balanço lateral |
| **agitado** | `head_motion` com z ≥ 2,5 em ≥ 3 de 5 s seguidos, todos com a cabeça visível |
| **chegou perto** | cabeça ≥ 18 % maior que o tamanho normal dele (rosto e caixa do YuNet, cada um contra o próprio neutro) |
| **saiu do quadro** | cabeça visível ≥ 3 s, até 2 s de transição parcial, depois ≤ 10 % por ≥ 3 s. **Só com o campo `head`** (série antiga não diz "saiu": lá o MediaPipe perdendo o rosto pareceria saída) |
## Onde aparece
- **API** `GET /v1/sessions/{id}/face`: cada segundo ganha `expr` (expressão do mapa) e `body` (movimento), além
dos campos novos; a resposta ganha `body: [{startS, endS, peakS, label, value}]`. Os picos (`moments`) podem vir
com os rótulos novos.
- **Juiz (analista)**: a linha "Rosto do streamer" traz até 2 movimentos do corpo no fim ("…; balançando a cabeça
em 1628s"). Com o rosto de perfil o tempo todo, antes não ia linha nenhuma; agora vai "rosto sem expressão legível
(de perfil ou longe; cabeça visível em 95% do trecho); saiu do quadro em 187s".
- **Painel**: `FaceSignal` (chip do corte) mostra os rótulos novos em português; o modal do corte ganhou o **Mapa de
expressões** (`clipper-face-map.tsx`): faixa com uma célula por segundo, cor por família (verde alegria/risada,
amarelo susto/espanto/medo, vermelho raiva/grito/nojo, azul tristeza/tensão, violeta confuso), faixa laranja do
corpo embaixo, legenda com segundos por expressão e os movimentos. Busca o trecho do corte; sem câmera ou serviço
antigo, não aparece.
## Calibração (dados reais, só leitura)
Banco copiado por `sqlite3.backup` (`mode=ro`); blocos `.ts` só lidos; MediaPipe rodado num script à parte com as
classes do `face.py` (matriz de pose ligada), quadros salvos fora do repositório. Cada regra foi conferida **olhando
os quadros** (folhas de contato de 8 quadros em volta de cada caso).
| Sessão | Canal | O que tem | Segundos com rosto (MediaPipe) |
|---|---|---|---|
| 8 | skipnho (PT), 1,7 h | 206 blocos, 14 cortes | 6009 de 6162 |
| 11 | skipnho (PT), 30 min | 59 blocos, 3 cortes | 1763 de 1770 |
| 7 | skipnho (PT), fim da live | 79 blocos ainda no disco (2217 s), 6 cortes | — |
| 15 | tfue (EN), gravando | 125 blocos, 27 cortes (13 descartados pela IA) | **486 de 3750** |
Achados que mudaram as regras:
- **Bocejo era o maior "grito"**: na sessão 8 os 5 trechos com jawOpen ≥ 0,6 por 3 s (1420, 3335, 3437, 3483 e
3659 s) eram todos bocejos (olhos fechados, braços esticando), com z 12–16. Gritos e exclamações abriram a boca
assim por 1 s (908, 2331 s). O bocejo ainda levanta o "sorriso" (cantos esticados): z 4–8. Regra de contexto
(≥ 2 s + olhos apertando) pegou os 5 (+1 em 5662 s) e nenhum grito de 1 s; o piscar não serve (o normal deste
streamer já é 0,5).
- **Nojo × risada**: a 1ª regra (lábio de cima sem boca aberta) deu 82 trechos na sessão 8; todos eram risada de
dentes à mostra (sorriso 0,91–0,97, que para ele já é quase o normal: z ~1). Com o sorriso < 0,3 exigido e o lábio
de cima contando para a risada: 5 trechos.
- **Mão no rosto engana a boca**: queixo apoiado, mão na boca e coçar o nariz (tique frequente do skipnho) fazem
`mouth_frown`, `stretch` e `pucker` subirem (911, 3984–3987, 4060, 5077, 5222 s). Não há sinal de oclusão no
MediaPipe (comparei os 52 blendshapes nesses segundos com o resto: nenhum separa). Tristeza passou a excluir bico
e boca esticada; o resto fica como limitação documentada (ver "Por que os canais novos não viram pico").
- **Cabeça para trás**: a 12° deu 16 "gargalhadas" na sessão 8, quase todas falsas (pose errada com a mão no rosto,
falando). A 20° fica a gargalhada real de 1566 s (24°, cabeça para trás com as mãos no rosto) e cai o resto, menos
uma: em 2572 s a cadeira estava **vazia** e o MediaPipe inventou um rosto no encosto (28°). Bebendo de lata também
vai a −25° (pitch), por isso "cabeça para trás" sozinha não vira rótulo — só com risada.
- **Balanço a 6 qps**: 28 eventos (δ 8°, ≥ 3 pernas) na sessão 8; nos quadros, eram cabeça indo e voltando
rindo, falando ou gesticulando — não dá para afirmar "não" literal a 6 qps (uma perna dura 1–2 quadros). Por isso o
rótulo é "balançando a cabeça", não "disse não". Olhar para o lado e voltar (1225, 2832 s) dá 2 pernas e fica fora.
- **Agitado**: 64 trechos na sessão 8; conferidos 6 — todos movimento de verdade (se inclinando para fora e
voltando, gesticulando, se espreguiçando).
- **Chegou perto**: razão tamanho/normal p99 1,15 e p99,9 1,21 (sessão 8); o 1,25 inicial não pegava nada. Com 1,18:
13 trechos na 8 (ex.: 2066 s, rosto colado na câmera), 1 na 15.
- **tfue de perfil (sessão 15)**: o MediaPipe acha rosto em **10 %** dos quadros (yaw mediano −44°: olha o monitor
ao lado da webcam); o YuNet acha a cabeça em **100 %** (180/180 em 4 blocos, score 0,89). Com a caixa do YuNet:
cabeça visível em 85 % dos segundos e **4 saídas do quadro**, que batem com os cortes: 187 s (corte 261 "Tfue Takes
a Bathroom Break Mid-Stream", 175–244), 577 s (corte 268 "…Waiting on a Bathroom Break", 518–581; tirou o fone e
levantou), 1236–1333 s (tela de "volto já" cobrindo a câmera) e 3572 s (corte 285). Sem a tolerância de 2 s de
transição (ele levanta em 1–2 s) só a 3ª aparecia. Raiva forte em 977/1011 s cai nos cortes 265/272 ("Base Is
Under Attack by Suspected Stream Snipers").
Resultado final (picos = `reaction_moments`; mapa = % dos segundos com rosto):
| Sessão | Picos antes → depois | Trocas de rótulo nos picos | Mapa (fora o neutro) | Corpo (eventos) |
|---|---|---|---|---|
| 8 | 251 → 254 (8 bocejos saíram, a seleção gulosa reescolheu vizinhos) | confuso→espanto 3, confuso→tristeza 1, risada→gargalhada 1 | risada 14,8 %, confuso 6,5, alegria 5,1, grito 1,5, susto 1,1, espanto 0,9, raiva 0,7, tristeza 0,3, bocejo 0,3, medo 0,2, nojo 0,1, tenso 0,1 | agitado 64, balançando 42, acenando 36, chegou perto 13 |
| 11 | 107 → 107 | confuso→tristeza 1, confuso→espanto 1, risada→gargalhada 1 | risada 19,0 %, confuso 6,0, alegria 5,3, susto 1,9, grito 0,9, espanto 0,7 | agitado 18, acenando 10, balançando 5 |
| 7 | 144 → 144 | confuso→espanto 3, grito→medo 1 | risada 12,9 %, alegria 8,3, confuso 6,9, grito 3,5, raiva 2,1, espanto 2,1 | acenando 10, balançando 7, agitado 4 |
| 15 | 22 → 22 | risada→gargalhada 1 | raiva 10,5 %, risada 4,7, confuso 2,9, grito 2,3 | agitado 9, saiu do quadro 4, balançando 3, acenando 3 |
(Sessões 7, 8 e 11 sem a caixa do YuNet na calibração — lá o rosto aparece em 97–99 % dos segundos; o "saiu do
quadro" delas vem do rosto sumindo e não entra na tabela.)
## Por que os canais novos não viram pico
Com peso na intensidade, cada canal novo criaria picos sozinho — e os falsos mais comuns (mão no rosto) caem
justamente nos canais da boca. A intensidade alimenta a nota dos cortes e a fonte `face`; mexer nela sem um conjunto
aprovado/rejeitado maior seria chute (nas sessões 7, 8 e 11 quase todos os cortes estão "ready", sem decisão do
dono). Então: `extra_weights` = 0 e os canais novos só **rotulam** o pico que as expressões antigas já acharam, e
pintam o mapa. Para ligar um canal na intensidade, é só dar peso em `ReactionParams.extra_weights` (testado no
código: `_signal_from_z`), depois de medir de novo.
## Custo (medido, mesma máquina: 32 threads, CPU; 6 blocos de 30 s por caso, rodados em sequência)
| Caso | Bloco antes | Bloco depois | `per_second` | JSON da série |
|---|---|---|---|---|
| skipnho (rosto em 100 % dos quadros) | 1775 ms (máx 2124) | 1773 ms (máx 2047) | 0,7 → 1,5 ms | 177 → 400 B/s |
| tfue de perfil (rosto em 1 %, só cabeça em 73 %) | 1238 ms (máx 1573) | 1721 ms (máx 2236) | 0,2 → 0,3 ms | 36 → 85 B/s |
- A matriz de pose não custa nada mensurável. O YuNet custa **5,3 ms por quadro sem rosto** (média de 20 255 quadros
da sessão 15) e só roda nesses quadros: streamer de frente não paga nada; de perfil, +0,5 s por bloco de 30 s
(ainda ~17× mais rápido que o tempo real).
- Banco: ~1,4 MB por hora de live em `face_track` (antes ~0,6 MB).
- Análise (`reaction_moments` + `body_moments` + `expression_map`) numa série de 1,7 h: ~1 s.
## Limitações conhecidas (não verificadas ou fora do alcance)
- **Mão no rosto** ainda pode virar tristeza/espanto/medo/raiva no mapa (ver calibração).
- **Rosto fantasma**: com a cadeira vazia o MediaPipe às vezes acha um rosto no encosto (sessão 8, 2567–2575 s,
presença 0,3–1,0 em segundos soltos); aparece no mapa como expressão. O "saiu do quadro" ainda pega a saída quando
há ≥ 3 s seguidos sem rosto.
- **Sim/não literal** não é medido (6 qps); "balançando/acenando" é o movimento, não a intenção.
- Serviço real rodando o código novo **não** foi testado (o serviço é do dono; só scripts com as classes e a suíte).
A caixa do YuNet dentro do `FaceService` foi coberta por teste com detector falso e medida por script com o real.
- Painel: só `tsc`; não abri no navegador.
- Nenhuma sessão com câmera escura/minúscula além da do tfue (rosto ~66 px de altura na fonte 1080p).
## Integração com o agente de Falantes (atividade da boca)
- Nada foi renomeado nem removido: `SECOND_FIELDS`, `FaceSample.blend`, `per_second`, `FaceSecond`,
`seconds_to_json/from_json` continuam iguais para quem já usa. Os campos novos estão em `EXTRA_SECOND_FIELDS`
(`to_json`/`from_json` percorrem `SECOND_FIELDS + EXTRA_SECOND_FIELDS`).
- `FaceSample` ganhou `pose` e `head` com padrão (`None`/`False`); quadro com `head=True` tem `present=False` e
**não tem blendshapes** — quem medir a boca deve continuar filtrando por `present`.
- `per_second` ganhou o parâmetro opcional `params` (só para os limiares do balanço). A atividade da boca para fala
pode usar `jaw`, `pucker` (bico/funil), `press`, `stretch`, `upper_lip` por segundo, que agora vêm na série.
- Ponto provável de conflito de merge: os dois agentes acrescentam campos ao fim de `FaceSecond` e uma tupla de
campos opcionais; manter as duas listas.
+139
View File
@@ -0,0 +1,139 @@
# Clipador — quem fala cada palavra (streamer × outra pessoa)
Pedido do dono (18/11/2026):
> Está atribuindo ao streamer a fala de outro jogador. A gente vai separar: a legenda do streamer em cima e a de
> outra pessoa abaixo, com outra cor, como se fossem duas pessoas conversando.
O áudio da live é um canal só: microfone do streamer, colegas no Discord e outros jogadores no chat de voz do jogo
saem misturados, e o Whisper devolve as palavras sem dizer de quem são. Na câmera só aparece o streamer: as outras
vozes **não estão no vídeo**.
## Como funciona
| Etapa | Onde | Quando | Custo medido |
| --- | --- | --- | --- |
| Trechos de fala → impressão de voz (256 números) + volume (dBFS) | `speakers.index_block` + `voiceprint.py` | análise de cada bloco, logo depois do Whisper (thread da análise) | **0,19 s de CPU por bloco de 30 s** (máx. 0,67 s) |
| Movimento da boca do streamer, quadro a quadro | `face.MouthMeter` (YuNet) | rastreio do rosto de cada bloco (thread `face`), nos mesmos quadros já decodificados | **+0,5 s de CPU por bloco** |
| Vozes da sessão, qual é o streamer, rótulo de cada trecho | `speakers.build_model` | sob demanda (`load_timeline`, editor), em cache até chegar bloco novo | **0,05 s** (1 061 trechos, 72 min); 0,07 s com 6 400 trechos (~7 h) |
Por que assim: a parte cara (rede de voz) roda uma vez por bloco, em segundo plano, junto com o áudio que a análise já
decodificou; o agrupamento precisa da sessão inteira (as vozes só se separam com muitos trechos) e custa centésimos,
então é refeito na leitura — e o rótulo melhora sozinho conforme a live avança, sem reescrever nada no banco.
1. **Trechos**: palavras seguidas (vão ≤ 0,25 s), até 3 s, e fecha no fim de frase (`. ? !`) — numa conversa a vez
troca quase sempre ali, mesmo sem pausa. Trecho ≥ 0,5 s vira impressão de voz (com 0,1 s de folga de áudio).
2. **Vozes**: os trechos ≥ 1 s são agrupados pela voz (aglomerativo, cosseno ≥ 0,5 entre os centros; até 600
trechos espalhados na sessão). Grupo com ≥ 15 s de fala é uma voz. Funciona com qualquer número de colegas.
3. **Qual voz é o streamer** — duas provas:
- **boca**: a voz cujos trechos coincidem com mais movimento da boca dele na webcam (média de muitos trechos;
t de Welch ≥ 3 contra a segunda voz);
- **volume**: o microfone dele vem mais forte que o Discord/jogo (mediana ≥ 3 dB acima da segunda voz).
Concordam ou só uma decide → ela. **Discordam ou nenhuma decide → ninguém vira "outro"** (tudo como do
streamer, o comportamento de antes). Uma voz só (streamer sozinho) → nada muda.
4. **Cada trecho** vai para a voz mais parecida. Só vira `otherN` com folga: cosseno com a outra voz ≥ 0,30 e ≥ 0,10
acima do cosseno com o streamer (+0,05 nos dois para trecho < 1 s). Senão, streamer. Trecho curto sem impressão
herda o rótulo do trecho vizinho (até 1 s); longe de tudo, streamer.
`GET /v1/sessions/{id}/speakers` mostra as vozes, qual é o streamer e por quê. Opção `speakers` (`intel.opts`,
padrão ligada) desliga tudo.
## Dados
- `scoring.Word` ganhou `speaker: str = ""` (no fim, opcional): `""`/`"streamer"` = streamer; `"other1"`,
`"other2"`… = outra pessoa (numeradas pela quantidade de fala na sessão; a numeração pode mudar com a live).
- `segments.words_json` aceita o 4º elemento `[início, fim, texto, falante]`; o formato antigo (3) continua valendo e é
o que se grava hoje (`speakers.dump_words`). Falante gravado no 4º elemento tem prioridade sobre a atribuição.
- Tabela `voice_chunks (session_id, idx, data_json, updated_at)` — `{model, chunks: [{s, e, db, v}]}`, `v` = vetor em
float16/base64 (~5 KB por bloco, ~0,6 MB por hora). Criada com `CREATE TABLE IF NOT EXISTS` ao subir o serviço,
**fora** da lista de migrações: a v14 é de outra frente e ainda não está nesta branch; numa posição fixa da lista ela
viraria a v14 aqui. Quem integrar pode movê-la para a v15.
- `face_track.data_json.mouth`: série por quadro (6 qps) do movimento da boca; blocos antigos não têm (a prova da boca
só vale para blocos rastreados depois desta versão).
- Projeto do editor: cada palavra ganha `sp` (só quando atribuída). Projetos antigos, sem `sp`, saem iguais.
- Tradução (`clips.translation_json`): cada linha tem `speaker`; as frases nunca misturam falantes. Tradução antiga,
sem `speaker`, é refeita na próxima chamada.
## Legenda
- Duas faixas: a do streamer na posição normal; a de outra pessoa **logo abaixo** (`caption.otherColor`, padrão
`#5CE1FF`; `caption.otherSize`, padrão vazio = 85 % de `size`). A palavra falada continua com `highlight`.
- Um bloco nunca mistura falantes; "nunca dois blocos ao mesmo tempo" vale dentro de cada faixa. Os dois falando
juntos = as duas linhas na tela, cada uma com `\pos` próprio (o libass não empilha).
- Sem espaço embaixo (horizontal, legenda a 85 % da altura), a linha do streamer **sobe** o necessário: a ordem nunca
inverte. O gancho (`hook_dodges`) desvia as duas linhas juntas.
- Tradução de desenvolvimento (`dev.translation`): o português de cada um fica embaixo da linha de quem fala (a do
streamer entre as duas linhas).
- Estilos `CaptionOther`/`KaraokeOther` só entram no ASS quando o corte tem outra pessoa: corte só com o streamer sai
byte a byte igual (conferido pelo teste dourado do vertical).
- Painel: a configuração do corte tem "Fala de outra pessoa" (cor e tamanho); o editor marca o falante de cada
parágrafo da transcrição e o botão **Outra pessoa / É o streamer** corrige as palavras selecionadas; a prévia
(canvas) desenha as duas linhas; o modal mostra quem fala em "O que falam".
## Juízes
`judge._transcript`: com outra pessoa no trecho, cada linha diz quem fala (`[Tfue] …` / `[other1] …`) e vem a nota
"Never attribute to Tfue what someone else said" (em português nos prompts em português). Sem outra pessoa, a
transcrição sai igual à de antes.
## Licenças (conferidas em 18/11/2026)
| Peça | Licença | Onde conferi |
| --- | --- | --- |
| **WeSpeaker ResNet34-LM** (`voxceleb_resnet34_LM.onnx`, commit `f0c48c2…` do Hugging Face) — os PESOS | **CC-BY-4.0** (uso comercial permitido, pede atribuição: "WeSpeaker, wenet-e2e") | cartão do modelo `Wespeaker/wespeaker-voxceleb-resnet34-LM` (`license: cc-by-4.0`) e `docs/pretrained.md` do WeSpeaker ("o modelo segue a licença do conjunto de treino"; VoxCeleb = CC BY 4.0) |
| Código de fbank | nosso (reimplementação em numpy; conferida contra o `torchaudio.compliance.kaldi.fbank`: diferença máx. 0,00016) | — |
| YuNet (boca) | MIT (já no projeto) | `models.lock.json` |
Não usados: **pyannote**, **SpeechBrain ECAPA**, **NeMo TitaNet**, **Resemblyzer** — todos pedem PyTorch, que não está
no venv do Clipador (o modelo escolhido roda no `onnxruntime` que já existe). **3D-Speaker CAM++** (código
Apache-2.0): a página do modelo no ModelScope não abriu para conferir a licença dos pesos, então ficou de fora.
Nenhum pacote novo foi instalado; o modelo (26,5 MB) entra no `models.lock.json` com sha256 e é baixado pelo
`setup.ps1` ou sob demanda (`ModelStore`).
## Qualidade medida — sessão 15 (twitch.tv/tfue, inglês, dois colegas no Discord)
Medido só lendo o banco e os blocos da pasta principal (cópia em memória), 144 blocos (~72 min), com o código desta
versão.
**A boca sozinha não resolve nesta live.** Webcam pequena (rosto ~45×66 px no 1080p) e streamer de PERFIL olhando o
monitor:
- MediaPipe Face Landmarker (o rastreio atual): rosto em ~4 % dos quadros na maioria dos blocos (0 a 58 %), e
`jawOpen` = 0,00 mesmo nos quadros com rosto e falando. Recorte justo no rosto: 26–69 % de presença, `jawOpen`
ainda ~0,01. Inútil para falante.
- YuNet + recorte da boca (`MouthMeter`): rosto em **99 %** dos quadros. Mas por trecho o sinal separa pouco: AUC
**0,55–0,64** (boca do streamer × boca nos trechos dos colegas). Somando muitos trechos aponta a voz certa
(média 0,188 × 0,167 × 0,159), com t = 2,3 contra a 2ª voz — abaixo do limiar 3: aqui quem decide é o volume.
Em câmera de frente e maior a boca deve pesar mais; não foi medido.
**A voz separa bem**:
- 3 vozes (358 s, 313 s e 244 s de fala em trechos ≥ 1 s); cosseno entre os centros 0,26–0,33 (vozes bem distintas).
- Volume: streamer −27,3 dBFS × −34,8 e −37,6 dBFS dos colegas → **+7,5 dB**; o streamer é achado pelo volume desde os
primeiros 5 minutos.
- 1 061 trechos: 916 com impressão; **514 viraram outra pessoa**, 73 ficaram como do streamer por dúvida (a voz mais
parecida era a de um colega, mas sem a folga exigida); 145 curtos herdam o vizinho.
- **Conferência visual às cegas** (30 trechos ≥ 1,2 s sorteados, 10 de cada voz, embaralhados; olhei 8 quadros da boca
de cada um sem saber a voz): 20 casos claros.
- boca parada o trecho todo (não é ele): **9 de 9** rotulados como outra pessoa;
- boca mexendo (seria ele): **7 de 11** rotulados streamer; os 4 restantes são todos da mesma voz de colega
(`other2`) e, revistos a 24 qps, mostram lábios entreabertos sem articular — duvidosos. Outros 2 trechos dessa
mesma voz mostram a boca dele fechada enquanto ela fala, e ela é 10 dB mais baixa que o microfone dele: tratei
como colega. Esta conferência é fraca (rosto de perfil, 45 px); não há gabarito de áudio.
- **Estabilidade** (streamer × outra pessoa, comparando com o modelo da sessão inteira): com 5 min de live, 52/62
trechos iguais (84 %); 10 min, 129/132 (98 %); 20 min, 287/292 (98 %); 40 min, 555/563 (99 %).
- Exemplo real (5:30–5:50): "How many drills is the gallery?" → streamer; "Gallery is three." → `other1`;
"I think we need five. I have three so I think you should bring two." → `other1`; "I got one code tablet
completed." → streamer (antes do corte por fim de frase, "I got one code" ia junto com o colega).
## Limites conhecidos
- Troca de falante no meio de um trecho sem pausa nem pontuação fica com um rótulo só.
- Nos primeiros minutos (menos de 15 s de fala por voz) não há atribuição: tudo como do streamer.
- Vozes do jogo (NPC, anúncio) também viram "outra pessoa" — o que é verdade (não é o streamer).
- Projeto do editor guarda o `sp` de quando foi criado; projeto antigo (sem `sp`) sai como antes. Nova avaliação dos
juízes refaz o projeto da IA já com falantes.
- A série da boca só existe em blocos rastreados por esta versão; a do volume vale para qualquer bloco com fala.
- Modelo de voz indisponível (sem rede no 1º uso, arquivo corrompido): os blocos analisados nesse tempo ficam sem
impressão de voz (não são refeitos depois) e o serviço tenta carregar de novo a cada 5 min.
- Tudo isso só vale depois de reiniciar o serviço (o código novo não roda no Clipador que está no ar).
+332
View File
@@ -0,0 +1,332 @@
# Clipador — pesquisa: três papéis de IA, vídeo como "linha do tempo JSON" e juiz de contexto (18/11/2026)
> Pesquisa + proposta. **Nada foi implementado.** Números de custo marcados com "≈" são estimativas a partir das
> fórmulas oficiais e do tamanho real dos prompts; números marcados com "medir" ainda não existem.
## 1. Pedido do dono
1. **Três papéis**, cada um com provedor + modelo próprios e instruções editáveis no painel:
ANALISTA (o que aconteceu) → EDITOR (vira corte? trecho, título, legenda) → **JUIZ** (novo: o corte tem
CONTEXTO e faz sentido sozinho? "não trazer corte sem sentido", principalmente em inglês).
2. **"Ler o vídeo como JSON"**: transformar o vídeo em uma linha curta por cena/instante, barata em tokens, e
descobrir o que melhora a nota/decisão de corte.
## 2. Ponto de partida (lido no código e no banco, 18/11/2026)
- Frames: `media.grab_frame` gera JPEG **768×432** (`scale=768:-2`, `-q:v 4`). Varredura: 7 frames por janela de
180 s (`intel.SCAN_MAX_FRAMES`); analista: 6–8 frames do trecho (`worker.judge_clip`); editor: só texto quando há
análise. Os mesmos instantes podem ser enviados duas vezes (varredura e depois analista).
- Prompts de sistema (EN): analista ≈ 670 tokens, editor ≈ 1.020, varredura ≈ 810 (+ schema 160–250). Perfil do jogo
ROB RUN em inglês: 4.156 caracteres (≈ 1.000 tokens) em **toda** chamada.
- Claude pela CLI: imagens via ferramenta `Read` (uma leitura por imagem = mais turnos); custo fixo medido da CLI
≈ 2,6 mil tokens por chamada (comentário em `judge._claude`). Codex e Gemini: fixo **não medido**.
- Volume real: sessão 15 (tfue, ROB RUN, 1h22) teve **35 candidatos** (≈ 25/h; 18 descartados pela IA); sessão 7
(5h07) teve 81 (≈ 16/h). Ou seja, **os candidatos pesam mais que a varredura** (2 chamadas × 15–25/h contra 20/h).
- Exemplo do problema que o JUIZ deve pegar (corte 291, mantido com nota 7,5): o próprio analista escreveu
*"The messages do not clearly establish the outcome of the encounter"* — o corte não tem o desfecho, e passou.
## 3. O que o mercado faz (sinais conhecidos)
| Ferramenta | O que se sabe dos sinais | Fonte |
| --- | --- | --- |
| **Opus Clip** (ClipAnything) | Multimodal (visual, áudio, "sentimento"); nota de viralidade 0–99 com 4 eixos: **Hook** (a abertura prende e tem a ver com o tema), **Flow** (segue lógico até uma **conclusão satisfatória**), **Value** (emoção/conexão), **Trend**; + relevância ao prompt. Fórmula não publicada. | help.opus.pro (sem data) |
| **Eklipse** "Gameplay Intelligence" (Premium desde 01/06/2026) | Abandonou "gatilho + janela" (1 kill/pico de chat/pico de áudio = 1 corte). Agora pontua candidatos por 4 sinais juntos: **eventos de estado do jogo**, **composição do áudio** (voz × jogo × fundo), **densidade de ação na tela** e **continuidade** (começo de sequência × lance isolado). Lê o estado visível do jogo para decidir início/fim: **mantém o setup quando o momento depende dele** e corta o tempo morto. Roteia por gênero pela categoria. Camada de "arco narrativo" (escalada em voz, chat e jogo) para conteúdo falado. Antes: OCR/detecção de objeto no HUD e **kill feed**; HUD tapado pela câmera = não detecta. | blog Eklipse (26/05/2026); páginas de comparação/ajuda |
| **Twitch Auto Clips** | Out/2025: "empolgação positiva, conversa engraçada". Mai/2026: **atividade do chat, inflexão da voz e eventos na tela**; corte já legendado. Dados de teste: 50% → 85% dos streamers com um corte para postar (alegação da empresa). | TwitchCon San Diego (17/10/2025) e Rotterdam (30/05/2026) |
| **YouTube** "Live recap"/destaques | Escolhe momentos da live encerrada e gera Shorts para o criador publicar (experimental). Sinais não publicados. | Made on YouTube (set/2025) |
| **StreamLadder ClipGPT** | Até 10 cortes por VOD + "Virality Score"; terceiros citam áudio + engajamento do chat (não confirmado pelo fornecedor). | streamladder.com; comparativos 2026 |
| **Klap / Vizard** | Generalistas, bons em conteúdo falado; Klap publica os fatores da nota 0–100. Não específicos de jogo. | comparativos 2026 |
| Medal, Powder, Athenascope | Não achei fonte atual confiável sobre os sinais (Medal aparece como captura manual em comparativo). Fora da análise. | — |
**Lições para nós:** (1) pontuar com vários sinais ao mesmo tempo, não um gatilho; (2) **estado do jogo pelo HUD**
(texto na tela) é o sinal visual mais barato e confiável; (3) "continuidade/arco" e "conclusão satisfatória" são
exatamente o que falta hoje — é o papel do JUIZ; (4) o corte precisa **incluir o setup quando o momento depende
dele** (Eklipse) — é a principal correção que o juiz pode pedir.
## 4. Como ler vídeo barato
### 4.1 Custo de imagem por provedor (fórmulas oficiais, consultadas em 18/11/2026)
| Provedor | Fórmula | 1 frame 768×432 (hoje) | Mosaico 4×2 de 384×216 (1536×432) |
| --- | --- | --- | --- |
| OpenAI (Codex) | patches de 32 px: `ceil(w/32)·ceil(h/32)` × multiplicador (1,2 na família gpt-5.x/gpt-6-astra; **assumido 1,2** para gpt-6-luna) | 24·14 = 336 × 1,2 ≈ **404** | 48·14 = 672 × 1,2 ≈ **807** (8 frames) |
| Anthropic (Claude) | patches de 28 px: `ceil(w/28)·ceil(h/28)`; teto 1.568 (padrão) / 4.784 (alta resolução, 4.7+) | 28·16 = **448** | 55·16 = **880** (8 frames) |
| Google (Gemini 3/4) | fixo por imagem conforme `media_resolution`: padrão **1.120**, low 280, medium 560 | **1.120** (a CLI usa o padrão) | **1.120** (8 frames) ou 280 em low |
| Gemini vídeo nativo | 1 fps padrão; **70 tokens/frame** (low/medium), 280 (high); áudio 32 tokens/s; ≈ 100 tokens/s no total; `fps` e `start/end_offset` configuráveis (API) | — | corte de 90 s ≈ 9 mil tokens com áudio (fps 0,5 ≈ 6 mil) |
Hoje, por hora (tfue, ~25 candidatos/h, Codex): imagens ≈ 20×7×404 + 25×8×404 ≈ **138 mil tokens**. No Gemini
(1.120/imagem) o mesmo fluxo daria ≈ **381 mil** — o mosaico ou o texto cortam isso em 4–8×.
### 4.2 Técnicas (o que a pesquisa mostra)
- **Mosaico/grade de frames numa imagem só.** IG-VLM (2024) mostrou que uma grade de frames numa imagem deixa um
modelo de imagem entender vídeo sem treino; TS-LLaVA (2024): 16 frames em 4 grades > frames soltos com o mesmo
número de tokens. **"Paying for Too Many Tokens?" (30/09/2026, AACL 2026): uma grade 2×8 de frames escolhidos por
mudança de plano chegou perto do vídeo inteiro (κ dentro de 0,05) com ~15% do custo**, e "só texto" muitas vezes
já bastava. Limite: grade perde detalhe fino (texto pequeno do HUD) → cobrir com OCR local.
Para nós: ffmpeg já faz (`select` + `scale=384:-2` + `tile=4x2`), sem dependência nova; no Claude vira 1 `Read`
em vez de 8.
- **Amostrar por mudança, não por relógio.** Em gameplay a câmera é contínua: corte de plano quase só acontece em
menu, loading, morte, teleporte, troca de câmera — justamente eventos úteis. Proposta híbrida: nova entrada quando
muda a cena (ffmpeg `scdet`/`select='gt(scene,x)'`, ou PySceneDetect, BSD-3) **ou** a cada no máximo 8 s, **ou**
num pico de chat/áudio/rosto, **ou** numa pausa da fala. PySceneDetect não publica velocidade; medir.
- **"Legenda primeiro, raciocínio depois" (caption-then-reason).** LLoVi (EMNLP 2024): um legendador descreve
pedaços curtos e um LLM raciocina só sobre o texto — bateu o estado da arte em vídeo longo. HiVid (fev/2026):
modelos de vídeo dão nota subjetiva ruim no zero-shot; janela deslizante local + resumo global funciona melhor.
É exatamente a "linha do tempo JSON".
- **OCR do HUD** (o sinal que o Eklipse usa): RapidOCR/PaddleOCR PP-OCRv5 (**Apache-2.0**), recortes fixos por jogo
(canto do kill feed, faixa central de "MISSION PASSED"/"WASTED", estrelas de procurado, dinheiro). Só registrar
texto **novo**.
- **Eventos de áudio**: YAMNet (**Apache-2.0**, 521 classes AudioSet: *Laughter, Screaming, Shout, Gunshot/gunfire,
Explosion, Siren, Applause, Cheering, Music*; saídas não calibradas → limiar por classe) roda em CPU sobre o mesmo
áudio 16 kHz do Whisper. PANNs (código MIT; pesos **CC-BY-4.0** segundo os ports — atribuição, permitido) como
alternativa mais precisa.
- **VLM local pequeno para a frase da cena** (licença dos PESOS conferida):
| Modelo | Licença dos pesos | Situação para o dono |
| --- | --- | --- |
| Qwen3-VL-2B/4B-Instruct | Apache-2.0 (card oficial do 4B; 2B por espelhos — conferir o LICENSE oficial) | **OK — melhor candidato** (entende jogo, segue JSON) |
| SmolVLM2 2.2B / 500M / 256M | Apache-2.0 (card oficial) | OK — leve, feito para vídeo, ~5 GB VRAM no 2.2B em fp16 |
| Florence-2 base/large | MIT | OK — rápido (~1 s/img numa T4), mas legenda genérica ("a car on a street"); bom para OCR/objetos |
| Moondream 2 | Apache-2.0 | OK (não testado aqui) |
| Moondream 3 (preview) / 3.1 | BSL 1.1 com concessão / "Moondream Model License" | **Evitar** (licença própria com restrição) |
| Qwen2.5-VL-**3B** | Qwen Research License = **não comercial** | **Proibido** |
| Gemma 3 | termos próprios do Gemma (não verificado nesta pesquisa) | Evitar por precaução |
- **Máquina local**: `nvidia-smi` em 18/11/2026 → **RTX 2060 SUPER, 8 GB, 7,1 GB já ocupados** naquele momento
(Whisper e o que mais estava aberto). VRAM é o gargalo: VLM só quantizado (Qwen3-VL-2B Q4 ≈ 1,5–2 GB via
llama.cpp/Ollama, ambos MIT) ou Florence-2-base (< 1 GB). Turing não tem bf16 → fp16/int4.
| Etapa local | Onde roda | Tempo por minuto de live (estimativa — medir) |
| --- | --- | --- |
| Mudança de cena (ffmpeg `scdet` em 160 px, NVDEC) | GPU decode/CPU | 1–3 s |
| OCR de 2–4 recortes do HUD a cada 2 s | CPU (RapidOCR ONNX) | 1–3 s |
| YAMNet em janelas de 0,96 s | CPU | < 1 s |
| Frase da cena: ~8–10 keyframes/min, Qwen3-VL-2B Q4 | GPU | 5–15 s |
| Rosto, chat, fala, volume | já existem | 0 |
Total ≈ 10–20 s por minuto de live (abaixo do tempo real), concorrendo com o Whisper pela GPU.
## 5. A "linha do tempo JSON" (proposta)
**Formato:** JSON Lines, uma linha por cena/instante, chaves curtas (a legenda das chaves vai **uma vez** no prompt de
sistema), segundos inteiros da gravação (o editor devolve `start_s/end_s` nessa régua), campos vazios omitidos.
| Campo | Conteúdo | De onde vem |
| --- | --- | --- |
| `t`, `d` | início (s da gravação) e duração da entrada | local: segmentação híbrida (cena / ≤ 8 s / pico / pausa da fala) |
| `k` | só quando houve corte de plano: `"cut"` | local: `scdet` |
| `v` | o que está na tela / ação, **≤ 12 palavras**, no idioma da fonte | VLM local (F3) **ou** a própria varredura escreve a partir do mosaico (F1) |
| `hud` | texto novo do HUD (`"WANTED 3★"`, `"-$1,200"`, `"MISSION PASSED"`) | local: OCR nos recortes do perfil do jogo |
| `face` | expressão do streamer + intensidade 0–1 (`"laugh.7"`, `"shock.8"`, `"talk"`) | local: YuNet + MediaPipe (`reaction.summarize`) |
| `aud` | eventos de áudio acima do limiar (`gunshot`, `laughter`, `siren`…) | local: YAMNet |
| `lvl` | volume relativo ao normal da live, 0–9 | local: RMS já calculado |
| `sp` | fala **literal** do trecho (até ~25 palavras) | local: Whisper (palavras com tempo) |
| `chat` | `"msgs\|emote×n\|frase mais repetida"` | local: `scoring`/emotes já calculados |
**Exemplo inventado — 60 s de ROB RUN (tfue, inglês)** — 1.681 caracteres ≈ **470 tokens**:
```jsonl
{"win":[4521,4581],"game":"ROB RUN","cam":"bottom-left","src":"en"}
{"t":4521,"d":6,"v":"Tfue on foot at beach house, aims rifle at masked player","hud":["WANTED 2★"],"face":"talk","aud":["music"],"lvl":3,"sp":"yo yo we're just passing through bro, we're friendly","chat":"6|LUL×2|he's lying"}
{"t":4527,"d":8,"v":"masked player points shotgun back, both standing still","face":"smile.4","lvl":3,"sp":"I literally only have an action camera, I swear","chat":"9|KEKW×3|action camera LMAO"}
{"t":4535,"d":7,"v":"teammate's car pulls up behind masked player","aud":["engine"],"lvl":4,"sp":"don't shoot, don't shoot, it's my first day in the city","chat":"8|ICANT×2|first day 💀"}
{"t":4542,"d":4,"k":"cut","v":"masked player fires, Tfue ragdolls to the ground","hud":["YOU ARE DOWN","-$1,200"],"face":"shock.8","aud":["gunshot","shout"],"lvl":8,"sp":"WHAT? BRO WHAT","chat":"21|OMEGALUL×7|LMAOOO"}
{"t":4546,"d":6,"v":"downed view, masked player loots Tfue's bag","hud":["REVIVE 0:12"],"face":"laugh.7","aud":["laughter"],"lvl":7,"sp":"he took my camera! he took my action camera!","chat":"26|KEKW×9|he's cooked"}
{"t":4552,"d":8,"v":"teammate runs over, revives Tfue behind car","hud":["REVIVED"],"face":"talk","lvl":5,"sp":"that guy came out of nowhere, he's gotta be hacking","chat":"14|Clueless×3|skill issue"}
{"t":4560,"d":9,"v":"Tfue drives car along beach road, police car behind","hud":["WANTED 3★"],"aud":["siren","engine"],"lvl":6,"sp":"cops cops cops, go go go","chat":"10|monkaS×2|"}
{"t":4569,"d":12,"v":"car chase through Looty Bay streets, crashes into fence","aud":["crash","siren"],"lvl":7,"face":"focus","sp":"I can't see anything, where are we going","chat":"7||"}
```
Lendo só isso, qualquer modelo de texto vê setup (4521–4541: implora paz, "action camera"), gatilho (4542: tiro),
desfecho (4546: rouba a câmera — a piada fecha) e a cauda que **não** pertence ao corte (4560+: perseguição).
É o que faltou no corte 291.
**Tokens por minuto:** ≈ 450–550 com fala contínua (tfue), ≈ 250 em minuto calado. Comparação da **evidência**
(sem prompt de sistema nem perfil):
| Chamada | Hoje (frames + transcrição + chat) | Linha do tempo | Cobertura visual |
| --- | --- | --- | --- |
| Varredura (3 min + 2 min de volta) | 7×404 + ~1.000 + ~400 ≈ **4.200** | 3 min × 500 + volta resumida ~400 ≈ **1.900** | 1 frame/25 s → 1 entrada/6–8 s + áudio + HUD |
| Analista (janela ~225 s, 8 frames) | 8×404 + ~800 + ~350 ≈ **4.400** | 3,75 min × 500 ≈ **1.900** (+ mosaico opcional 807) | 1 frame/20 s → 1 entrada/6–8 s |
| No Gemini (1.120/imagem) | varredura ≈ 9.200 · analista ≈ 10.100 | igual acima | — |
## 6. Arquitetura recomendada dos três papéis (+ varredura)
```
blocos .ts ─► LOCAL: cena/HUD/áudio/rosto/fala/chat ─► timeline.jsonl (por sessão, reaproveitada por todos)
VARREDURA (texto [+ 1 mosaico/3 min]) ─► candidatos ─┐
chat/áudio/rosto ─► candidatos ──────────────────────┴► ANALISTA ─► EDITOR ─► (manteve e nota ≥ mínima) ─► JUIZ
├ aprova ─► render
├ ajusta ─► 1 nova checagem ─► render | descarta
└ reprova ─► "descartado pelo juiz" (forçável)
```
| Papel | Vê imagem? | Entrada | Saída JSON (chaves em inglês; `pt` para o painel em fonte EN) |
| --- | --- | --- | --- |
| **Varredura** | opcional: 1 mosaico 4×2 por janela | timeline da janela + memória + perfil enxuto (`clip_worthy`, `jargon`) | como hoje (`moments`, `summary`) + em F1 **`lines`: a frase `v` de cada keyframe do mosaico**, que vai para a timeline e é reaproveitada |
| **Analista** | opcional: 1 mosaico do trecho (só se `v` faltar ou confiança baixa) | timeline da janela (volta até `backtrackS`) + perfil enxuto + rosto | campos atuais + **`setup_s`** (onde começa o contexto necessário), **`trigger_s`**, **`payoff_s`** e `beats` (≤ 4 frases curtas: setup → gatilho → desfecho) |
| **Editor** | não | análise + timeline **só do trecho** ± 15 s + perfil (hashtags, jargão) | atual (`keep`, `score`, `start_s`, `end_s`, `title`, `caption`, `hashtags`, `reason`) + **`context_line`** opcional (≤ 8 palavras na tela nos 2 primeiros segundos, ex.: "Tfue tries to talk his way out of a robbery") |
| **Juiz** | não | **só o que o espectador verá**: timeline de `start_s..end_s` + 20 s antes marcados "fora do corte" + título/legenda/`context_line` + "história pretendida" (`what_happened` do analista) + 1 linha do jogo | `viewer_summary` (o que um espectador frio entende, escrito ANTES dos checks), `checks`, `fix`, `confidence`, `reason`, `pt` |
**Schema do JUIZ (saída):**
```jsonc
{
"viewer_summary": "Tfue begs a robber to spare him, gets shot anyway and loses his 'action camera'.",
"checks": { // cada um: ok + instante de evidência + motivo curto
"setup": {"ok": true, "t": 4521, "why": "plea starts at 4521"},
"payoff": {"ok": true, "t": 4546, "why": "camera stolen = punchline"},
"who_what": {"ok": true, "t": 4521, "why": "streamer vs masked robber clear"},
"standalone": {"ok": false, "t": 4552, "why": "'that guy came out of nowhere' refers to earlier fight"},
"intelligible": {"ok": true, "t": null, "why": ""},
"faithful": {"ok": true, "t": null, "why": ""},
"strong_open": {"ok": false, "t": 4521, "why": "first 3 s are calm talking"}
},
"fix": {"start_s": null, "end_s": 4551, "context_line": "Tfue tries to talk his way out of a robbery"},
"confidence": 0.8,
"reason": "Works alone if it ends on the stolen camera; tail depends on earlier context.",
"pt": {"viewer_summary": "…", "reason": "…"}
}
```
**Decisão pelo código, não pelo modelo** (calibrável no painel): `setup`, `payoff` e `standalone` são **críticos**.
Crítico falho + `fix` dentro da margem (`backtrackS`, duração mín./máx.) → aplica (`fit_window`) e roda o juiz **uma**
vez de novo no trecho novo; falhou de novo → descarta com motivo em português. Crítico falho sem `fix` → descarta.
Não críticos só baixam a nota (`score_final = score_editor − 0,5 por check não crítico falho`, ajustável).
Corte manual: juiz só **avisa** (não descarta), como o editor hoje.
**Critérios específicos para lives em inglês** (instruções padrão do juiz):
- Referência a algo **fora do corte**: "that guy", "again", "like I said", "remember when", nomes nunca apresentados,
callbacks a doação/raid/sub, piada interna do chat ou do canal.
- Fala-chave **de colega no Discord** ou de outro jogador que o Whisper não pegou (o streamer só reage) → `intelligible` falha.
- Ironia/gíria que muda o sentido ("he's cooked", "Clueless", "W") só vale se a tela confirma.
- Corte que termina **antes do desfecho** (sem resultado da treta, da fuga, da missão) → `payoff` falha (o caso 291).
- Título que afirma o que só foi suspeita ("caught a hacker" quando ele só acusa) → `faithful` falha.
- Conteúdo que só funciona para quem acompanha o streamer (lore do canal) → `standalone` falha, salvo `context_line` resolver.
### 6.1 Técnicas de LLM-como-juiz aplicadas
- **Checklist sim/não em vez de nota livre** (TICK, 2024: checklist gerada elevou a concordância exata com humanos de
46,4% para 52,2%; guias de 2025–2026 recomendam critérios binários com justificativa; white paper da Microsoft
(jun/2026) aponta nota direta 1–5 como frágil). A nota final sai das checagens.
- **Raciocínio antes do veredito**: `viewer_summary` vem primeiro; comparar com a "história pretendida" é um juiz com
**referência**, que a literatura mostra ser mais estável (G-Eval, 2023; MT-Bench, 2023).
- **Cascata barata** (Trust or Escalate, ICLR 2025: juiz pequeno primeiro, escala para um forte só quando não está
confiante — >80% de concordância garantida cobrindo ~80% dos casos): `confidence < 0,6` ou exatamente um crítico
falho → **segunda opinião** com outro provedor/modelo (configurável); empate decide pelo descarte. Votação
(self-consistency) só nesses casos, não em todos.
- **Evitar autopreferência**: o juiz de preferência em **provedor diferente** do editor (modelos julgam melhor o
texto que eles mesmos gerariam).
- **Calibração com o dono**: aprovar/rejeitar no painel já existe; acrescentar o motivo "sem contexto" na rejeição e
medir a concordância juiz × dono. Exemplos reais (2 bons, 2 ruins) entram como few-shot nas instruções do admin.
### 6.2 Modelo por papel
| Papel | Perfil de modelo | Sugestão inicial (CLI logada) |
| --- | --- | --- |
| Varredura | muito frequente, barato; só texto (+1 mosaico) | `gpt-6-luna` / `haiku` / `gemini-3.1-flash-lite` |
| Analista | cruza fontes; visão só no mosaico opcional | `gemini-3.5-flash` (boa visão; vídeo nativo na escalada) ou `gpt-6-luna` |
| Editor | escreve título/legenda em inglês nativo | `haiku` ou `gpt-6-luna`; modelo maior só se o dono notar título fraco |
| Juiz | raciocínio curto e rígido, só texto | provedor ≠ editor; `gpt-6-luna` com `model_reasoning_effort="medium"` ou `haiku`; segunda opinião: `sonnet` / `gemini-2.5-pro` |
Com chave de API: deixar estáveis no início do prompt (sistema + perfil) e o variável no fim, para aproveitar o
cache automático de prefixo (OpenAI) / cache do Claude.
### 6.3 Custo estimado por candidato e por hora (tfue, ~25 candidatos/h, Codex)
| Chamada | Hoje (entrada ≈) | Proposta (entrada ≈) | Observação |
| --- | --- | --- | --- |
| Varredura ×20/h | 6.300 → **126 mil/h** | 3.400 → **68 mil/h** | perfil enxuto (~500) + timeline |
| Analista ×25/h | 6.600 → **165 mil/h** | 3.500–4.300 → **88–108 mil/h** | com/sem mosaico |
| Editor ×25/h | 4.450 → **111 mil/h** | 2.850 → **71 mil/h** | só o trecho, sem a volta inteira |
| Juiz ×~13/h (só mantidos) | — | 1.950 (+30% 2ª opinião/rechecagem) → **≈ 33 mil/h** | saída ≈ 250 |
| **Conteúdo total** | **≈ 400 mil/h** | **≈ 260–280 mil/h (−30 a −35%)** | |
| Fixo das CLIs (≈ 2,5 mil/chamada) | 70 chamadas → ≈ 175 mil | ≈ 83 chamadas → ≈ 208 mil | **medir** (Codex/Gemini) |
| **Total** | **≈ 575 mil/h** | **≈ 470–490 mil/h (−15%)** | no Gemini a economia passa de −40% (imagens a 1.120) |
Por candidato mantido: hoje ≈ 11 mil (analista + editor); proposta ≈ 8–9 mil **com** o juiz. A economia de token é
moderada; o ganho principal é **qualidade** (cobertura a cada 6–8 s, áudio e HUD, desfecho checado). Alavancas extras:
portão local antes do analista (timeline mostra menu/loading, sem fala e sem reação → não gasta IA); candidato da
varredura que já veio com análise pula o analista; o fixo da CLI é o maior item restante — medir antes de otimizar.
## 7. Plano em fases
| Fase | O que entra | Precisa de modelo novo? |
| --- | --- | --- |
| **F0 — medir (1–2 dias)** | Gravar `usage` por chamada em `judge_json` (`claude -p --output-format json` traz uso; `codex exec --json` e `gemini -o json` trazem `stats`); base: tokens/h por papel, latência, % descartado, % aprovado pelo dono. Separar 50–100 cortes antigos rotulados pelo dono (bom / ruim / "sem contexto"). | não |
| **F1 — três papéis + timeline v0** | Configuração por papel (provedor, modelo, esforço, instruções, liga/desliga); JUIZ só texto com o schema acima e decisão pelo código; mosaico 4×2 (ffmpeg `tile`) no lugar dos N frames; timeline com o que já existe (fala, chat, rosto, volume, `scdet`) + frase `v` escrita pela varredura a partir do mosaico e guardada; perfil enxuto por papel. | não |
| **F2 — sinais locais leves** | YAMNet (áudio, CPU) e RapidOCR (HUD, CPU); perfil do jogo ganha `hud_regions` e `hud_keywords` (ex.: "WANTED", "MISSION PASSED", "YOU ARE DOWN"). | sim, pequenos (Apache-2.0) |
| **F3 — legenda local de cena** | Qwen3-VL-2B/4B (Apache-2.0) via llama.cpp/Ollama, ou SmolVLM2; bake-off contra a frase da varredura em 30 cortes (como `doc/FACE_BAKEOFF.md`). Ganhando, analista e varredura ficam só texto; imagem só na escalada. | sim (VLM) |
| **F4 — escalada com vídeo nativo (opcional)** | Casos duvidosos: Gemini por API key com o trecho em vídeo (fps 0,5–1, low; ≈ 6–9 mil tokens por 90 s, com áudio). | não (API) |
**Riscos:** VRAM de 8 GB já cheia (VLM concorre com o Whisper → F3 só quantizado, e medir); legenda de VLM pequeno
alucina (mitigar: vocabulário do perfil, confiança, analista cruza com fala/HUD); OCR falha em fonte estilizada;
gameplay contínuo gera poucos cortes de plano (por isso o teto de 8 s); juiz rígido demais mata corte bom (medir
falso negativo); +1 chamada (~5–7 s) por corte mantido; a CLI do Gemini cobra 1.120 tokens por imagem e não expõe
`media_resolution` (por isso mosaico/texto); mudanças de flags nas CLIs.
**O que medir para saber se melhorou** (antes × depois, mesma fonte):
- **Precisão**: % dos cortes "prontos" que o dono aprova (meta: subir); **falso positivo**: mantido pela IA e
rejeitado pelo dono, em especial com motivo "sem contexto/sem sentido" (meta: cair pela metade).
- **Falso negativo**: amostra semanal de 10 descartados pelo juiz — quantos o dono aprovaria (meta: ≤ 1).
- Concordância juiz × dono no conjunto rotulado (κ de Cohen); % de cortes ajustados pelo juiz que o dono mantém
sem editar o trecho.
- Tokens/h e chamadas/h por papel; latência por candidato; tempo local por minuto de live (F2/F3).
## 8. Esboço da UI (Clipador → Juiz → "Equipe de IA")
```
┌ Equipe de IA ─────────────────────────────────────────────────────────────────────┐
│ Papel Ligado Provedor Modelo Esforço Imagens │
│ Varredura [x] Codex ▾ gpt-6-luna ▾ baixo ▾ mosaico/3 min ▾ │
│ Analista [x] Gemini ▾ gemini-3.5-flash ▾ — se faltar cena ▾ │
│ Editor [x] Claude ▾ haiku ▾ — nunca │
│ Juiz [x] Codex ▾ gpt-6-luna ▾ médio ▾ nunca │
│ 2ª opinião [x] Claude ▾ sonnet ▾ quando: confiança < [0,6] ou 1 crítico│
│ │
│ ▸ Instruções — Juiz │
│ Padrão (somente leitura, EN/PT) [ver] [restaurar padrão] │
│ Do administrador (somadas ao padrão; pode escrever em português): │
│ [ Não aprove corte que termina antes do resultado da treta. ] │
│ Checagens: setup [crítico] desfecho [crítico] sozinho [crítico] │
│ quem/o quê [ ] fala clara [ ] título fiel [ ] abertura forte [ ] │
│ Pode ajustar o trecho [x] Pode pôr frase de contexto na tela [x] │
│ Exemplos do dono: + escolher corte (bom/ruim + 1 frase) │
│ [Testar nos últimos 10 cortes] → mostra o que mudaria, sem gravar │
│ [Salvar] │
└───────────────────────────────────────────────────────────────────────────────────┘
```
Gravação sugerida (tabela `settings`, chave `judge.roles`; identificadores em inglês):
```jsonc
{
"scan": {"enabled": true, "provider": "codex", "model": "", "effort": "low", "images": "mosaic", "extra": ""},
"analyst": {"enabled": true, "provider": "gemini", "model": "", "effort": "low", "images": "fallback", "extra": ""},
"editor": {"enabled": true, "provider": "claude", "model": "haiku", "images": "never", "extra": ""},
"judge": {"enabled": true, "provider": "codex", "model": "", "effort": "medium", "extra": "",
"critical": ["setup", "payoff", "standalone"], "allowFix": true, "allowContextLine": true,
"second": {"enabled": true, "provider": "claude", "model": "sonnet", "minConfidence": 0.6},
"examples": [{"clipId": 291, "good": false, "note": "termina antes do desfecho"}]}
}
```
`model: ""` = padrão do provedor; a reserva (`fallback_chain`) passa a valer **por papel**. As instruções do
administrador entram depois do texto padrão com o rótulo "Admin notes (may be in Portuguese)" — os juízes trabalham
em inglês e entendem português; a saída para o painel continua no bloco `pt`.
## 9. Fontes (consultadas em 18/11/2026)
- OpenAI — Images and vision (tokens por patch/tile e multiplicadores): https://developers.openai.com/api/docs/guides/images-vision
- Anthropic — Vision (patches de 28 px, tetos por modelo): https://platform.claude.com/docs/en/build-with-claude/vision
- Google — Media resolution (Gemini 3/4: 1.120/280/560 por imagem, 70/280 por frame): https://aistudio.google.com/docs/media-resolution
- Google — Video understanding (1 fps, ~100 tokens/s, áudio 32/s, `fps` e offsets): https://aistudio.google.com/docs/video-understanding
- Opus Clip — Virality score (Hook, Flow, Value, Trend): https://help.opus.pro/docs/article/virality-score
- Eklipse — Gameplay Intelligence (26/05/2026): https://blog.eklipse.gg/streaming-tips/gameplay-intelligence.html ; HUD/kill feed: https://eklipse.gg/compare/eklipse-vs-spikes-studio/
- Twitch — TwitchCon Rotterdam (30/05/2026): https://blog.twitch.com/en/2026/05/30/everything-we-announced-at-twitchcon-rotterdam-2026/ ; San Diego (17/10/2025): https://blog.twitch.com/en/2025/10/17/ten-years-of-twitchcon-here-s-what-we-announced-in-san-diego/
- YouTube — Made on YouTube (20/09/2025): https://techcrunch.com/2025/09/20/updates-to-studio-youtube-live-new-gen-ai-tools-and-everything-else-announced-at-made-on-youtube/
- StreamLadder ClipGPT: https://streamladder.com/clipgpt-features/ai-virality-score ; comparativo 2026: https://www.twoaveragegamers.com/best-ai-clip-detection-tools-for-streamers-2026/
- Grade de frames: IG-VLM https://arxiv.org/abs/2403.18406 ; TS-LLaVA https://arxiv.org/abs/2411.11066 ; "Paying for Too Many Tokens?" (30/09/2026) https://arxiv.org/abs/2610.00809
- Legenda → LLM: LLoVi (EMNLP 2024) https://arxiv.org/abs/2312.17235 ; HiVid (fev/2026) https://arxiv.org/abs/2602.14214
- Juiz: TICK https://arxiv.org/abs/2410.03608 ; Trust or Escalate https://arxiv.org/abs/2407.18370 ; MT-Bench https://arxiv.org/abs/2306.05685 ; G-Eval https://arxiv.org/abs/2303.16634 ; Self-consistency https://arxiv.org/abs/2203.11171 ; Microsoft, nota 1–5 (jun/2026) https://microsoft.github.io/mcscatblog/assets/posts/better-llm-scoring/20260626_LLM1-5Scoring_WhitePaper.pdf
- Licenças: Qwen3-VL-4B https://huggingface.co/Qwen/Qwen3-VL-4B-Instruct ; Qwen2.5-VL-3B (não comercial) https://huggingface.co/Qwen/Qwen2.5-VL-3B-Instruct/blob/main/LICENSE ; SmolVLM2 https://huggingface.co/HuggingFaceTB/SmolVLM2-2.2B-Instruct ; Florence-2 https://huggingface.co/microsoft/Florence-2-large-ft ; Moondream 3 https://huggingface.co/moondream/moondream3-preview ; YAMNet https://github.com/tensorflow/models/blob/master/research/audioset/yamnet/README.md ; PANNs (pesos CC-BY-4.0 via port) https://huggingface.co/litert-community/PANNs-CNN14-AudioSet-LiteRT ; PP-OCRv5 https://paddlepaddle.github.io/PaddleOCR/main/en/version3.x/algorithm/PP-OCRv5/PP-OCRv5.html ; PySceneDetect (BSD-3) https://scenedetect.com/copyright
+85
View File
@@ -0,0 +1,85 @@
# Clipador — vídeo de revisão × vídeo final
Pedido do dono (18/11/2026):
> Quando o clipe está ali para a gente aprovar, a legenda é só de dev. Quando a gente aprovar, ele vai renderizar o
> vídeo de novo, removendo as coisas de dev.
## Fluxo
```
fila de render ─► VÍDEO DE REVISÃO clip-<id>.mp4 (dev=True: entram as camadas `dev` ligadas)
│ status ready → equipe assiste e decide
▼
Aprovar (PATCH status=approved|published)
│
review_dev_json = []? ──sim──► o de revisão JÁ É o final (sem render novo; final.reused = true)
│não / não se sabe
▼
VÍDEO FINAL clip-<id>-final.mp4 (+ -final.jpg, -final-cover.jpg) (dev=False)
│ final_status: pending → rendering → ready | error
▼
Publicação: SÓ `publishFile` (o final pronto); sem ele, o envio espera
```
- **Camadas `dev`** (`layout.py`, grupo `dev` da configuração do corte): hoje `translation` (português embaixo da
legenda) e `dub` (dublagem em português). `layout.dev_flags(cfg, dev=False)` desliga todas.
- O render da fila (`worker._render_clip` → `editor_api.render_clip_edit(..., dev=True)`) grava em
`clips.review_dev_json` quais camadas entraram de fato (`editor_api.review_layers`): a tradução só conta se havia
frases para desenhar (fonte em português nunca tem); as outras chaves contam pela configuração, por cautela.
- O final roda na mesma fila do motor (`Engine.render_pending`: finais primeiro, até 3 por volta), com
`render_clip_edit(..., dev=False)` sobre o MESMO projeto de edição. Não pede tradução, não grava `review_dev_json`.
- Falha no final vira `final_status = 'error'` com `final_error`; o corte continua aprovado e nada é publicado.
Serviço caiu no meio: na subida `rendering` volta a `pending`.
## O final deixa de valer quando…
| Ação | Efeito |
| --- | --- |
| Desfazer aprovação / rejeitar (`PATCH status=ready|rejected`) | final some (`drop_final`); aprovar de novo gera outro |
| Mudar início/fim de um aprovado (`PATCH startS/endS`) | volta para `pending` (revisão nova) e o final some |
| Exportar do editor (`POST /export`), re-render (`POST /render`), mandar de novo para a IA (`POST /rejudge`) | final some; o corte volta a ser revisão e precisa ser aprovado de novo |
| Qualquer render de revisão novo terminar | final some (conteúdo novo) |
| Desaprovar DURANTE o render do final | o resultado é descartado (só grava se ainda estiver `rendering`) |
O arquivo `clip-<id>-final.mp4` antigo fica no disco até o próximo final (mesmo nome) ou até apagar o corte
(`clip_delete` apaga `clip-<id>-*`). Apagar é recusado enquanto o final renderiza.
**Limpeza dos blocos** (`CLIPPER_KEEP_HOURS`): além dos cortes em andamento, `prune` guarda o trecho de quem ainda vai
precisar do final — aprovado com final `pending`/`rendering`/`error`, e pronto para aprovar cujo vídeo de revisão tem
camada de teste (ou não se sabe). Corte pronto **sem** camada de teste não segura blocos (o de revisão já é o final).
## Banco (migração v14, `clipper/app/db.py`)
`clips.review_dev_json` (JSON: `["translation", …]`; `[]` = nenhuma; NULL = desconhecido) · `final_status`
(`pending|rendering|ready|error`; NULL = sem final) · `final_file` · `final_thumb` · `final_cover` · `final_error` ·
`final_at`. Cortes antigos: sem `translation_json` → `review_dev_json = []` (a tradução era a única camada); aprovados
assim ganham o final = o próprio arquivo; aprovados com tradução ficam `pending` (renderiza na subida); publicados com
tradução ficam sem final (gera com `POST /final` se forem para outra rede).
## API (`/v1/clips…`)
- Cada corte traz `review: {devLayers}`, `final: {status, file, thumb, cover, error, at, reused} | null` e
`publishFile` = `final.file` quando o corte está `approved|published` e o final está `ready`; senão `null`.
`file`/`thumb` continuam sendo os do vídeo de revisão.
- `POST /v1/clips/{id}/final` — (re)gera o final de um corte aprovado ("Tentar de novo"); 409 se não aprovado.
## Publicação (painel)
- `panel/src/lib/publishing-rules.ts` → `clipPublishFile(clip)`: devolve `publishFile` ou o motivo de esperar. Nunca
devolve `file` quando o Clipador manda o campo (Clipador antigo, sem `publishFile`, segue com `file`).
- `publishing.ts → sendDue`: antes de mandar um job de corte ao Publicador, relê o corte no Clipador
(`clipFinalForJob`); sem final pronto o job fica na fila com o passo "Esperando o vídeo final…"; com o final, troca
`file` (e a capa, se o final tiver) do job e envia. O arquivo gravado ao criar o job é só referência.
- Capa do corte (`clipCover`): a do final primeiro.
## Painel (`/clipper`)
- Lista: etiqueta `revisão · teste` (vídeo com camadas de teste), `gerando final`, `final` ou `final com erro`.
- Modal: o player toca o final quando existe (botões **Final / Revisão** para comparar); texto dizendo se é o de
revisão (e quais camadas de teste) ou o final; estado do final depois de aprovar (na fila/gerando… · pronto · erro com
**Tentar de novo**); aprovado sem final: **Gerar vídeo final**.
- Diálogo "Publicar": aviso de que o envio espera o vídeo final enquanto ele não está pronto.
Testes: `clipper/tests/test_final_render.py`; `panel/src/lib/publishing-rules.test.ts` (regra) e
`publishing-db.test.ts` (despachante espera o final e envia o arquivo final).
+51 -14
View File
@@ -10,7 +10,8 @@ import {
/** `muted` = trecho sem o som da live (a narração e a música continuam). */ /** `muted` = trecho sem o som da live (a narração e a música continuam). */
export type EditCut = { start: number; end: number; mode: LayoutMode | null; muted?: boolean }; export type EditCut = { start: number; end: number; mode: LayoutMode | null; muted?: boolean };
export type EditWord = { s: number; e: number; w: string; emph?: boolean; hidden?: boolean }; /** `sp` = quem fala (doc/clipador/FALANTES.md): ausente/"streamer" = o streamer; "other1", "other2"… = outra pessoa. */
export type EditWord = { s: number; e: number; w: string; emph?: boolean; hidden?: boolean; sp?: string };
export type CaptionPreset = "classic" | "pop" | "karaoke" | "single" | "minimal"; export type CaptionPreset = "classic" | "pop" | "karaoke" | "single" | "minimal";
export type TextAnim = HookAnim; export type TextAnim = HookAnim;
/** Gancho: tempo de SAÍDA (vale a partir do 1º quadro). Texto: tempo da SESSÃO (gruda no conteúdo). */ /** Gancho: tempo de SAÍDA (vale a partir do 1º quadro). Texto: tempo da SESSÃO (gruda no conteúdo). */
@@ -278,7 +279,35 @@ export function removeSilences(cuts: EditCut[], words: EditWord[], minGap: numbe
/* ---------- legenda (prévia no navegador) ---------- */ /* ---------- legenda (prévia no navegador) ---------- */
export type OutWord = { start: number; end: number; word: string; emph: boolean }; export type OutWord = { start: number; end: number; word: string; emph: boolean; sp?: string };
/** Fala de outra pessoa (qualquer `sp` que não seja vazio nem "streamer"). */
export function isOther(sp: string | undefined | null): boolean {
return Boolean(sp) && sp !== "streamer";
}
/** Faixa da legenda: a do streamer (posição normal) ou a de outra pessoa (logo abaixo). */
export type CaptionLane = "streamer" | "other";
export function laneOf(sp: string | undefined | null): CaptionLane {
return isOther(sp) ? "other" : "streamer";
}
/** Rótulo de quem fala, para o painel. */
export function speakerLabel(sp: string | undefined | null): string {
if (!isOther(sp)) return "Streamer";
const n = /^other(\d+)$/.exec(sp ?? "");
return n ? `Outra pessoa ${n[1]}` : "Outra pessoa";
}
/** Tamanho da fala de outra pessoa (`caption.otherSize` ou 85 % do tamanho), como `subtitles.other_size`. */
export function otherSize(cap: CutSettings["caption"]): number {
return cap.otherSize ? cap.otherSize : Math.max(30, Math.round(cap.size * 0.85));
}
/** Distância do centro da linha do streamer ao centro da de outra pessoa, como `subtitles.other_offset`. */
export function otherOffset(size: number, osize: number): number {
return Math.round(0.6 * size + 0.6 * osize) + 10;
}
export function outputWords(project: EditProject): OutWord[] { export function outputWords(project: EditProject): OutWord[] {
const ps = pieces(project.cuts); const ps = pieces(project.cuts);
@@ -291,7 +320,7 @@ export function outputWords(project: EditProject): OutWord[] {
const s = p.out + Math.max(w.s, p.start) - p.start; const s = p.out + Math.max(w.s, p.start) - p.start;
const e = p.out + Math.min(w.e, p.end) - p.start; const e = p.out + Math.min(w.e, p.end) - p.start;
// Arredondado a 3 casas como `editor.output_words` (o agrupamento compara esses números). // Arredondado a 3 casas como `editor.output_words` (o agrupamento compara esses números).
out.push({ start: round3(s), end: round3(Math.max(e, s + 0.05)), word: w.w, emph: Boolean(w.emph) }); out.push({ start: round3(s), end: round3(Math.max(e, s + 0.05)), word: w.w, emph: Boolean(w.emph), sp: w.sp ?? "" });
} }
return out; return out;
} }
@@ -350,7 +379,8 @@ export function groupWords(words: OutWord[], maxWords: number = CAPTION_TIMING.M
const groups: OutWord[][] = []; const groups: OutWord[][] = [];
for (const word of cleanWords(words)) { for (const word of cleanWords(words)) {
const cur = groups[groups.length - 1]; const cur = groups[groups.length - 1];
if (cur && word.start - cur[cur.length - 1].end <= MAX_GAP_S && word.end - cur[0].start <= MAX_BLOCK_S) { const same = cur && (cur[cur.length - 1].sp || "streamer") === (word.sp || "streamer"); // bloco nunca mistura falantes
if (cur && same && word.start - cur[cur.length - 1].end <= MAX_GAP_S && word.end - cur[0].start <= MAX_BLOCK_S) {
const fits = [...cur, word].map((w) => w.word).join(" ").length <= maxChars; const fits = [...cur, word].map((w) => w.word).join(" ").length <= maxChars;
// Fala rápida: o bloco cheio passaria voando; uma palavra a mais (se couber) dá tempo de ler. // Fala rápida: o bloco cheio passaria voando; uma palavra a mais (se couber) dá tempo de ler.
const room = cur.length < maxWords || (maxWords >= 2 && cur.length === maxWords && word.end - cur[0].start < FAST_BLOCK_S); const room = cur.length < maxWords || (maxWords >= 2 && cur.length === maxWords && word.end - cur[0].start < FAST_BLOCK_S);
@@ -363,22 +393,29 @@ export function groupWords(words: OutWord[], maxWords: number = CAPTION_TIMING.M
export type CaptionBlock = { words: OutWord[]; end: number }; export type CaptionBlock = { words: OutWord[]; end: number };
/** Blocos com o fim: nunca passa do início do bloco seguinte (dois eventos ativos o libass empilharia). */ /**
* Blocos com o fim: nunca passa do início do bloco seguinte DA MESMA FAIXA (streamer / outra pessoa), como
* `subtitles.caption_blocks`. Os dois falando juntos = um bloco em cada faixa ao mesmo tempo.
*/
export function captionBlocks(words: OutWord[], maxWords: number = CAPTION_TIMING.MAX_WORDS): CaptionBlock[] { export function captionBlocks(words: OutWord[], maxWords: number = CAPTION_TIMING.MAX_WORDS): CaptionBlock[] {
const groups = groupWords(words, maxWords); const out: CaptionBlock[] = [];
return groups.map((g, k) => { for (const lane of ["streamer", "other"] as const) {
let end = Math.max(g[g.length - 1].end, g[g.length - 1].start + CAPTION_TIMING.MIN_HOLD_S); const groups = groupWords(words.filter((w) => laneOf(w.sp) === lane), maxWords);
if (k + 1 < groups.length) end = Math.min(end, groups[k + 1][0].start); groups.forEach((g, k) => {
return { words: g, end: pyRound3(end) }; let end = Math.max(g[g.length - 1].end, g[g.length - 1].start + CAPTION_TIMING.MIN_HOLD_S);
}); if (k + 1 < groups.length) end = Math.min(end, groups[k + 1][0].start);
out.push({ words: g, end: pyRound3(end) });
});
}
return out.sort((a, b) => a.words[0].start - b.words[0].start);
} }
/** /**
* Bloco e palavra destacada no instante `t` (saída), como os eventos do ASS: o bloco vale de `[0].start` até `end`; * Bloco e palavra destacada no instante `t` (saída), como os eventos do ASS: o bloco vale de `[0].start` até `end`;
* a palavra i vale do início dela até o início da seguinte (a última, até o fim do bloco). * a palavra i vale do início dela até o início da seguinte (a última, até o fim do bloco). `lane` = faixa.
*/ */
export function captionAt(blocks: CaptionBlock[], t: number): { block: CaptionBlock; active: number } | null { export function captionAt(blocks: CaptionBlock[], t: number, lane: CaptionLane = "streamer"): { block: CaptionBlock; active: number } | null {
const block = blocks.find((b) => t >= b.words[0].start && t < b.end); const block = blocks.find((b) => laneOf(b.words[0].sp) === lane && t >= b.words[0].start && t < b.end);
if (!block) return null; if (!block) return null;
let active = 0; let active = 0;
for (let i = 0; i < block.words.length; i++) if (t >= block.words[i].start) active = i; for (let i = 0; i < block.words.length; i++) if (t >= block.words[i].start) active = i;
+17 -5
View File
@@ -19,7 +19,7 @@ import type { CutSettings, Rect } from "./clipper-client";
import { canvasFont, fontMetrics } from "./clip-editor-fonts"; import { canvasFont, fontMetrics } from "./clip-editor-fonts";
import { import {
BANNER_SLIDE_MS, CHAT_HOLD_S, INSET_ANIM_S, INSET_SHADOW_ALPHA, INSET_SLIDE_S, TEXT_SLIDE_MS, bannerLayout, camPanelHeight, captionY, BANNER_SLIDE_MS, CHAT_HOLD_S, INSET_ANIM_S, INSET_SHADOW_ALPHA, INSET_SLIDE_S, TEXT_SLIDE_MS, bannerLayout, camPanelHeight, captionY,
captionAt, captionBlocks, chatDefault, clamp, cutAt, easeAt, ffmpegCropFill, gameWindowAt, insetAt, insetHeight, outputDuration, outputWords, plainLines, produce, resolvedMode, captionAt, captionBlocks, chatDefault, clamp, otherOffset, otherSize, type CaptionLane, cutAt, easeAt, ffmpegCropFill, gameWindowAt, insetAt, insetHeight, outputDuration, outputWords, plainLines, produce, resolvedMode,
round3, setInsetPlace, toOutput, zoomAt, type ChatItem, type EditProject, type Frame, type InsetOverlay, type OutWord, type Selection, type TextOverlay, round3, setInsetPlace, toOutput, zoomAt, type ChatItem, type EditProject, type Frame, type InsetOverlay, type OutWord, type Selection, type TextOverlay,
} from "./clip-editor-model"; } from "./clip-editor-model";
import { cx } from "./ui"; import { cx } from "./ui";
@@ -277,8 +277,15 @@ function renderFrame(ctx: CanvasRenderingContext2D, comp: HTMLCanvasElement, vid
if (fontsReady) { if (fontsReady) {
const cap = cfg.caption; const cap = cfg.caption;
if (cap.enabled && inside) { if (cap.enabled && inside) {
const box = drawCaption(ctx, project, cfg, tOut, captionY(cfg, mode, frame) * k, k, cw); // Fala de outra pessoa (colega no Discord, voz do jogo): logo abaixo, na cor dela (FALANTES.md). Sem espaço
// embaixo, a linha do streamer sobe (como no render: a ordem nunca inverte).
const two = project.captions.words.some((w) => w.sp && w.sp !== "streamer");
const offset = otherOffset(cap.size, otherSize(cap));
const capY = two ? Math.min(captionY(cfg, mode, frame), frame.canvasHeight - 8 - offset - Math.trunc(0.6 * otherSize(cap)))
: captionY(cfg, mode, frame);
const box = drawCaption(ctx, project, cfg, tOut, capY * k, k, cw);
if (box) hits.push({ key: "caption", ...box }); if (box) hits.push({ key: "caption", ...box });
if (two) drawCaption(ctx, project, cfg, tOut, (capY + offset) * k, k, cw, "other");
} }
for (const o of project.overlays) { for (const o of project.overlays) {
if (o.kind === "zoom" || o.kind === "inset") continue; if (o.kind === "zoom" || o.kind === "inset") continue;
@@ -547,10 +554,15 @@ function drawBanner(ctx: CanvasRenderingContext2D, o: TextOverlay, frame: Frame,
* comportamento de cada preset de `editor_render.build_project_ass`. `y` = centro em px do canvas. Estilo "Caption": * comportamento de cada preset de `editor_render.build_project_ass`. `y` = centro em px do canvas. Estilo "Caption":
* negrito, contorno e sombra 3 (meio preto). * negrito, contorno e sombra 3 (meio preto).
*/ */
function drawCaption(ctx: CanvasRenderingContext2D, project: EditProject, cfg: CutSettings, t: number, y: number, k: number, cw: number): Box { function drawCaption(ctx: CanvasRenderingContext2D, project: EditProject, cfg: CutSettings, t: number, y: number, k: number, cw: number,
const cap = cfg.caption; lane: CaptionLane = "streamer"): Box {
// A linha de outra pessoa usa a cor e o tamanho dela (`otherColor`/`otherSize`), como o estilo CaptionOther do ASS.
const cap = lane === "other"
? { ...cfg.caption, color: cfg.caption.otherColor ?? "#5CE1FF", size: otherSize(cfg.caption),
outlineWidth: cfg.caption.outlineWidth ? Math.max(2, Math.floor((cfg.caption.outlineWidth * otherSize(cfg.caption)) / cfg.caption.size)) : 0 }
: cfg.caption;
const preset = project.captions.preset; const preset = project.captions.preset;
const now = captionAt(captionBlocks(outputWords(project), cap.maxWords), t); const now = captionAt(captionBlocks(outputWords(project), cap.maxWords), t, lane);
const group = now?.block.words; const group = now?.block.words;
const m = fontMetrics(cap.font); const m = fontMetrics(cap.font);
const size = cap.size * k; const size = cap.size * k;
@@ -4,10 +4,13 @@
// Com palavras selecionadas, a barra oferece tirar/manter no corte e ênfase (o resto fica em Propriedades). // Com palavras selecionadas, a barra oferece tirar/manter no corte e ênfase (o resto fica em Propriedades).
// Palavras fora do corte aparecem riscadas. Ferramentas: remover silêncios maiores que X s e re-transcrever um // Palavras fora do corte aparecem riscadas. Ferramentas: remover silêncios maiores que X s e re-transcrever um
// trecho com o Whisper do serviço de voz. Chat: as mensagens da janela, com o tempo; clique = ir ao instante. // trecho com o Whisper do serviço de voz. Chat: as mensagens da janela, com o tempo; clique = ir ao instante.
// Quem fala (doc/clipador/FALANTES.md): cada parágrafo é de um falante só; a fala de outra pessoa (colega no Discord,
// voz do jogo) vem marcada e na cor dela; "Falante" troca as palavras selecionadas entre streamer e outra pessoa.
import { useEffect, useRef, useState } from "react"; import { useEffect, useRef, useState } from "react";
import { clipperCall } from "./clipper-client"; import { clipperCall } from "./clipper-client";
import { import {
cutAt, keepRange, produce, removeRange, removeSilences, sessionClock, type ChatItem, type EditProject, type EditWord, type Selection, cutAt, isOther, keepRange, produce, removeRange, removeSilences, sessionClock, speakerLabel, type ChatItem, type EditProject, type EditWord,
type Selection,
} from "./clip-editor-model"; } from "./clip-editor-model";
import { Btn } from "./clip-editor-ui"; import { Btn } from "./clip-editor-ui";
import { MicIcon, ScissorsIcon } from "./icons"; import { MicIcon, ScissorsIcon } from "./icons";
@@ -62,9 +65,10 @@ export function EditorTranscript({ clipId, project, playhead, selection, onSelec
if (!parts.length || parts.join(" ") === sel.map((w) => w.w).join(" ")) return; if (!parts.length || parts.join(" ") === sel.map((w) => w.w).join(" ")) return;
const weight = parts.reduce((n, w) => n + w.length + 1, 0); const weight = parts.reduce((n, w) => n + w.length + 1, 0);
let cursor = selA; let cursor = selA;
const sp = sel[0].sp; // o texto novo continua de quem falava
const fresh: EditWord[] = parts.map((w) => { const fresh: EditWord[] = parts.map((w) => {
const dur = Math.max(0.06, ((selB - selA) * (w.length + 1)) / weight); const dur = Math.max(0.06, ((selB - selA) * (w.length + 1)) / weight);
const item = { s: Math.round(cursor * 1000) / 1000, e: Math.round(Math.min(selB, cursor + dur) * 1000) / 1000, w: w.slice(0, 40) }; const item: EditWord = { s: Math.round(cursor * 1000) / 1000, e: Math.round(Math.min(selB, cursor + dur) * 1000) / 1000, w: w.slice(0, 40), ...(sp ? { sp } : {}) };
cursor += dur; cursor += dur;
return item; return item;
}).filter((w) => w.e > w.s); }).filter((w) => w.e > w.s);
@@ -92,11 +96,13 @@ export function EditorTranscript({ clipId, project, playhead, selection, onSelec
onNotice(true, `Whisper transcreveu ${sessionClock(a)}–${sessionClock(b)} de novo: ${r.data.words.length} palavras em ${r.data.seconds.toLocaleString("pt-BR")} s.`); onNotice(true, `Whisper transcreveu ${sessionClock(a)}–${sessionClock(b)} de novo: ${r.data.words.length} palavras em ${r.data.seconds.toLocaleString("pt-BR")} s.`);
} }
// Parágrafos: quebra quando a fala para mais de 1,2 s (fica mais fácil achar onde cortar). // Parágrafos: quebra quando a fala para mais de 1,2 s (fica mais fácil achar onde cortar) ou quando muda quem fala.
const paragraphs: number[][] = []; const paragraphs: number[][] = [];
const speakerOf = (w: EditWord) => (isOther(w.sp) ? w.sp : "streamer");
const anyOther = words.some((w) => isOther(w.sp));
words.forEach((w, i) => { words.forEach((w, i) => {
const last = paragraphs[paragraphs.length - 1]; const last = paragraphs[paragraphs.length - 1];
if (!last || w.s - words[i - 1].e > 1.2) paragraphs.push([i]); if (!last || w.s - words[i - 1].e > 1.2 || speakerOf(w) !== speakerOf(words[i - 1])) paragraphs.push([i]);
else last.push(i); else last.push(i);
}); });
@@ -120,6 +126,11 @@ export function EditorTranscript({ clipId, project, playhead, selection, onSelec
const on = !sel.every((w) => w.emph); const on = !sel.every((w) => w.emph);
setWords((ws) => ws.map((w, i) => (range && i >= range.from && i <= range.to ? { ...w, emph: on || undefined } : w))); setWords((ws) => ws.map((w, i) => (range && i >= range.from && i <= range.to ? { ...w, emph: on || undefined } : w)));
}}>Ênfase</Btn> }}>Ênfase</Btn>
<Btn variant="ghost" className="px-2" title="Trocar quem fala estas palavras: streamer ↔ outra pessoa (legenda de baixo, outra cor)" onClick={() => {
const toStreamer = sel.every((w) => isOther(w.sp));
setWords((ws) => ws.map((w, i) => (range && i >= range.from && i <= range.to ? { ...w, sp: toStreamer ? "streamer" : "other1" } : w)));
onNotice(true, toStreamer ? "Palavras marcadas como do streamer." : "Palavras marcadas como de outra pessoa (legenda de baixo).");
}}>{sel.every((w) => isOther(w.sp)) ? "É o streamer" : "Outra pessoa"}</Btn>
</> </>
) : ( ) : (
<> <>
@@ -160,8 +171,15 @@ export function EditorTranscript({ clipId, project, playhead, selection, onSelec
{paragraphs.map((para) => ( {paragraphs.map((para) => (
<p key={para[0]} className="mb-1.5 grid grid-cols-[52px_minmax(0,1fr)] gap-x-2"> <p key={para[0]} className="mb-1.5 grid grid-cols-[52px_minmax(0,1fr)] gap-x-2">
<button type="button" tabIndex={-1} onClick={() => onSeek(words[para[0]].s)} <button type="button" tabIndex={-1} onClick={() => onSeek(words[para[0]].s)}
className="cursor-pointer pt-[3px] text-left font-mono text-[10.5px] text-nle-hot/80 hover:text-nle-hot">{sessionClock(words[para[0]].s)}</button> className="grid cursor-pointer content-start pt-[3px] text-left font-mono text-[10.5px] text-nle-hot/80 hover:text-nle-hot">
<span> {sessionClock(words[para[0]].s)}
{anyOther && (
<span className={cx("font-sans text-[10px] leading-tight", isOther(words[para[0]].sp) ? "text-[#5ce1ff]" : "text-nle-dim")}>
{speakerLabel(words[para[0]].sp)}
</span>
)}
</button>
<span className={cx(isOther(words[para[0]].sp) && "text-[#9fe9ff]")}>
{para.map((i) => { {para.map((i) => {
const w = words[i]; const w = words[i];
const kept = cutAt(project.cuts, (w.s + w.e) / 2) >= 0; const kept = cutAt(project.cuts, (w.s + w.e) / 2) >= 0;
+10
View File
@@ -213,6 +213,16 @@ function PublishDialog({ clip, jobs, onClose, onDone }: {
<p className="text-xs text-fg-subtle">Vai com o título e a legenda do cartão. Para mudar, edite no cartão e salve antes.</p> <p className="text-xs text-fg-subtle">Vai com o título e a legenda do cartão. Para mudar, edite no cartão e salve antes.</p>
</div> </div>
{clip.publishFile === null && (
// Só o vídeo final (sem as camadas de teste) vai para as redes: os envios esperam por ele (doc/clipador/REVISAO.md).
<p role="note" className="flex gap-2 rounded-control border border-info/30 bg-info-soft px-3 py-2 text-[0.8125rem] leading-relaxed text-info">
<InfoIcon size={15} className="mt-0.5 shrink-0" />
<span>{clip.final?.status === "error"
? <>O vídeo final deu erro no Clipador. Pode agendar: nada sai até ele ficar pronto — use “Tentar de novo” no corte.</>
: <>O vídeo final (sem as camadas de teste) ainda está sendo gerado. Pode agendar: o envio espera por ele e nunca usa o vídeo de revisão.</>}</span>
</p>
)}
{loadError ? ( {loadError ? (
<Feedback ok={false}>Não deu para ler os canais de publicação ({loadError}).</Feedback> <Feedback ok={false}>Não deu para ler os canais de publicação ({loadError}).</Feedback>
) : !accounts ? ( ) : !accounts ? (
+71 -4
View File
@@ -113,10 +113,33 @@ export type CamDetect = {
confidence?: number; fullFrame?: boolean; confidence?: number; fullFrame?: boolean;
}; };
/** Expressões do rosto (reaction.py, `EXPRESSION_LABELS`). Serviço antigo só manda as 7 primeiras. */
export type FaceExpression = "risada" | "grito" | "susto" | "choque" | "confuso" | "raiva" | "neutro"
| "gargalhada" | "alegria" | "medo" | "espanto" | "nojo" | "tristeza" | "tenso" | "bocejo";
/** Movimento da cabeça/corpo (reaction.py, `body_moments`), mesmo sem expressão no rosto. */
export type BodyLabel = "balançando" | "acenando" | "agitado" | "chegou perto" | "saiu do quadro";
/** Reação no rosto do streamer (rastreio local, reaction.py): pico, início e intensidade (z relativo ao normal dele). */ /** Reação no rosto do streamer (rastreio local, reaction.py): pico, início e intensidade (z relativo ao normal dele). */
export type FaceReaction = { export type FaceReaction = {
peakS: number; onsetS: number; endS: number; intensity: number; strong: boolean; peakS: number; onsetS: number; endS: number; intensity: number; strong: boolean;
label: "risada" | "grito" | "susto" | "choque" | "confuso" | "raiva" | "neutro"; label: FaceExpression;
};
/** Um segundo do mapa de expressões (`GET sessions/{id}/face`); só os campos que o painel usa. */
export type FaceMapSecond = {
t: number; present: number;
/** Expressão dominante; ausente = sem rosto legível (ou serviço antigo). */
expr?: FaceExpression;
/** Movimento do corpo que cobre o segundo; ausente = nada. */
body?: BodyLabel;
/** Fração dos quadros com a cabeça visível (inclui a caixa do detector com o rosto de perfil). */
head?: number;
};
export type BodyMoment = { startS: number; endS: number; peakS: number; label: BodyLabel; value: number };
export type FaceView = {
fromS: number; toS: number; seconds: FaceMapSecond[]; moments: FaceReaction[];
/** Ausente no serviço antigo. */
body?: BodyMoment[];
}; };
export type Situation = "lag_ou_bug" | "jogada" | "falha_engracada" | "morte" | "susto" | "treta" | "conversa_engracada" export type Situation = "lag_ou_bug" | "jogada" | "falha_engracada" | "morte" | "susto" | "treta" | "conversa_engracada"
@@ -141,7 +164,8 @@ export type ClipAnalysis = {
/** Fonte em inglês: a fala do corte em frases (tempo da sessão) com a tradução em português. */ /** Fonte em inglês: a fala do corte em frases (tempo da sessão) com a tradução em português. */
export type ClipTranslation = { export type ClipTranslation = {
language: string; startS: number; endS: number; model?: string; language: string; startS: number; endS: number; model?: string;
lines: { s: number; e: number; text: string; pt: string }[]; /** `speaker` = quem fala a frase ("streamer" ou "other1", "other2"…; ausente nas traduções antigas = streamer). */
lines: { s: number; e: number; text: string; pt: string; speaker?: string }[];
}; };
export type ClipJudge = null export type ClipJudge = null
@@ -197,8 +221,34 @@ export type Clip = {
aspect?: Aspect; aspect?: Aspect;
/** Idioma da sessão de origem (resolvido pelo serviço). Opcional: o serviço antigo não manda (= padrão, pt-BR). */ /** Idioma da sessão de origem (resolvido pelo serviço). Opcional: o serviço antigo não manda (= padrão, pt-BR). */
language?: string; language?: string;
/** Vídeo de revisão (`file`): camadas de teste que entraram nele ([] = nenhuma; null = não se sabe). doc/clipador/REVISAO.md */
review?: { devLayers: string[] | null };
/** Vídeo final, gerado ao aprovar (sem as camadas de teste); null = ainda não aprovado. */
final?: ClipFinal | null;
/** O único arquivo que vai para as redes: o final pronto. null = ainda não (a publicação espera). */
publishFile?: string | null;
}; };
export type ClipFinal = {
status: "pending" | "rendering" | "ready" | "error";
file: string | null;
thumb: string | null;
cover: string | null;
error: string | null;
at: string | null;
/** O vídeo de revisão não tinha camada de teste: ele mesmo virou o final (sem render novo). */
reused: boolean;
};
/** Nome das camadas de teste do vídeo de revisão (grupo `dev` da configuração do corte). */
export const DEV_LAYER_LABEL: Record<string, string> = { translation: "tradução em português", dub: "dublagem em português" };
/** O vídeo de revisão (o da fila) tem camadas de teste? null = não se sabe (corte antigo). */
export function reviewHasDevLayers(clip: Pick<Clip, "review">): boolean | null {
const layers = clip.review?.devLayers;
return layers == null ? null : layers.length > 0;
}
/* ---------- Configuração do corte ---------- */ /* ---------- Configuração do corte ---------- */
/** Retângulo normalizado (0–1) sobre o quadro original 16:9; x, y = canto superior esquerdo. */ /** Retângulo normalizado (0–1) sobre o quadro original 16:9; x, y = canto superior esquerdo. */
@@ -212,11 +262,21 @@ export type CutSettings = {
caption: { caption: {
enabled: boolean; font: string; size: number; color: string; highlight: string; outline: string; enabled: boolean; font: string; size: number; color: string; highlight: string; outline: string;
outlineWidth: number; y: number | null; uppercase: boolean; maxWords: number; outlineWidth: number; y: number | null; uppercase: boolean; maxWords: number;
/** Fala de outra pessoa (colega no Discord, voz do jogo): cor e tamanho (null = 85 % de `size`). Serviço antigo não manda. */
otherColor?: string; otherSize?: number | null;
/** Legado: virou `dev.translation`. */ /** Legado: virou `dev.translation`. */
translation?: boolean; translation?: boolean;
}; };
/** Camadas só de desenvolvimento (vídeo de revisão); o vídeo final, depois de aprovar, sai sem elas. */ /** Camadas só de desenvolvimento (vídeo de revisão); o vídeo final, depois de aprovar, sai sem elas. */
dev?: { translation: boolean; dub: boolean }; dev?: {
translation: boolean; dub: boolean;
/** Dublagem (doc/clipador/DUBLAGEM.md): voz TTS pronta do serviço de voz — nunca clone do streamer. */
dubVoice?: string;
/** Voz das falas marcadas como de outra pessoa (`speaker: "other"`). */
dubVoiceOther?: string;
/** Volume do áudio original enquanto a dublagem toca (0–1). */
dubDuck?: number;
};
credit: { enabled: boolean; position: "top" | "bottom"; size: number }; credit: { enabled: boolean; position: "top" | "bottom"; size: number };
duration: { minS: number; maxS: number; backtrackS: number }; duration: { minS: number; maxS: number; backtrackS: number };
/** O serviço antigo não manda este grupo: use `withFormat` para preencher com vertical. */ /** O serviço antigo não manda este grupo: use `withFormat` para preencher com vertical. */
@@ -433,8 +493,15 @@ export const SOURCE_LABEL: Record<Clip["source"], string> = {
chat: "pico do chat", audio: "pico do áudio", manual: "corte manual", ai: "IA viu na tela", face: "reação no rosto", chat: "pico do chat", audio: "pico do áudio", manual: "corte manual", ai: "IA viu na tela", face: "reação no rosto",
}; };
export const FACE_LABEL: Record<FaceReaction["label"], string> = { export const FACE_LABEL: Record<FaceExpression, string> = {
risada: "risada", grito: "grito", susto: "susto", choque: "choque", confuso: "confuso", raiva: "raiva", neutro: "neutro", risada: "risada", grito: "grito", susto: "susto", choque: "choque", confuso: "confuso", raiva: "raiva", neutro: "neutro",
gargalhada: "gargalhada", alegria: "alegria", medo: "medo", espanto: "espanto", nojo: "nojo", tristeza: "tristeza",
tenso: "tensão", bocejo: "bocejo",
};
export const BODY_LABEL: Record<BodyLabel, string> = {
"balançando": "balançando a cabeça", acenando: "acenando com a cabeça", agitado: "agitado na cadeira",
"chegou perto": "chegou perto da câmera", "saiu do quadro": "saiu do quadro",
}; };
export const SITUATION_LABEL: Record<Situation, string> = { export const SITUATION_LABEL: Record<Situation, string> = {
+19 -4
View File
@@ -6,9 +6,11 @@
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import { CLIP_STATUS, SOURCE_LABEL, clipperCall, formatClock, formatDuration, languageLabel, useClipperAction, type Clip, type ClipperSession } from "./clipper-client"; import { CLIP_STATUS, SOURCE_LABEL, clipperCall, formatClock, formatDuration, languageLabel, useClipperAction, type Clip, type ClipperSession } from "./clipper-client";
import { import {
ChatSignals, ClipActions, ClipMedia, DeleteControl, FaceSignal, JudgeVerdict, TrimControl, situationLabel, type DeleteClip, ChatSignals, ClipActions, ClipMedia, ClipVideoState, DeleteControl, FaceSignal, JudgeVerdict, TrimControl, situationLabel, type DeleteClip,
} from "./clipper-clip-parts"; } from "./clipper-clip-parts";
import { isOther, speakerLabel } from "./clip-editor-model";
import { Dialog } from "./dialog"; import { Dialog } from "./dialog";
import { FaceMap } from "./clipper-face-map";
import { ArrowLeftIcon, ArrowRightIcon, CheckIcon, ClockIcon } from "./icons"; import { ArrowLeftIcon, ArrowRightIcon, CheckIcon, ClockIcon } from "./icons";
import type { PublishJob } from "./publishing-client"; import type { PublishJob } from "./publishing-client";
import { PublishChips, TextLink } from "./publishing-ui"; import { PublishChips, TextLink } from "./publishing-ui";
@@ -91,13 +93,17 @@ function ClipBody({ clip, onChanged, publishJobs }: { clip: Clip; onChanged: ()
} }
const showPublication = clip.status === "approved" || clip.status === "published"; const showPublication = clip.status === "approved" || clip.status === "published";
// Player: o vídeo final quando existe (é o que vai para as redes); dá para voltar ao de revisão.
const [show, setShow] = useState<"review" | "final">("final");
return ( return (
<div className="grid gap-6 md:grid-cols-[minmax(0,18rem)_minmax(0,1fr)]"> <div className="grid gap-6 md:grid-cols-[minmax(0,18rem)_minmax(0,1fr)]">
<div className="grid content-start gap-4"> <div className="grid content-start gap-4">
<ClipMedia clip={clip} version={videoVersion} /> <ClipMedia clip={clip} version={videoVersion} show={show} />
<ClipVideoState clip={clip} show={show} onShow={setShow} pending={pending} run={run} />
<ChatSignals clip={clip} /> <ChatSignals clip={clip} />
<FaceSignal clip={clip} /> <FaceSignal clip={clip} />
<FaceMap clip={clip} />
</div> </div>
<div className="grid min-w-0 content-start gap-5"> <div className="grid min-w-0 content-start gap-5">
@@ -168,6 +174,8 @@ function Portuguese({ clip, pending, run }: {
const pt = clip.judge && "pt" in clip.judge ? clip.judge.pt : undefined; const pt = clip.judge && "pt" in clip.judge ? clip.judge.pt : undefined;
const lines = clip.translation?.lines ?? []; const lines = clip.translation?.lines ?? [];
const english = (clip.language ?? "").toLowerCase().startsWith("en"); const english = (clip.language ?? "").toLowerCase().startsWith("en");
// Quem fala cada frase (doc/clipador/FALANTES.md): o streamer ou outra pessoa (colega no Discord, voz do jogo).
const others = lines.some((l) => isOther(l.speaker));
if (!english && !pt && !lines.length) return null; if (!english && !pt && !lines.length) return null;
const translate = () => run("translate", () => clipperCall<Clip>(`clips/${clip.id}/translate`, "POST"), "Fala traduzida."); const translate = () => run("translate", () => clipperCall<Clip>(`clips/${clip.id}/translate`, "POST"), "Fala traduzida.");
return ( return (
@@ -180,12 +188,19 @@ function Portuguese({ clip, pending, run }: {
{pt?.caption && <p className="text-[0.8125rem] leading-relaxed text-fg-muted">{pt.caption}</p>} {pt?.caption && <p className="text-[0.8125rem] leading-relaxed text-fg-muted">{pt.caption}</p>}
{lines.length > 0 ? ( {lines.length > 0 ? (
<details className="text-[0.8125rem]"> <details className="text-[0.8125rem]">
<summary className="cursor-pointer text-fg-muted select-none hover:text-fg">O que ele fala ({lines.length} frases)</summary> <summary className="cursor-pointer text-fg-muted select-none hover:text-fg">
{others ? "O que falam" : "O que ele fala"} ({lines.length} frases)
</summary>
<ol className="mt-2 grid gap-2"> <ol className="mt-2 grid gap-2">
{lines.map((line, i) => ( {lines.map((line, i) => (
<li key={i} className="grid grid-cols-[3.25rem_minmax(0,1fr)] gap-2"> <li key={i} className="grid grid-cols-[3.25rem_minmax(0,1fr)] gap-2">
<span className="pt-px font-mono text-[0.6875rem] text-fg-subtle tabular-nums">{formatClock(line.s - clip.startS)}</span> <span className="pt-px font-mono text-[0.6875rem] text-fg-subtle tabular-nums">{formatClock(line.s - clip.startS)}</span>
<span className="grid gap-0.5"> <span className={cx("grid gap-0.5", isOther(line.speaker) && "border-l-2 border-info/60 pl-2")}>
{others && (
<span className={cx("text-[0.6875rem] font-semibold", isOther(line.speaker) ? "text-info" : "text-fg-muted")}>
{speakerLabel(line.speaker)}
</span>
)}
<span className="text-fg">{line.pt}</span> <span className="text-fg">{line.pt}</span>
<span className="text-xs text-fg-subtle italic">{line.text}</span> <span className="text-xs text-fg-subtle italic">{line.text}</span>
</span> </span>
+105 -6
View File
@@ -5,7 +5,8 @@
// confirmação curta no lugar. Nada aqui busca dados: tudo vem por props; cada ação chama `run` (useClipperAction). // confirmação curta no lugar. Nada aqui busca dados: tudo vem por props; cada ação chama `run` (useClipperAction).
import { useEffect, useRef, useState, type ReactNode } from "react"; import { useEffect, useRef, useState, type ReactNode } from "react";
import { import {
ACTIVE_CLIP, CLIP_STATUS, FACE_LABEL, SITUATION_LABEL, TAG_LABEL, UNDELETABLE_CLIP, aspectOf, clipperCall, formatClock, formatDuration, formatScore, ACTIVE_CLIP, CLIP_STATUS, DEV_LAYER_LABEL, FACE_LABEL, SITUATION_LABEL, TAG_LABEL, UNDELETABLE_CLIP, aspectOf, clipperCall, formatClock, formatDuration, formatScore,
reviewHasDevLayers,
type Clip, type ClipAnalysis, type ClipTags, type Situation, type useClipperAction, type Clip, type ClipAnalysis, type ClipTags, type Situation, type useClipperAction,
} from "./clipper-client"; } from "./clipper-client";
import { ClipPublishButton } from "./clip-publish"; import { ClipPublishButton } from "./clip-publish";
@@ -84,14 +85,20 @@ export function DeleteControl({ clip, deleting, disabled, onDelete }: { clip: Cl
/* ---------- Cartão do corte ---------- */ /* ---------- Cartão do corte ---------- */
export function ClipMedia({ clip, version }: { clip: Clip; version: string }) { /** `show = "final"` toca o vídeo final (quando pronto); o padrão é o de revisão (o da fila). */
export function ClipMedia({ clip, version, show = "review" }: { clip: Clip; version: string; show?: "review" | "final" }) {
const busy = ACTIVE_CLIP.includes(clip.status); const busy = ACTIVE_CLIP.includes(clip.status);
const poster = clip.thumb ? fileUrl(clip.thumb) : undefined; const final = show === "final" && clip.final?.status === "ready" && clip.final.file ? clip.final : null;
const file = final ? final.file : clip.file;
const thumb = final?.thumb ?? clip.thumb;
const poster = thumb ? fileUrl(thumb) : undefined;
const frame = aspectOf(clip) === "horizontal" ? "aspect-video" : "aspect-9/16 max-sm:max-w-60"; const frame = aspectOf(clip) === "horizontal" ? "aspect-video" : "aspect-9/16 max-sm:max-w-60";
if (clip.file && !busy) { if (file && !busy) {
const v = final ? `final-${final.at ?? ""}` : version;
return ( return (
<video key={version} controls preload="metadata" poster={poster} aria-label={`Vídeo do corte: ${clip.title || clip.id}`} <video key={`${show}-${v}`} controls preload="metadata" poster={poster}
src={`${fileUrl(clip.file)}&v=${encodeURIComponent(version)}`} aria-label={`${final ? "Vídeo final" : "Vídeo de revisão"} do corte: ${clip.title || clip.id}`}
src={`${fileUrl(file)}&v=${encodeURIComponent(v)}`}
className={cx(frame, "w-full self-start rounded-control border border-line bg-sunken object-contain")} /> className={cx(frame, "w-full self-start rounded-control border border-line bg-sunken object-contain")} />
); );
} }
@@ -107,6 +114,98 @@ export function ClipMedia({ clip, version }: { clip: Clip; version: string }) {
); );
} }
/* ---------- Vídeo de revisão × vídeo final (doc/clipador/REVISAO.md) ---------- */
function devLayersText(clip: Clip): string {
const layers = clip.review?.devLayers ?? [];
return layers.map((l) => DEV_LAYER_LABEL[l] ?? l).join(", ");
}
/** Etiqueta curta para a lista: em que pé está o vídeo do corte (revisão com teste, final gerando/pronto/erro). */
export function VideoTag({ clip }: { clip: Clip }) {
const final = clip.final;
const tag = (tone: string, text: string, title: string) => (
<span className={cx("rounded-sm border px-1 text-[0.625rem]", tone)} title={title}>{text}</span>
);
if (final?.status === "pending" || final?.status === "rendering") {
return tag("border-info/40 text-info", "gerando final", "Aprovado: o vídeo final (sem as camadas de teste) está sendo gerado. A publicação espera por ele.");
}
if (final?.status === "error") return tag("border-danger/40 text-danger", "final com erro", `O vídeo final falhou: ${final.error ?? "erro"}. Abra o corte para tentar de novo.`);
if (final?.status === "ready") return tag("border-success/40 text-success", "final", "Vídeo final pronto: é ele que vai para as redes.");
if (clip.file && reviewHasDevLayers(clip) && clip.status !== "approved" && clip.status !== "published") {
return tag("border-warning/40 text-warning", "revisão · teste", `Vídeo de revisão com camadas de teste (${devLayersText(clip)}). Ao aprovar, sai o vídeo final sem elas.`);
}
return null;
}
/**
* Bloco do modal sob o vídeo: diz se o que está tocando é o vídeo de revisão (com camadas de teste) ou o final, mostra o
* estado do final depois de aprovar (gerando… / pronto / erro com "tentar de novo") e troca o player entre os dois.
*/
export function ClipVideoState({ clip, show, onShow, pending, run }: {
clip: Clip; show: "review" | "final"; onShow: (show: "review" | "final") => void; pending: string | null; run: Run;
}) {
if (!clip.file || ACTIVE_CLIP.includes(clip.status)) return null;
const final = clip.final;
const approved = clip.status === "approved" || clip.status === "published";
const hasDev = reviewHasDevLayers(clip);
const retry = (text: string) => run("final", () => clipperCall<Clip>(`clips/${clip.id}/final`, "POST"), text);
const canToggle = final?.status === "ready" && !final.reused;
let reviewNote: ReactNode;
if (final?.status === "ready" && final.reused) {
reviewNote = <>O vídeo de revisão não tinha camada de teste: <strong className="font-medium text-success">ele já é o vídeo final</strong>.</>;
} else if (hasDev === true) {
reviewNote = <>Vídeo de <strong className="font-medium text-warning">revisão (com camadas de teste)</strong>: {devLayersText(clip)}.
{!approved && " Ao aprovar, sai o vídeo final sem elas — é só ele que vai para as redes."}</>;
} else if (hasDev === false) {
reviewNote = <>Vídeo de revisão sem camadas de teste{approved ? "" : ": ao aprovar, ele mesmo vira o final"}.</>;
} else {
reviewNote = <>Vídeo de revisão{approved ? "" : " (ao aprovar, o vídeo final é gerado de novo, sem camadas de teste)"}.</>;
}
return (
<section aria-label="Vídeo de revisão e vídeo final" className="grid gap-2 text-xs leading-relaxed">
{canToggle && (
<div role="group" aria-label="Qual vídeo tocar" className="flex gap-1 rounded-control border border-line-strong bg-sunken/60 p-1">
{(["final", "review"] as const).map((v) => (
<button key={v} type="button" aria-pressed={show === v} onClick={() => onShow(v)}
className={cx("flex-1 rounded-[0.45rem] px-2 py-1 font-medium transition-colors focus-visible:outline-2 focus-visible:outline-accent",
show === v ? "bg-overlay text-fg" : "text-fg-muted hover:text-fg")}>
{v === "final" ? "Final" : "Revisão"}
</button>
))}
</div>
)}
{show === "final" && canToggle
? <p className="text-fg-muted">Tocando o <strong className="font-medium text-success">vídeo final</strong>: sem camadas de teste; é ele que vai para as redes.</p>
: <p className="text-fg-muted">{reviewNote}</p>}
{approved && (!final ? (
<div className="flex flex-wrap items-center gap-2 text-fg-subtle">
<span>Sem vídeo final ainda.</span>
<Button variant="ghost" size="sm" disabled={pending !== null} onClick={() => void retry("Vídeo final pedido.")}>
{pending === "final" ? <Spinner className="size-3.5" /> : <RefreshIcon size={15} />}Gerar vídeo final
</Button>
</div>
) : final.status === "pending" || final.status === "rendering" ? (
<p className="flex items-center gap-2 text-info" role="status">
<Spinner className="size-3.5" />{final.status === "pending" ? "Na fila para gerar o vídeo final…" : "Gerando o vídeo final…"} A publicação espera por ele.
</p>
) : final.status === "error" ? (
<div className="grid gap-1.5 rounded-control border border-danger/30 bg-danger-soft px-3 py-2 text-danger">
<span className="flex items-start gap-1.5"><AlertIcon size={14} className="mt-px shrink-0" />
<span>O vídeo final falhou: <span className="font-mono break-words">{final.error ?? "erro"}</span>. Nada é publicado até ele sair.</span></span>
<Button variant="secondary" size="sm" className="justify-self-start" disabled={pending !== null} onClick={() => void retry("Tentando de novo: o vídeo final entrou na fila.")}>
{pending === "final" ? <Spinner className="size-3.5" /> : <RefreshIcon size={15} />}Tentar de novo
</Button>
</div>
) : !final.reused ? (
<p className="flex items-center gap-1.5 text-success"><CheckIcon size={14} />Vídeo final pronto.</p>
) : null)}
</section>
);
}
export function JudgeVerdict({ clip }: { clip: Clip }) { export function JudgeVerdict({ clip }: { clip: Clip }) {
const judge = clip.judge; const judge = clip.judge;
if (!judge) { if (!judge) {
+2 -1
View File
@@ -8,7 +8,7 @@ import {
type Clip, type ClipperSession, type Clip, type ClipperSession,
} from "./clipper-client"; } from "./clipper-client";
import { ClipPublishButton } from "./clip-publish"; import { ClipPublishButton } from "./clip-publish";
import { canDelete, judgeScore, situationLabel, type DeleteClip } from "./clipper-clip-parts"; import { VideoTag, canDelete, judgeScore, situationLabel, type DeleteClip } from "./clipper-clip-parts";
import type { QueueFilter } from "./clipper-queue"; import type { QueueFilter } from "./clipper-queue";
import { ArrowRightIcon, CheckIcon, RefreshIcon, ScissorsIcon, SparkIcon, UndoIcon, XIcon } from "./icons"; import { ArrowRightIcon, CheckIcon, RefreshIcon, ScissorsIcon, SparkIcon, UndoIcon, XIcon } from "./icons";
import type { PublishJob } from "./publishing-client"; import type { PublishJob } from "./publishing-client";
@@ -133,6 +133,7 @@ function ClipRow({ clip, sessions, stage, nameOf, defaultLanguage, publishing, o
<span className="rounded-sm border border-line-strong px-1 font-mono text-[0.625rem] text-fg-muted" title={`Idioma da live: ${language}`}>{languageShort(language)}</span> <span className="rounded-sm border border-line-strong px-1 font-mono text-[0.625rem] text-fg-muted" title={`Idioma da live: ${language}`}>{languageShort(language)}</span>
)} )}
{horizontal && <span className="rounded-sm border border-line-strong px-1 text-[0.625rem] text-fg-muted">16:9</span>} {horizontal && <span className="rounded-sm border border-line-strong px-1 text-[0.625rem] text-fg-muted">16:9</span>}
<VideoTag clip={clip} />
</p> </p>
</div> </div>
</Td> </Td>
+85 -1
View File
@@ -18,7 +18,8 @@ import {
} from "./icons"; } from "./icons";
import { RECT_MIN_SIZE, clampRect, moveRect, nudgeRect, resizeRect } from "./rect-geometry"; import { RECT_MIN_SIZE, clampRect, moveRect, nudgeRect, resizeRect } from "./rect-geometry";
import { Tabs, type TabItem } from "./tabs"; import { Tabs, type TabItem } from "./tabs";
import { Badge, Button, ChoiceGroup, Feedback, RangeField, Spinner, Switch, cx, fileUrl } from "./ui"; import { Badge, Button, ChoiceGroup, Feedback, Field, RangeField, Select, Spinner, Switch, cx, fileUrl } from "./ui";
import type { VoiceInfo } from "./voice-client";
// Gancho e fontes (editor de cortes): seletor com amostra e fontes empacotadas carregadas no navegador. // Gancho e fontes (editor de cortes): seletor com amostra e fontes empacotadas carregadas no navegador.
import { HOOK_ANIM_LABEL, HOOK_STYLE_LABEL, SYSTEM_FONTS, hookOf, type HookAnim, type HookSettings, type HookStyle } from "./clipper-client"; import { HOOK_ANIM_LABEL, HOOK_STYLE_LABEL, SYSTEM_FONTS, hookOf, type HookAnim, type HookSettings, type HookStyle } from "./clipper-client";
import { FontPicker, fontStack, usePackagedFonts } from "./clip-editor-fonts"; import { FontPicker, fontStack, usePackagedFonts } from "./clip-editor-fonts";
@@ -505,6 +506,21 @@ function CutSettingsEditor({ scope, onDirty, onClose, onSaved }: {
</div> </div>
<RangeField label="Espessura do contorno" min={0} max={14} step={1} value={draft.caption.outlineWidth} <RangeField label="Espessura do contorno" min={0} max={14} step={1} value={draft.caption.outlineWidth}
onChange={(outlineWidth) => update("caption", { outlineWidth })} format={(v) => `${v} px`} /> onChange={(outlineWidth) => update("caption", { outlineWidth })} format={(v) => `${v} px`} />
<h4 className="pt-2 text-eyebrow font-semibold text-fg-subtle uppercase">Fala de outra pessoa</h4>
<p className="-mt-2 text-xs text-fg-subtle">
Colega no Discord ou outro jogador no chat de voz: a legenda dele sai logo abaixo da do streamer, nesta cor.
</p>
<div className="grid grid-cols-3 gap-2">
<ColorField label="Cor da outra pessoa" value={draft.caption.otherColor ?? "#5CE1FF"}
onChange={(otherColor) => update("caption", { otherColor })} />
</div>
<Switch label="Tamanho automático" checked={!draft.caption.otherSize}
onChange={(auto) => update("caption", { otherSize: auto ? null : Math.round(draft.caption.size * 0.85) })}
hint="85% do tamanho da legenda do streamer." />
{Boolean(draft.caption.otherSize) && (
<RangeField label="Tamanho da outra pessoa" min={30} max={140} step={2} value={draft.caption.otherSize ?? 70}
onChange={(otherSize) => update("caption", { otherSize })} format={(v) => `${v} px`} />
)}
</div> </div>
<div className="grid content-start gap-4"> <div className="grid content-start gap-4">
<h4 className="text-eyebrow font-semibold text-fg-subtle uppercase">Ritmo e posição</h4> <h4 className="text-eyebrow font-semibold text-fg-subtle uppercase">Ritmo e posição</h4>
@@ -523,6 +539,7 @@ function CutSettingsEditor({ scope, onDirty, onClose, onSaved }: {
<MockFigure aspect={aspect} layout={draft.layout} caption={draft.caption} credit={null} /> <MockFigure aspect={aspect} layout={draft.layout} caption={draft.caption} credit={null} />
</div> </div>
</fieldset> </fieldset>
<DubSettings dev={draft.dev} onChange={(values) => update("dev", values)} />
</Section> </Section>
); );
@@ -708,6 +725,68 @@ function CutSettingsEditor({ scope, onDirty, onClose, onSaved }: {
); );
} }
/* ----- Dublagem em português (camada de teste; doc/clipador/DUBLAGEM.md) ----- */
// Padrões do Clipador (layout.DEFAULTS["dev"]); valem com o serviço antigo, que ainda não manda as chaves.
const DUB_VOICE = "pt-br-antonio";
const DUB_VOICE_OTHER = "kokoro-pm-alex";
const DUB_DUCK = 0.25;
function voiceLabel(v: VoiceInfo): string {
const gender = v.gender === "male" ? "masculina" : v.gender === "female" ? "feminina" : null;
return [v.name, gender, v.offline ? "offline" : "online"].filter(Boolean).join(" · ");
}
/** Fica fora da caixa da legenda: a dublagem não depende de a legenda estar ligada. */
function DubSettings({ dev, onChange }: {
dev: CutSettings["dev"]; onChange: (values: Partial<NonNullable<CutSettings["dev"]>>) => void;
}) {
const on = dev?.dub ?? false;
const [voices, setVoices] = useState<VoiceInfo[] | null>(null);
useEffect(() => {
if (!on || voices) return;
let alive = true;
// Só vozes TTS prontas em português: voz clonada fica de fora (nunca imitar o streamer, que não consentiu).
fetch("/api/voice/status", { cache: "no-store" }).then((r) => r.json()).then((s: { voices?: VoiceInfo[] }) => {
if (alive) setVoices((s.voices ?? []).filter((v) => v.provider !== "clone" && (v.languages ?? []).some((l) => l.toLowerCase().startsWith("pt"))));
}).catch(() => { if (alive) setVoices([]); });
return () => { alive = false; };
}, [on, voices]);
const voice = dev?.dubVoice ?? DUB_VOICE;
const other = dev?.dubVoiceOther ?? DUB_VOICE_OTHER;
const duck = dev?.dubDuck ?? DUB_DUCK;
const options = (current: string) => {
const list = voices ?? [];
// A voz salva aparece mesmo se o serviço estiver fora (ou se ela sair do catálogo).
return list.some((v) => v.id === current) ? list : [{ id: current, name: current } as VoiceInfo, ...list];
};
return (
<div className="mt-6 grid gap-x-8 gap-y-4 border-t border-line pt-5 xl:grid-cols-2">
<Switch label="Dublagem em português (teste)" checked={on} onChange={(dub) => onChange({ dub })}
hint={"Só no vídeo de revisão (fonte em inglês): cada frase traduzida é dublada por uma voz TTS pronta e o áudio original fica baixo por baixo — dá para ouvir o jogo. O 1º render demora mais (~1,6 s por frase; depois fica guardado). O vídeo final, ao aprovar, sai com o áudio original."} />
{on && (
<div className="grid content-start gap-4">
{voices === null && <p role="status" className="flex items-center gap-2 text-xs text-fg-subtle"><Spinner className="size-3" />Carregando as vozes…</p>}
{voices !== null && voices.length === 0 && <Note tone="warning">Serviço de voz fora do ar: a dublagem não sai até ele voltar.</Note>}
<Field label="Voz do streamer">
<Select value={voice} onChange={(e) => onChange({ dubVoice: e.target.value })}>
{options(voice).map((v) => <option key={v.id} value={v.id}>{v.languages ? voiceLabel(v) : v.id}</option>)}
</Select>
</Field>
<Field label="Voz de outra pessoa" hint="Para as falas de quem não é o streamer, quando a transcrição separar quem fala.">
<Select value={other} onChange={(e) => onChange({ dubVoiceOther: e.target.value })}>
{options(other).map((v) => <option key={v.id} value={v.id}>{v.languages ? voiceLabel(v) : v.id}</option>)}
</Select>
</Field>
<RangeField label="Volume do áudio original durante a dublagem" min={0} max={1} step={0.05} value={duck}
onChange={(dubDuck) => onChange({ dubDuck })} format={pct}
hint="Fora das falas dubladas o áudio fica normal." />
</div>
)}
</div>
);
}
function countFields(layer: CutLayer | null | undefined): number { function countFields(layer: CutLayer | null | undefined): number {
return Object.values(layer ?? {}).reduce((n, g) => n + Object.keys(g ?? {}).length, 0); return Object.values(layer ?? {}).reduce((n, g) => n + Object.keys(g ?? {}).length, 0);
} }
@@ -916,6 +995,11 @@ function CaptionSample({ caption }: { caption: CutSettings["caption"] }) {
}}> }}>
{words.map((w, i) => <span key={w} style={i === 1 ? { color: caption.highlight } : undefined}>{w}{i < words.length - 1 ? " " : ""}</span>)} {words.map((w, i) => <span key={w} style={i === 1 ? { color: caption.highlight } : undefined}>{w}{i < words.length - 1 ? " " : ""}</span>)}
</span> </span>
{/* A fala de outra pessoa (colega no Discord), logo abaixo e na cor dela. */}
<span className="text-center text-lg leading-tight" style={{
fontFamily: fontStack(caption.font), fontWeight: 900, color: caption.otherColor ?? "#5CE1FF",
WebkitTextStroke: stroke ? `${stroke}px ${caption.outline}` : undefined, paintOrder: "stroke fill",
}}>{caption.uppercase ? "E O COLEGA" : "e o colega"}</span>
</div> </div>
); );
} }
+102
View File
@@ -0,0 +1,102 @@
"use client";
// Mapa de expressões de UM corte: uma faixa com a expressão dominante do streamer em cada segundo do trecho (cor por
// família) e, embaixo, o movimento do corpo (balançando, agitado, saiu do quadro…), que aparece mesmo quando o rosto
// está de perfil e não dá para ler expressão. Busca a série sozinho (GET sessions/{id}/face do trecho), ao contrário
// das peças de clipper-clip-parts. Serviço antigo (sem `expr`) ou corte sem câmera: não mostra nada.
import { useEffect, useState } from "react";
import {
BODY_LABEL, FACE_LABEL, clipperCall, formatClock,
type BodyLabel, type Clip, type FaceExpression, type FaceMapSecond, type FaceView,
} from "./clipper-client";
import { Spinner, cx } from "./ui";
/** Cor de cada expressão, por família: alegria (verde), susto/surpresa (amarelo), raiva/grito (vermelho), tristeza e
* tensão (azul), confusão (violeta); neutro e bocejo quase somem. */
const EXPR_TONE: Record<FaceExpression, string> = {
risada: "bg-success", gargalhada: "bg-success", alegria: "bg-success/45",
susto: "bg-warning", choque: "bg-warning/80", espanto: "bg-warning/60", medo: "bg-glow",
grito: "bg-flame", raiva: "bg-danger", nojo: "bg-option-d",
tristeza: "bg-info", tenso: "bg-option-b/70", confuso: "bg-option-c",
bocejo: "bg-fg-subtle/30", neutro: "bg-line-strong",
};
type Load = { state: "loading" } | { state: "error"; text: string } | { state: "ok"; view: FaceView };
export function FaceMap({ clip }: { clip: Clip }) {
const from = Math.floor(clip.startS);
const to = Math.ceil(clip.endS);
const [load, setLoad] = useState<Load>({ state: "loading" });
useEffect(() => {
let alive = true;
setLoad({ state: "loading" });
void clipperCall<FaceView>(`sessions/${clip.sessionId}/face?from=${from}&to=${to}`).then((r) => {
if (alive) setLoad(r.ok ? { state: "ok", view: r.data } : { state: "error", text: r.error });
});
return () => { alive = false; };
}, [clip.sessionId, from, to]);
if (load.state === "loading") {
return <p className="flex items-center gap-2 text-xs text-fg-subtle"><Spinner className="size-3.5" />Lendo o mapa de expressões…</p>;
}
if (load.state === "error") return null; // sem câmera, rastreio desligado ou serviço fora: o resto do modal segue
const seconds = load.view.seconds.filter((s) => s.t >= from && s.t < to);
const hasMap = seconds.some((s) => s.expr || s.body);
if (!seconds.length || !hasMap) return null;
const counts = new Map<FaceExpression, number>();
for (const s of seconds) if (s.expr && s.expr !== "neutro") counts.set(s.expr, (counts.get(s.expr) ?? 0) + 1);
const legend = [...counts.entries()].sort((a, b) => b[1] - a[1]).slice(0, 6);
const bodies = (load.view.body ?? []).filter((b) => b.endS >= from && b.startS < to);
const withFace = seconds.filter((s) => s.expr).length;
const summary = [
legend.length ? `Expressões: ${legend.map(([k, n]) => `${FACE_LABEL[k] ?? k} ${n} s`).join(", ")}` : "Sem expressão marcante",
bodies.length ? `corpo: ${bodies.map((b) => `${BODY_LABEL[b.label] ?? b.label} em ${formatClock(b.peakS)}`).join(", ")}` : "",
].filter(Boolean).join("; ");
return (
<section aria-label="Mapa de expressões do corte" className="grid gap-1.5">
<h3 className="flex items-baseline justify-between gap-2 text-eyebrow font-semibold text-fg-subtle uppercase">
Mapa de expressões
<span className="font-normal normal-case tabular-nums">
{withFace < seconds.length ? `rosto legível em ${Math.round((100 * withFace) / seconds.length)}%` : `${seconds.length} s`}
</span>
</h3>
<div role="img" aria-label={summary} className="grid gap-0.5">
<Strip seconds={seconds} pick={(s) => (s.expr ? EXPR_TONE[s.expr] ?? "bg-line-strong" : "")}
title={(s) => `${formatClock(s.t)} · ${s.expr ? FACE_LABEL[s.expr] ?? s.expr : (s.head ?? 0) > 0 ? "rosto de perfil (sem expressão legível)" : "sem rosto"}`}
className="h-4" />
{bodies.length > 0 && (
<Strip seconds={seconds} pick={(s) => (s.body ? "bg-accent" : "")}
title={(s) => `${formatClock(s.t)} · ${s.body ? BODY_LABEL[s.body] ?? s.body : "corpo parado"}`} className="h-1.5" />
)}
</div>
<ul className="flex flex-wrap gap-x-3 gap-y-1 text-[0.75rem] text-fg-muted">
{legend.map(([k, n]) => (
<li key={k} className="inline-flex items-center gap-1.5">
<span aria-hidden className={cx("size-2.5 rounded-sm", EXPR_TONE[k])} />{FACE_LABEL[k] ?? k}
<span className="text-fg-subtle tabular-nums">{n} s</span>
</li>
))}
{bodies.map((b) => (
<li key={`${b.label}-${b.startS}`} className="inline-flex items-center gap-1.5">
<span aria-hidden className="h-1.5 w-2.5 rounded-sm bg-accent" />{BODY_LABEL[b.label as BodyLabel] ?? b.label}
<span className="text-fg-subtle tabular-nums">{formatClock(b.peakS)}</span>
</li>
))}
{!legend.length && !bodies.length && <li className="text-fg-subtle">rosto neutro no trecho</li>}
</ul>
</section>
);
}
/** Uma faixa: uma célula por segundo (cor de `pick`; vazio = sem dado), dica com `title` ao passar o mouse. */
function Strip({ seconds, pick, title, className }: {
seconds: FaceMapSecond[]; pick: (s: FaceMapSecond) => string; title: (s: FaceMapSecond) => string; className?: string;
}) {
return (
<div className={cx("flex overflow-hidden rounded-sm bg-sunken/60", className)}>
{seconds.map((s) => <span key={s.t} title={title(s)} className={cx("min-w-0 flex-1", pick(s))} />)}
</div>
);
}
+7 -2
View File
@@ -30,14 +30,19 @@ function serviceUrl(pathname: string): { url: string; key: string } {
* status · judge · emotes · games[/id[/research|refine|translate|notes/n]] (POST games = cadastrar; PUT/DELETE games/id) · channels[/id[/check|settings]] * status · judge · emotes · games[/id[/research|refine|translate|notes/n]] (POST games = cadastrar; PUT/DELETE games/id) · channels[/id[/check|settings]]
* sessions[/id[/timeline|stop|resume|finish|clips|settings|frame|preview|detect-cam|game|face[/reset]]] · clips[/id[/render|rejudge]] * sessions[/id[/timeline|stop|resume|finish|clips|settings|frame|preview|detect-cam|game|face[/reset]]] · clips[/id[/render|rejudge]]
* editor de cortes: clips/id/(edit|proxy|waveform|export|preview-render|retranscribe|tts|suggest) * editor de cortes: clips/id/(edit|proxy|waveform|export|preview-render|retranscribe|tts|suggest)
* vídeo final (doc/clipador/REVISAO.md): POST clips/id/final · tradução da fala (IDIOMAS.md): POST clips/id/translate
* vozes da sessão (FALANTES.md): GET sessions/id/speakers
* apagar cortes: DELETE clips/id · POST clips/delete (lote) — o método é conferido em METHODS * apagar cortes: DELETE clips/id · POST clips/delete (lote) — o método é conferido em METHODS
*/ */
const ALLOWED = /^(status|judge|emotes|games(\/[a-z0-9-]{1,60}(\/(research|refine|translate|notes\/\d{1,3}))?)?|channels(\/(twitch|youtube|kick)-[a-z0-9._-]{2,60}(\/(check|settings))?)?|sessions(\/\d{1,9}(\/(timeline|stop|resume|finish|clips|settings|frame|preview|detect-cam|game|face(\/reset)?))?)?|clips(\/(delete|\d{1,9}(\/(render|rejudge|edit|proxy|waveform|export|preview-render|retranscribe|tts|suggest))?))?)$/; const ALLOWED = /^(status|judge|emotes|games(\/[a-z0-9-]{1,60}(\/(research|refine|translate|notes\/\d{1,3}))?)?|channels(\/(twitch|youtube|kick)-[a-z0-9._-]{2,60}(\/(check|settings))?)?|sessions(\/\d{1,9}(\/(timeline|stop|resume|finish|clips|settings|frame|preview|detect-cam|game|face(\/reset)?|speakers))?)?|clips(\/(delete|\d{1,9}(\/(render|rejudge|edit|proxy|waveform|export|preview-render|retranscribe|tts|suggest|final|translate))?))?)$/;
/** Métodos aceitos nos caminhos de apagar corte (os demais caminhos seguem só pela regex acima). */ /** Métodos aceitos nos caminhos de apagar corte (os demais caminhos seguem só pela regex acima). */
const METHODS: [RegExp, string[]][] = [ const METHODS: [RegExp, string[]][] = [
[/^clips\/delete$/, ["POST"]], [/^clips\/delete$/, ["POST"]],
[/^clips\/\d{1,9}$/, ["GET", "PATCH", "DELETE"]], [/^clips\/\d{1,9}$/, ["GET", "PATCH", "DELETE"]],
[/^clips\/\d{1,9}\/final$/, ["POST"]],
[/^clips\/\d{1,9}\/translate$/, ["POST"]],
[/^sessions\/\d{1,9}\/speakers$/, ["GET"]],
// Jogos: listar e cadastrar; gravar a edição (PUT ?lang=pt|en) e apagar (doc/clipador/JOGOS.md). // Jogos: listar e cadastrar; gravar a edição (PUT ?lang=pt|en) e apagar (doc/clipador/JOGOS.md).
[/^games$/, ["GET", "POST"]], [/^games$/, ["GET", "POST"]],
[/^games\/[a-z0-9-]{1,60}$/, ["PUT", "DELETE"]], [/^games\/[a-z0-9-]{1,60}$/, ["PUT", "DELETE"]],
@@ -71,7 +76,7 @@ export async function proxy(request: Request, segments: string[]): Promise<Respo
const timeoutMs = /^games\/[^/]+\/(research|refine)$/.test(sub) ? 480_000 const timeoutMs = /^games\/[^/]+\/(research|refine)$/.test(sub) ? 480_000
: /^games\/[^/]+\/translate$/.test(sub) || (/^games\/[^/]+$/.test(sub) && method === "PUT") ? 300_000 : /^games\/[^/]+\/translate$/.test(sub) || (/^games\/[^/]+$/.test(sub) && method === "PUT") ? 300_000
: sub === "games" && method === "POST" ? 30_000 : sub === "games" && method === "POST" ? 30_000
: /^clips\/\d+\/(proxy|preview-render|retranscribe|tts|suggest|waveform)$/.test(sub) ? 300_000 : /^clips\/\d+\/(proxy|preview-render|retranscribe|tts|suggest|waveform|translate)$/.test(sub) ? 300_000
: /\/(detect-cam|preview|check)$/.test(sub) ? 180_000 : /\/(detect-cam|preview|check)$/.test(sub) ? 180_000
: /^sessions\/\d+\/face(\/reset)?$/.test(sub) ? 30_000 : 120_000; : /^sessions\/\d+\/face(\/reset)?$/.test(sub) ? 30_000 : 120_000;
const response = await clipperFetch(`/v1/${sub}${search}`, { const response = await clipperFetch(`/v1/${sub}${search}`, {
+14 -7
View File
@@ -312,6 +312,8 @@ type Focus = { kind: "element"; element: El["kind"] } | { kind: "animal" };
/** O assunto do trecho: o 1º objeto ou bicho citado na NARRAÇÃO (é do que o vídeo está falando naquele momento); /** O assunto do trecho: o 1º objeto ou bicho citado na NARRAÇÃO (é do que o vídeo está falando naquele momento);
* sem nenhum, uma peça citada na coluna Imagem. */ * sem nenhum, uma peça citada na coluna Imagem. */
function focusOf(narration: string, direction: string): Focus | null { function focusOf(narration: string, direction: string): Focus | null {
// Objeto procurado, não encontrado ou só "parecido" não aparece pronto na cena (seria afirmar o contrário do texto).
if (/\b(procur\w*|busca\w*|sem sucesso|nunca (foi )?encontrad\w*|lembra (um|uma)|em forma de|forma de (barco|arca)|nao ha comprovacao)\b/.test(narration)) return null;
const hits: { at: number; f: Focus }[] = []; const hits: { at: number; f: Focus }[] = [];
for (const [re, element] of FOCUS_ELEMENTS) { const at = narration.search(re); if (at >= 0) hits.push({ at, f: { kind: "element", element } }); } for (const [re, element] of FOCUS_ELEMENTS) { const at = narration.search(re); if (at >= 0) hits.push({ at, f: { kind: "element", element } }); }
const a = narration.search(FOCUS_ANIMALS); const a = narration.search(FOCUS_ANIMALS);
@@ -330,21 +332,26 @@ const INSIDE = /\b(dentro d[aoe]|a bordo|embarc\w*|entr(a|am|ou|aram) n[ao] (arc
*/ */
function stageFocus(place: Place, focus: Focus, text: string, n: number): { xs: number[]; ys: number[]; scale: number } | null { function stageFocus(place: Place, focus: Focus, text: string, n: number): { xs: number[]; ys: number[]; scale: number } | null {
const side = (count: number) => ({ xs: Array.from({ length: count }, (_, i) => (i % 2 === 0 ? 0.15 : 0.85) + (i > 1 ? (i % 2 === 0 ? 0.1 : -0.1) : 0)), ys: Array.from({ length: count }, (_, i) => 0.8 + (i > 1 ? 0.03 : 0)), scale: count > 2 ? 0.6 : 0.72 }); const side = (count: number) => ({ xs: Array.from({ length: count }, (_, i) => (i % 2 === 0 ? 0.15 : 0.85) + (i > 1 ? (i % 2 === 0 ? 0.1 : -0.1) : 0)), ys: Array.from({ length: count }, (_, i) => 0.8 + (i > 1 ? 0.03 : 0)), scale: count > 2 ? 0.6 : 0.72 });
if (focus.kind === "animal") return n ? side(n) : null; // Ninguém fica em pé na água: com chão de água e um barco em cena, quem aparece está DENTRO dele, seja qual for
const family: El["kind"][] = focus.element === "ark" ? ["ark", "ark_frame"] : [focus.element]; // o assunto falado (o corvo, a pomba…).
let el = place.elements.find((e) => family.includes(e.kind)); const boat = place.ground === "water" && n > 0 ? place.elements.find((e) => e.kind === "ark") : undefined;
if (!el) { if (focus.kind === "animal" && !boat) return n ? side(n) : null;
const family: El["kind"][] = boat ? ["ark"] : focus.kind === "element" && focus.element === "ark" ? ["ark", "ark_frame"] : focus.kind === "element" ? [focus.element] : [];
let el = boat ?? place.elements.find((e) => family.includes(e.kind));
if (!el && focus.kind === "element") {
if (place.indoor) return null; if (place.indoor) return null;
el = { kind: focus.element === "ark" && /constru/.test(text) && !/pronta/.test(text) ? "ark_frame" : focus.element, x: 0.5, z: 0.4 }; el = { kind: focus.element === "ark" && /constru/.test(text) && !/pronta/.test(text) ? "ark_frame" : focus.element, x: 0.5, z: 0.4 };
place.elements.push(el); place.elements.push(el);
} }
if (!el) return n ? side(n) : null;
if (el.kind === "rainbow") return n ? side(n) : null; if (el.kind === "rainbow") return n ? side(n) : null;
el.x = 0.5; el.x = 0.5;
const occupiable = el.kind === "ark" || el.kind === "car"; const occupiable = el.kind === "ark" || el.kind === "car";
const inside = occupiable && n > 0 && (INSIDE.test(text) || (el.kind === "ark" && place.ground === "water")); const inside = occupiable && n > 0 && (!!boat || INSIDE.test(text));
if (!inside) { if (!inside) {
if (!el.lift) el.z = Math.min(el.z ?? 0.4, 0.42); // O assunto grande, na frente do meio da cena (o personagem pequeno ao lado dá a escala).
el.scale = Math.max(el.scale ?? 1, el.kind === "ark" || el.kind === "ark_frame" ? 1.2 : 1.3); if (!el.lift) el.z = Math.min(el.z ?? 0.4, 0.35);
el.scale = Math.max(el.scale ?? 1, el.kind === "ark" || el.kind === "ark_frame" ? 1.35 : 1.4);
return n ? side(n) : null; return n ? side(n) : null;
} }
// Dentro: a peça vem para a frente e os personagens ficam no convés, da cintura para cima. // Dentro: a peça vem para a frente e os personagens ficam no convés, da cintura para cima.
+43
View File
@@ -234,8 +234,19 @@ describe("despachante: corridas, clientRef e vínculos (ALTOS)", () => {
}; };
const clearQueue = () => dbm.run(`UPDATE publish_jobs SET status = 'canceled', cancel_reason = 'user' const clearQueue = () => dbm.run(`UPDATE publish_jobs SET status = 'canceled', cancel_reason = 'user'
WHERE status IN ('queued', 'scheduled', 'awaiting_approval', 'publishing')`); WHERE status IN ('queued', 'scheduled', 'awaiting_approval', 'publishing')`);
// Clipador falso: cada corte responde aprovado e com o vídeo final pronto (doc/clipador/REVISAO.md); `finals`
// troca isso por corte. A listagem fica fora do ar (nada de sincronizar cortes neste bloco, como antes).
const clipperEnv = path.join(ROOT, "clipper", ".env");
const finals = new Map<string, { publishFile: string | null; final: { status: string; error: string | null } | null }>();
const clipBody = (id: string) => ({
id: Number(id), status: "approved", channelId: "twitch-xis", createdAt: "2026-11-01T00:00:00.000Z", title: "Corte", caption: "#corte",
file: MP4, thumb: null, edit: null,
...(finals.get(id) ?? { publishFile: MP4, final: { status: "ready", error: null, cover: null } }),
});
before(() => { before(() => {
fs.mkdirSync(path.dirname(clipperEnv), { recursive: true });
fs.writeFileSync(clipperEnv, "CLIPPER_SERVICE_KEY=chave-de-teste\nCLIPPER_PORT=4520\n");
fs.mkdirSync(path.join(ROOT, "publisher"), { recursive: true }); fs.mkdirSync(path.join(ROOT, "publisher"), { recursive: true });
fs.writeFileSync(path.join(ROOT, "publisher", ".env"), "PUBLISHER_SERVICE_KEY=chave-de-teste\nPUBLISHER_PORT=4530\n"); fs.writeFileSync(path.join(ROOT, "publisher", ".env"), "PUBLISHER_SERVICE_KEY=chave-de-teste\nPUBLISHER_PORT=4530\n");
dbm.run("UPDATE account_networks SET status = 'connected', mode = 'official', enabled = 1 WHERE account_id = 'canal'"); dbm.run("UPDATE account_networks SET status = 'connected', mode = 'official', enabled = 1 WHERE account_id = 'canal'");
@@ -247,6 +258,9 @@ describe("despachante: corridas, clientRef e vínculos (ALTOS)", () => {
const body = typeof init?.body === "string" ? (JSON.parse(init.body) as Record<string, unknown>) : null; const body = typeof init?.body === "string" ? (JSON.parse(init.body) as Record<string, unknown>) : null;
calls.push({ method, path: url.pathname, body }); calls.push({ method, path: url.pathname, body });
if (url.pathname === "/v1/status") return json({ browser: { found: true, kind: "chrome", path: "x" }, worker: "idle", queue: 0 }); if (url.pathname === "/v1/status") return json({ browser: { found: true, kind: "chrome", path: "x" }, worker: "idle", queue: 0 });
if (url.pathname === "/v1/clips") throw new TypeError("fetch failed");
const clip = /^\/v1\/clips\/(\d+)$/.exec(url.pathname);
if (clip) return json(clipBody(clip[1]));
const prof = /^\/v1\/profiles\/([^/]+)$/.exec(url.pathname); const prof = /^\/v1\/profiles\/([^/]+)$/.exec(url.pathname);
if (prof && method === "GET") return json(profile(decodeURIComponent(prof[1]))); if (prof && method === "GET") return json(profile(decodeURIComponent(prof[1])));
if (url.pathname === "/v1/jobs" && method === "POST") return onCreate(body!); if (url.pathname === "/v1/jobs" && method === "POST") return onCreate(body!);
@@ -260,6 +274,35 @@ describe("despachante: corridas, clientRef e vínculos (ALTOS)", () => {
after(() => { after(() => {
globalThis.fetch = realFetch; globalThis.fetch = realFetch;
fs.rmSync(clipperEnv, { force: true });
});
it("corte sem vídeo final pronto espera na fila; com o final pronto sai com o arquivo FINAL, nunca o de revisão", async () => {
clearQueue();
const id = queuedClipJob();
const sourceId = dbm.get<{ source_id: string }>("SELECT source_id FROM publish_jobs WHERE id = ?", id)!.source_id;
const files: string[] = [];
onCreate = async (body) => { files.push(String(body.file)); return json(remoteJob("pj-final"), 201); };
finals.set(sourceId, { publishFile: null, final: { status: "rendering", error: null } });
await pub.dispatcherTick();
let job = pub.getJobView(id)!;
assert.equal(job.status, "queued");
assert.match(job.step, /vídeo final/);
finals.set(sourceId, { publishFile: null, final: { status: "error", error: "ffmpeg caiu" } });
await pub.dispatcherTick();
assert.equal(pub.getJobView(id)!.status, "queued");
assert.deepEqual(files, []); // nada foi ao Publicador enquanto não havia final
const finalFile = "output/clipper/3/clip-9-final.mp4";
fs.mkdirSync(path.join(ROOT, "output", "clipper", "3"), { recursive: true });
fs.writeFileSync(path.join(ROOT, finalFile), "mp4 final");
finals.set(sourceId, { publishFile: finalFile, final: { status: "ready", error: null } });
await pub.dispatcherTick();
job = pub.getJobView(id)!;
assert.equal(job.status, "publishing");
assert.equal(job.file, finalFile);
assert.deepEqual(files, [path.resolve(ROOT, finalFile)]);
finals.delete(sourceId);
}); });
it("cancelar enquanto o Publicador cria o envio: o job fica cancelado e o envio é cancelado lá", async () => { it("cancelar enquanto o Publicador cria o envio: o job fica cancelado e o envio é cancelado lá", async () => {
+23 -1
View File
@@ -4,7 +4,7 @@
import assert from "node:assert/strict"; import assert from "node:assert/strict";
import { describe, it } from "node:test"; import { describe, it } from "node:test";
import { import {
DEFAULT_SLOTS, clientRefFor, isDue, localDay, mayBeLive, needsReflow, nextFreeSlot, parseVideoUrl, placeJob, planClipSync, readPublisherJob, sendBlocker, DEFAULT_SLOTS, clientRefFor, clipPublishFile, isDue, localDay, mayBeLive, needsReflow, nextFreeSlot, parseVideoUrl, placeJob, planClipSync, readPublisherJob, sendBlocker,
tagsFromCaption, zonedTimeToUtc, type ClipInfo, type ClipTarget, type ExistingJob, tagsFromCaption, zonedTimeToUtc, type ClipInfo, type ClipTarget, type ExistingJob,
} from "./publishing-rules"; } from "./publishing-rules";
@@ -254,3 +254,25 @@ describe("envio: idempotência, reencaixe e confirmação", () => {
assert.match(sendBlocker({ status: "expired", enabled: 1 }, false)!, /venceu/); assert.match(sendBlocker({ status: "expired", enabled: 1 }, false)!, /venceu/);
}); });
}); });
describe("corte: só o vídeo final vai para as redes (doc/clipador/REVISAO.md)", () => {
const review = "output/clipper/3/clip-9.mp4";
it("final pronto: publica o final, não o de revisão", () => {
assert.deepEqual(clipPublishFile({ file: review, publishFile: "output/clipper/3/clip-9-final.mp4", final: { status: "ready", error: null } }),
{ file: "output/clipper/3/clip-9-final.mp4" });
});
it("sem final pronto espera, nunca devolve o vídeo de revisão", () => {
for (const final of [null, { status: "pending" as const, error: null }, { status: "rendering" as const, error: null }, { status: "error" as const, error: "ffmpeg" }]) {
const target = clipPublishFile({ file: review, publishFile: null, final });
assert.ok("wait" in target, JSON.stringify(final));
}
assert.match((clipPublishFile({ file: review, publishFile: null, final: { status: "error", error: "ffmpeg caiu" } }) as { wait: string }).wait, /ffmpeg caiu/);
});
it("Clipador antigo (sem `publishFile`) continua usando o arquivo do corte", () => {
assert.deepEqual(clipPublishFile({ file: review }), { file: review });
assert.ok("wait" in clipPublishFile({ file: null }));
});
});
+25
View File
@@ -182,6 +182,31 @@ export type ClipAction =
| { kind: "forget_auto"; clipId: number } | { kind: "forget_auto"; clipId: number }
| { kind: "mark_clip_published"; clipId: number }; | { kind: "mark_clip_published"; clipId: number };
/** O que o Clipador diz do vídeo de um corte (doc/clipador/REVISAO.md). `publishFile` ausente = Clipador antigo. */
export type ClipVideo = {
file: string | null;
publishFile?: string | null;
final?: { status: "pending" | "rendering" | "ready" | "error"; error: string | null } | null;
};
/**
* Arquivo de um corte que pode ir para as redes: SÓ o vídeo final (sem as camadas de teste do vídeo de revisão).
* Sem final pronto, devolve o motivo de esperar — nunca o vídeo de revisão (`file`). Clipador antigo (sem o campo
* `publishFile`) não tem vídeo de revisão separado: vale `file`.
*/
export function clipPublishFile(clip: ClipVideo): { file: string } | { wait: string } {
if (clip.publishFile) return { file: clip.publishFile };
if (clip.publishFile === undefined) return clip.file ? { file: clip.file } : { wait: "Esperando: o corte ainda não tem vídeo pronto." };
const final = clip.final;
if (final?.status === "pending" || final?.status === "rendering") {
return { wait: "Esperando o vídeo final do Clipador (gerando, sem as camadas de teste)." };
}
if (final?.status === "error") {
return { wait: `Esperando: o vídeo final deu erro no Clipador (${final.error ?? "erro"}). Use “Tentar de novo” no corte.` };
}
return { wait: "Esperando o vídeo final: o corte precisa estar aprovado no Clipador." };
}
const PUBLISHABLE = new Set(["ready", "approved"]); const PUBLISHABLE = new Set(["ready", "approved"]);
/** Estados do corte em que os jobs não enviados continuam válidos. */ /** Estados do corte em que os jobs não enviados continuam válidos. */
const KEEPS_JOBS = new Set(["ready", "approved", "published"]); const KEEPS_JOBS = new Set(["ready", "approved", "published"]);
+41 -8
View File
@@ -19,9 +19,9 @@ import { ServiceError } from "./http";
import { REPO_ROOT, SERVABLE_ROOTS, resolveInside, storyDir } from "./paths"; import { REPO_ROOT, SERVABLE_ROOTS, resolveInside, storyDir } from "./paths";
import { cancelJob, createJob, getJob, profileIdFor, publisherStatus, type PublisherJob } from "./publisher"; import { cancelJob, createJob, getJob, profileIdFor, publisherStatus, type PublisherJob } from "./publisher";
import { import {
OCCUPYING, UNSENT, aiGeneratedFor, clientRefFor, isDue, jobActions, mayBeLive, needsReflow, parseVideoUrl, placeJob, planClipSync, readPublisherJob, OCCUPYING, UNSENT, aiGeneratedFor, clientRefFor, clipPublishFile, isDue, jobActions, mayBeLive, needsReflow, parseVideoUrl, placeJob, planClipSync, readPublisherJob,
sendBlocker, tagsFromCaption, sendBlocker, tagsFromCaption,
type ClipAction, type ClipInfo, type ClipTarget, type ExistingJob, type ClipAction, type ClipInfo, type ClipTarget, type ClipVideo, type ExistingJob,
} from "./publishing-rules"; } from "./publishing-rules";
import { autoCollectMetrics } from "./metrics-sync"; import { autoCollectMetrics } from "./metrics-sync";
import { getSettings } from "./settings"; import { getSettings } from "./settings";
@@ -197,8 +197,14 @@ export function placeApproved(jobId: number, opts: {
type ClipView = { type ClipView = {
id: number; status: string; channelId: string | null; createdAt: string; title: string; caption: string; id: number; status: string; channelId: string | null; createdAt: string; title: string; caption: string;
file: string | null; thumb: string | null; edit: { cover: string | null } | null; file: string | null; thumb: string | null; edit: { cover: string | null } | null;
/** Vídeo final (sem as camadas de teste do vídeo de revisão): só ele vai para as redes. doc/clipador/REVISAO.md */
publishFile?: ClipVideo["publishFile"];
final?: (NonNullable<ClipVideo["final"]> & { cover: string | null }) | null;
}; };
/** Arquivo que fica no job: o final, se já existe; senão o de revisão só como referência — `sendDue` troca pelo final. */
const jobFileOf = (clip: ClipView) => clip.publishFile ?? clip.file;
async function fetchClip(clipId: number): Promise<ClipView | null> { async function fetchClip(clipId: number): Promise<ClipView | null> {
const response = await clipperFetch(`/v1/clips/${clipId}`, {}, 15_000); const response = await clipperFetch(`/v1/clips/${clipId}`, {}, 15_000);
if (response.status === 404) return null; if (response.status === 404) return null;
@@ -479,7 +485,7 @@ export async function publishClip(clipId: number, input: { accountId?: unknown;
if (!existing) { if (!existing) {
const info = run(`INSERT INTO publish_jobs (account_id, platform, source_kind, source_id, source_label, file, cover, title, caption, status, origin, created_at, updated_at) const info = run(`INSERT INTO publish_jobs (account_id, platform, source_kind, source_id, source_label, file, cover, title, caption, status, origin, created_at, updated_at)
VALUES (?, ?, 'clip', ?, ?, ?, ?, ?, ?, 'awaiting_approval', 'manual', ?, ?)`, VALUES (?, ?, 'clip', ?, ?, ?, ?, ?, ?, 'awaiting_approval', 'manual', ?, ?)`,
account.id, platform, String(clipId), clip.channelId ?? "", clip.file, cover, title, caption, ts, ts); account.id, platform, String(clipId), clip.channelId ?? "", jobFileOf(clip), cover, title, caption, ts, ts);
toPlace.push(Number(info.lastInsertRowid)); toPlace.push(Number(info.lastInsertRowid));
} else if (existing.status === "published") { } else if (existing.status === "published") {
skipped.push({ platform, reason: "já foi publicado nesta rede" }); skipped.push({ platform, reason: "já foi publicado nesta rede" });
@@ -494,7 +500,7 @@ export async function publishClip(clipId: number, input: { accountId?: unknown;
} else { } else {
// Aguardando aprovação, cancelado, falhou (sem envio no Publicador) ou pediu login: volta com o vídeo atual. // Aguardando aprovação, cancelado, falhou (sem envio no Publicador) ou pediu login: volta com o vídeo atual.
run("UPDATE publish_jobs SET file = ?, cover = ?, title = ?, caption = ?, origin = 'manual', updated_at = ? WHERE id = ?", run("UPDATE publish_jobs SET file = ?, cover = ?, title = ?, caption = ?, origin = 'manual', updated_at = ? WHERE id = ?",
clip.file, cover, title, caption, ts, existing.id); jobFileOf(clip), cover, title, caption, ts, existing.id);
toPlace.push(existing.id); toPlace.push(existing.id);
} }
} }
@@ -712,11 +718,12 @@ async function listClips(query: string): Promise<FullClip[]> {
return ((await response.json()) as { clips: FullClip[] }).clips; return ((await response.json()) as { clips: FullClip[] }).clips;
} }
/** Capa do corte: a do editor; senão `clip-<id>-cover.jpg` ao lado do vídeo; senão a miniatura. */ /** Capa do corte: a do vídeo final; senão a do editor; senão `clip-<id>-cover.jpg` ao lado do vídeo; senão a miniatura. */
function clipCover(clip: FullClip): string | null { function clipCover(clip: FullClip): string | null {
const exists = (rel: string | null | undefined) => !!rel && fs.existsSync(path.resolve(REPO_ROOT, rel)); const exists = (rel: string | null | undefined) => !!rel && fs.existsSync(path.resolve(REPO_ROOT, rel));
let found: string | null = null; let found: string | null = null;
if (exists(clip.edit?.cover)) found = clip.edit!.cover; if (clip.publishFile && exists(clip.final?.cover)) found = clip.final!.cover;
else if (exists(clip.edit?.cover)) found = clip.edit!.cover;
else if (clip.file) { else if (clip.file) {
const cover = path.posix.join(path.posix.dirname(clip.file.replace(/\\/g, "/")), `clip-${clip.id}-cover.jpg`); const cover = path.posix.join(path.posix.dirname(clip.file.replace(/\\/g, "/")), `clip-${clip.id}-cover.jpg`);
if (exists(cover)) found = cover; if (exists(cover)) found = cover;
@@ -840,7 +847,7 @@ async function applyClipActions(actions: ClipAction[], clips: Map<number, FullCl
const info = run(`INSERT INTO publish_jobs (account_id, platform, source_kind, source_id, source_label, file, cover, title, caption, status, created_at, updated_at) const info = run(`INSERT INTO publish_jobs (account_id, platform, source_kind, source_id, source_label, file, cover, title, caption, status, created_at, updated_at)
VALUES (?, ?, 'clip', ?, ?, ?, ?, ?, ?, 'awaiting_approval', ?, ?) VALUES (?, ?, 'clip', ?, ?, ?, ?, ?, ?, 'awaiting_approval', ?, ?)
ON CONFLICT (account_id, platform, source_kind, source_id) DO NOTHING`, ON CONFLICT (account_id, platform, source_kind, source_id) DO NOTHING`,
a.accountId, a.platform, String(clip.id), clip.channelId ?? "", clip.file, clipCover(clip), a.accountId, a.platform, String(clip.id), clip.channelId ?? "", jobFileOf(clip), clipCover(clip),
(clip.title || `Corte ${clip.id}`).slice(0, 100), (clip.caption ?? "").slice(0, 2200), ts, ts); (clip.title || `Corte ${clip.id}`).slice(0, 100), (clip.caption ?? "").slice(0, 2200), ts, ts);
if (approved && info.changes > 0) placeApproved(Number(info.lastInsertRowid), { from: ["awaiting_approval"] }); if (approved && info.changes > 0) placeApproved(Number(info.lastInsertRowid), { from: ["awaiting_approval"] });
break; break;
@@ -860,7 +867,7 @@ async function applyClipActions(actions: ClipAction[], clips: Map<number, FullCl
progress = 0, attempts = attempts + 1, schedule_source = 'auto', step = 'O corte está pronto de novo.', file = ?, cover = ?, progress = 0, attempts = attempts + 1, schedule_source = 'auto', step = 'O corte está pronto de novo.', file = ?, cover = ?,
title = ?, caption = ?, scheduled_at = NULL, updated_at = ? title = ?, caption = ?, scheduled_at = NULL, updated_at = ?
WHERE id = ? AND status = 'canceled' AND cancel_reason IN ('source_changed', 'unlinked')`, WHERE id = ? AND status = 'canceled' AND cancel_reason IN ('source_changed', 'unlinked')`,
clip.file, clipCover(clip), (clip.title || `Corte ${clip.id}`).slice(0, 100), (clip.caption ?? "").slice(0, 2200), ts, a.jobId).changes; jobFileOf(clip), clipCover(clip), (clip.title || `Corte ${clip.id}`).slice(0, 100), (clip.caption ?? "").slice(0, 2200), ts, a.jobId).changes;
if (revived && a.approved && !failedApprovals.has(clip.id)) placeApproved(a.jobId, { from: ["awaiting_approval"] }); if (revived && a.approved && !failedApprovals.has(clip.id)) placeApproved(a.jobId, { from: ["awaiting_approval"] });
break; break;
} }
@@ -1023,6 +1030,20 @@ function episodeUsesPersonaVoice(episodeId: number): boolean {
} }
} }
/** Vídeo final de um job de corte, lido no Clipador agora; ou o motivo de esperar (Clipador fora, final não pronto). */
async function clipFinalForJob(job: JobRow): Promise<{ file: string; cover: string | null } | { wait: string }> {
let clip: ClipView | null;
try {
clip = await fetchClip(Number(job.source_id));
} catch (error) {
return { wait: `Esperando o Clipador para conferir o vídeo final (${errorText(error)}).` };
}
if (!clip) return { wait: "Esperando: o corte não existe mais no Clipador." };
const target = clipPublishFile(clip);
if ("wait" in target) return target;
return { file: target.file, cover: clip.publishFile ? clipCover(clip) : null };
}
/** /**
* Envia ao Publicador os jobs vencidos cujo perfil está pronto (um envio por perfil por vez). Seguro contra: * Envia ao Publicador os jobs vencidos cujo perfil está pronto (um envio por perfil por vez). Seguro contra:
* - cancelamento no meio do ciclo: relê a linha antes de enviar e grava com UPDATE condicional; se o job mudou * - cancelamento no meio do ciclo: relê a linha antes de enviar e grava com UPDATE condicional; se o job mudou
@@ -1055,6 +1076,18 @@ async function sendDue(): Promise<void> {
} }
const key = `${job.account_id}|${job.platform}`; const key = `${job.account_id}|${job.platform}`;
if (busy.has(key) || sent >= MAX_SENDS_PER_TICK) { setStep("Esperando o envio anterior terminar."); continue; } if (busy.has(key) || sent >= MAX_SENDS_PER_TICK) { setStep("Esperando o envio anterior terminar."); continue; }
if (job.source_kind === "clip") {
// Corte: só o vídeo FINAL vai para as redes (doc/clipador/REVISAO.md). Relê no Clipador na hora de enviar e,
// sem final pronto, espera — nunca manda o vídeo de revisão (com as camadas de teste).
const target = await clipFinalForJob(job);
if ("wait" in target) { setStep(target.wait); continue; }
if (target.file !== job.file || (target.cover && target.cover !== job.cover)) {
run("UPDATE publish_jobs SET file = ?, cover = COALESCE(?, cover), updated_at = ? WHERE id = ? AND status = 'queued'",
target.file, target.cover, now(), job.id);
job.file = target.file;
if (target.cover) job.cover = target.cover;
}
}
// O Publicador só aceita arquivos dentro de output/, stories/ ou assets/ (as mesmas pastas que o painel serve). // O Publicador só aceita arquivos dentro de output/, stories/ ou assets/ (as mesmas pastas que o painel serve).
const file = resolveInside(job.file, SERVABLE_ROOTS); const file = resolveInside(job.file, SERVABLE_ROOTS);
if (!file || !fs.existsSync(file)) { if (!file || !fs.existsSync(file)) {
+171 -214
View File
@@ -3,7 +3,7 @@
"width": 1080, "width": 1080,
"height": 1920, "height": 1920,
"fps": 30, "fps": 30,
"durationS": 7.478, "durationS": 5.847,
"seed": 1, "seed": 1,
"scene": { "scene": {
"kind": "place", "kind": "place",
@@ -15,9 +15,9 @@
"elements": [ "elements": [
{ {
"kind": "ark", "kind": "ark",
"x": 0.6, "x": 0.5,
"z": 0.55, "z": 0.35,
"scale": 1.2 "scale": 1.35
}, },
{ {
"kind": "palm", "kind": "palm",
@@ -54,8 +54,9 @@
"actors": [ "actors": [
{ {
"kind": "person", "kind": "person",
"x": 0.34, "x": 0.15,
"y": 0.78, "y": 0.8,
"scale": 0.72,
"enterS": 0.15, "enterS": 0.15,
"character": { "character": {
"name": "Noé", "name": "Noé",
@@ -128,8 +129,8 @@
"lines": [ "lines": [
"Construtor da arca" "Construtor da arca"
], ],
"x": 0.64, "x": 0.45,
"y": 0.51, "y": 0.606,
"atS": 0.5 "atS": 0.5
} }
], ],
@@ -137,215 +138,202 @@
{ {
"text": "Um", "text": "Um",
"startS": 0, "startS": 0,
"endS": 0.3 "endS": 0.18
}, },
{ {
"text": "barco", "text": "barco",
"startS": 0.3, "startS": 0.18,
"endS": 0.72 "endS": 0.56
}, },
{ {
"text": "da", "text": "da",
"startS": 0.72, "startS": 0.56,
"endS": 0.84 "endS": 0.66
}, },
{ {
"text": "altura", "text": "altura",
"startS": 0.84, "startS": 0.66,
"endS": 1.18, "endS": 0.98,
"tone": "key" "tone": "key"
}, },
{ {
"text": "de", "text": "de",
"startS": 1.18, "startS": 0.98,
"endS": 1.34 "endS": 1.12
}, },
{ {
"text": "um", "text": "um",
"startS": 1.34, "startS": 1.12,
"endS": 1.44 "endS": 1.2
}, },
{ {
"text": "prédio", "text": "prédio",
"startS": 1.44, "startS": 1.2,
"endS": 1.78 "endS": 1.52
}, },
{ {
"text": "de", "text": "de",
"startS": 1.78, "startS": 1.52,
"endS": 1.92 "endS": 1.64
}, },
{ {
"text": "quatro", "text": "quatro",
"startS": 1.92, "startS": 1.64,
"endS": 2.26 "endS": 1.94
}, },
{ {
"text": "andares,", "text": "andares,",
"startS": 2.26, "startS": 1.94,
"endS": 2.78 "endS": 2.42
}, },
{ {
"text": "feito", "text": "feito",
"startS": 3.02, "startS": 2.62,
"endS": 3.36 "endS": 2.96
}, },
{ {
"text": "à", "text": "à",
"startS": 3.36, "startS": 2.96,
"endS": 3.48 "endS": 3.06
}, },
{ {
"text": "mão,", "text": "mão,",
"startS": 3.48, "startS": 3.06,
"endS": 3.68 "endS": 3.24
}, },
{ {
"text": "a", "text": "a",
"startS": 3.92, "startS": 3.46,
"endS": 4.14 "endS": 3.66
}, },
{ {
"text": "Arca", "text": "Arca",
"startS": 4.14, "startS": 3.66,
"endS": 4.48 "endS": 3.98
}, },
{ {
"text": "de", "text": "de",
"startS": 4.48, "startS": 3.98,
"endS": 4.6 "endS": 4.08
}, },
{ {
"text": "Noé,", "text": "Noé,",
"startS": 4.6, "startS": 4.08,
"endS": 4.9 "endS": 4.34
}, },
{ {
"text": "segundo", "text": "segundo",
"startS": 5.24, "startS": 4.62,
"endS": 5.58 "endS": 5
}, },
{ {
"text": "Gênesis.", "text": "Gênesis.",
"startS": 5.58, "startS": 5,
"endS": 6.24 "endS": 5.54
} }
], ],
"audioEnv": { "audioEnv": {
"fps": 30, "fps": 30,
"values": [ "values": [
0, 0,
0, 0.52,
0, 0.68,
0,
0.16,
0.62,
0.67,
0.62, 0.62,
0.62, 0.62,
0.59, 0.56,
0.46, 0.44,
0.17, 0.14,
0.83,
1, 1,
1, 1,
1, 1,
0.71, 0.86,
0.26, 0.36,
0.12, 0.11,
0.02, 0.02,
0.06, 0.06,
0.76, 0.73,
0.34, 0.2,
0.45, 0.65,
1, 1,
0.96,
1, 1,
0.65,
0.28,
0.03,
0,
0.12,
0.56,
0.75,
0.71,
1,
1,
0.26,
0.14,
0.47,
0.6,
0.41,
0.04,
0.2,
0.67,
0.88,
1,
0.88,
0.75,
0.17,
0.3,
0.39,
0.08,
0.24,
0.42,
0.02,
0,
0.1,
0.74,
1,
1,
0.79,
0.07,
0.15,
0.3,
0.57,
0.69,
0.5,
0.44,
0.27,
0.72,
0.71,
0.72,
0.7,
0.48, 0.48,
0.16, 0.16,
0.01, 0.23,
0,
0.13,
0.57,
0.78,
0.79,
0.75,
1,
0.88,
0.14,
0.18,
0.5,
0.63,
0.4,
0.05,
0.06,
0.76,
0.77,
1,
0.91,
0.95,
0.64,
0.16,
0.37,
0.42,
0.08,
0.19,
0.54,
0.15,
0.01,
0.09,
0.21,
1,
1,
1,
0.84,
0.06, 0.06,
0.04, 0.04,
0.33,
0.5,
0.71,
0.65,
0.41,
0.43,
0.25,
0.78,
0.73,
0.73,
0.73,
0.61,
0.18,
0.24,
0.17,
0.04,
0.05,
0.03, 0.03,
0.03, 0.03,
0, 0,
0, 0,
0,
0.01, 0.01,
0.01, 0.01,
0, 0,
0, 0,
0, 0,
0.01, 0,
0.36, 0.05,
1, 0.94,
0.72, 0.68,
0.24, 0.24,
0.01, 0.04,
0.39, 0.59,
0.89, 0.89,
0.86, 0.75,
0.43, 0.37,
0.4, 0.4,
0.44, 0.66,
0.74, 0.68,
0.67, 0.39,
0.42, 0.41,
0.4, 0.15,
0.24, 0.03,
0.06,
0, 0,
0, 0,
0, 0,
@@ -353,98 +341,67 @@
0, 0,
0, 0,
0, 0,
0, 0.01,
0, 0.77,
0.71, 0.84,
0.92, 0.79,
0.71,
0.93,
0.95,
0.87, 0.87,
0.88, 0.88,
0.87,
0.83, 0.83,
0.34, 0.37,
0.19, 0.19,
0.07, 0.07,
0.01,
0.45,
0.8,
0.22,
0.15,
0.5,
0.46,
0.64,
0.78,
0.72,
0.84,
0.71,
0.54,
0.28,
0.07,
0.03,
0,
0,
0,
0,
0,
0,
0,
0.01,
0.01,
0.01,
0.05,
0.66,
0.56,
0.21,
0.14,
0.53,
0.67,
0.52,
0.54,
0.43,
0.49,
0.82,
0.81,
0.32,
0.14,
0.44,
0.83,
0.61,
0.43,
0.28,
0.31,
0.17,
0.02,
0.09, 0.09,
0.16, 0.68,
0.6,
0.12,
0.46,
0.45,
0.57,
0.77,
0.72,
0.81,
0.68,
0.43,
0.18,
0.05,
0.01,
0,
0,
0,
0,
0,
0,
0.01,
0.01,
0.04,
0.54,
0.61,
0.26,
0.14,
0.58,
0.62,
0.52,
0.51,
0.38,
0.6,
0.88,
0.41,
0.17,
0.4,
0.79,
0.6,
0.37,
0.29,
0.24,
0.05,
0.02,
0.15,
0.08, 0.08,
0.03, 0.03,
0.03,
0.02, 0.02,
0.01, 0.02,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0, 0,
0, 0,
0 0
+167 -221
View File
@@ -3,7 +3,7 @@
"width": 1080, "width": 1080,
"height": 1920, "height": 1920,
"fps": 30, "fps": 30,
"durationS": 6.974, "durationS": 5.033,
"seed": 8, "seed": 8,
"scene": { "scene": {
"kind": "place", "kind": "place",
@@ -152,296 +152,242 @@
{ {
"text": "Quem", "text": "Quem",
"startS": 0, "startS": 0,
"endS": 0.36 "endS": 0.18
}, },
{ {
"text": "era", "text": "era",
"startS": 0.36, "startS": 0.18,
"endS": 0.64 "endS": 0.44
}, },
{ {
"text": "Noé?", "text": "Noé?",
"startS": 0.64, "startS": 0.44,
"endS": 0.94 "endS": 0.72
}, },
{ {
"text": "A", "text": "A",
"startS": 1.44, "startS": 0.96,
"endS": 1.96 "endS": 1.34
}, },
{ {
"text": "Bíblia", "text": "Bíblia",
"startS": 1.96, "startS": 1.34,
"endS": 2.32 "endS": 1.64
}, },
{ {
"text": "conta", "text": "conta",
"startS": 2.32, "startS": 1.64,
"endS": 2.66 "endS": 1.94
}, },
{ {
"text": "que", "text": "que",
"startS": 2.66, "startS": 1.94,
"endS": 2.84 "endS": 2.1
}, },
{ {
"text": "ele", "text": "ele",
"startS": 2.84, "startS": 2.1,
"endS": 2.96 "endS": 2.22
}, },
{ {
"text": "era", "text": "era",
"startS": 2.96, "startS": 2.22,
"endS": 3.08 "endS": 2.32
}, },
{ {
"text": "um", "text": "um",
"startS": 3.08, "startS": 2.32,
"endS": 3.18 "endS": 2.42
}, },
{ {
"text": "homem", "text": "homem",
"startS": 3.18, "startS": 2.42,
"endS": 3.42, "endS": 2.62,
"tone": "key" "tone": "key"
}, },
{ {
"text": "justo", "text": "justo",
"startS": 3.42, "startS": 2.62,
"endS": 3.82, "endS": 2.98,
"tone": "key" "tone": "key"
}, },
{ {
"text": "e", "text": "e",
"startS": 3.82, "startS": 2.98,
"endS": 3.98 "endS": 3.12
}, },
{ {
"text": "íntegro", "text": "íntegro",
"startS": 3.98, "startS": 3.12,
"endS": 4.32 "endS": 3.46
}, },
{ {
"text": "entre", "text": "entre",
"startS": 4.32, "startS": 3.46,
"endS": 4.52 "endS": 3.64
}, },
{ {
"text": "os", "text": "os",
"startS": 4.52, "startS": 3.64,
"endS": 4.7 "endS": 3.8
}, },
{ {
"text": "seus", "text": "seus",
"startS": 4.7, "startS": 3.8,
"endS": 4.84 "endS": 3.92
}, },
{ {
"text": "contemporâneos.", "text": "contemporâneos.",
"startS": 4.84, "startS": 3.92,
"endS": 5.72 "endS": 4.72
} }
], ],
"audioEnv": { "audioEnv": {
"fps": 30, "fps": 30,
"values": [ "values": [
0, 0.01,
0, 0.06,
0, 0.59,
0,
0,
0.04,
0.05,
0.66,
0.67, 0.67,
0.64, 0.63,
0.6,
0.64,
0.7,
0.87,
0.74,
0.9,
1,
1,
1,
0.87,
0.51,
0.64,
0.84,
0.86,
0.89,
0.66,
0.49,
0.16,
0.04,
0.01,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0.84,
1,
0.7,
0.21,
0.14,
0.23,
0.45,
0.53,
0.53,
0.24,
0.3,
0.89,
1,
0.85,
0.12,
0.01,
0.07,
0.51,
0.81,
0.74,
0.73,
0.37,
0.16,
0.14,
0.49,
0.27,
0.01,
0.02,
0.18,
0.81,
1,
0.57,
1,
0.99,
1,
0.46,
0.62,
0.49,
0.46,
0.58, 0.58,
0.62, 0.62,
0.67, 0.7,
0.9, 0.9,
0.49, 0.77,
0.98,
1,
0.87,
0.98,
0.53,
0.62,
0.86,
0.92,
0.77,
0.62,
0.31,
0.08,
0.01,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0.5,
1,
0.77,
0.26,
0.13,
0.26,
0.47,
0.54,
0.44,
0.17,
0.7,
1,
0.89,
0.1,
0.01,
0.07,
0.55, 0.55,
0.51, 0.83,
0.49, 0.74,
0.55,
0.26,
0.04,
0.44,
0.28,
0.01,
0.02,
0.3,
0.94,
0.73,
0.72,
1,
1,
0.67,
0.66,
0.52,
0.46,
0.62,
0.6,
0.79,
0.79,
0.54,
0.53,
0.47,
0.58, 0.58,
0.3, 0.3,
0.13, 0.13,
0.15,
0.42,
0.89,
1,
0.65,
0.47,
0.12,
0.09,
0.02,
0.12,
0.9,
0.71,
0.47,
0.52,
0.59,
0.64,
0.16,
0.19,
1,
0.7,
0.16,
0.57,
0.57,
0.76,
0.68,
0.48,
0.5,
0.31,
0.05,
0.29,
0.54,
0.65,
0.17, 0.17,
0.04, 0.52,
0.03, 0.99,
0.73, 0.9,
0.88,
0.58, 0.58,
0.1, 0.25,
0.08, 0.12,
0.04, 0.02,
0.05, 0.25,
0.54, 0.94,
0.61, 0.65,
0.42,
0.03,
0.47,
0.48,
0.42,
0.24,
0.03,
0.67,
1,
1,
0.49, 0.49,
0.78, 0.55,
0.69, 0.63,
0.48, 0.43,
0.39, 0.03,
0.27, 1,
0.26, 0.85,
0.23, 0.16,
0.1, 0.68,
0.04, 0.58,
0.06, 0.77,
0.05, 0.54,
0.48,
0.43,
0.06,
0.3,
0.53,
0.67,
0.21,
0.04,
0.17,
0.97,
0.82,
0.29,
0.08,
0.05,
0.05,
0.57,
0.64,
0.39,
0.22,
0.54,
0.45,
0.37,
0.04,
0.42,
1,
1,
0.61,
0.84,
0.62,
0.45,
0.31,
0.28,
0.22,
0.14,
0.06,
0.06,
0.04,
0.03, 0.03,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0, 0,
0 0
] ]
+226 -281
View File
@@ -3,7 +3,7 @@
"width": 1080, "width": 1080,
"height": 1920, "height": 1920,
"fps": 30, "fps": 30,
"durationS": 9.47, "durationS": 7.264,
"seed": 15, "seed": 15,
"scene": { "scene": {
"kind": "place", "kind": "place",
@@ -55,6 +55,12 @@
"x": 0.5, "x": 0.5,
"z": 0.8, "z": 0.8,
"color": "#d8b88a" "color": "#d8b88a"
},
{
"kind": "ark_frame",
"x": 0.5,
"z": 0.35,
"scale": 1.35
} }
] ]
}, },
@@ -70,8 +76,9 @@
"actors": [ "actors": [
{ {
"kind": "person", "kind": "person",
"x": 0.5, "x": 0.15,
"y": 0.78, "y": 0.8,
"scale": 0.72,
"enterS": 0.15, "enterS": 0.15,
"character": { "character": {
"name": "Noé", "name": "Noé",
@@ -136,7 +143,7 @@
"atP": 0.32 "atP": 0.32
} }
], ],
"framing": "medium", "framing": "full",
"flip": false "flip": false
} }
], ],
@@ -155,219 +162,206 @@
{ {
"text": "Segundo", "text": "Segundo",
"startS": 0, "startS": 0,
"endS": 0.62 "endS": 0.42
}, },
{ {
"text": "o", "text": "o",
"startS": 0.62, "startS": 0.42,
"endS": 0.76 "endS": 0.54
}, },
{ {
"text": "relato,", "text": "relato,",
"startS": 0.76, "startS": 0.54,
"endS": 1.12 "endS": 0.86
}, },
{ {
"text": "a", "text": "a",
"startS": 1.4, "startS": 1.14,
"endS": 1.62 "endS": 1.32
}, },
{ {
"text": "terra", "text": "terra",
"startS": 1.62, "startS": 1.32,
"endS": 1.78 "endS": 1.46
}, },
{ {
"text": "estava", "text": "estava",
"startS": 1.78, "startS": 1.46,
"endS": 2.12 "endS": 1.78
}, },
{ {
"text": "cheia", "text": "cheia",
"startS": 2.12, "startS": 1.78,
"endS": 2.46 "endS": 2.1
}, },
{ {
"text": "de", "text": "de",
"startS": 2.46, "startS": 2.1,
"endS": 2.58 "endS": 2.2
}, },
{ {
"text": "maldade.", "text": "maldade.",
"startS": 2.58, "startS": 2.2,
"endS": 3.08 "endS": 2.64
}, },
{ {
"text": "Noé", "text": "Noé",
"startS": 3.76, "startS": 3.16,
"endS": 4.36 "endS": 3.46
}, },
{ {
"text": "recebeu", "text": "recebeu",
"startS": 4.36, "startS": 3.46,
"endS": 4.8 "endS": 3.86
}, },
{ {
"text": "a", "text": "a",
"startS": 4.8, "startS": 3.86,
"endS": 4.88 "endS": 3.94
}, },
{ {
"text": "ordem", "text": "ordem",
"startS": 4.88, "startS": 3.94,
"endS": 5.24 "endS": 4.26
}, },
{ {
"text": "de", "text": "de",
"startS": 5.24, "startS": 4.26,
"endS": 5.36 "endS": 4.36
}, },
{ {
"text": "construir", "text": "construir",
"startS": 5.36, "startS": 4.36,
"endS": 5.76 "endS": 4.74
}, },
{ {
"text": "uma", "text": "uma",
"startS": 5.76, "startS": 4.74,
"endS": 6 "endS": 4.94
}, },
{ {
"text": "arca", "text": "arca",
"startS": 6, "startS": 4.94,
"endS": 6.3 "endS": 5.24
}, },
{ {
"text": "para", "text": "para",
"startS": 6.3, "startS": 5.24,
"endS": 6.48 "endS": 5.4
}, },
{ {
"text": "salvar", "text": "salvar",
"startS": 6.48, "startS": 5.4,
"endS": 6.8 "endS": 5.68
}, },
{ {
"text": "a", "text": "a",
"startS": 6.8, "startS": 5.68,
"endS": 6.96 "endS": 5.82
}, },
{ {
"text": "família", "text": "família",
"startS": 6.96, "startS": 5.82,
"endS": 7.34 "endS": 6.18
}, },
{ {
"text": "e", "text": "e",
"startS": 7.34, "startS": 6.18,
"endS": 7.54 "endS": 6.36
}, },
{ {
"text": "os", "text": "os",
"startS": 7.54, "startS": 6.36,
"endS": 7.72 "endS": 6.52
}, },
{ {
"text": "animais.", "text": "animais.",
"startS": 7.72, "startS": 6.52,
"endS": 8.18 "endS": 6.9
} }
], ],
"audioEnv": { "audioEnv": {
"fps": 30, "fps": 30,
"values": [ "values": [
0,
0,
0,
0,
0,
0, 0,
0.01, 0.01,
0.02, 0.02,
0.03, 0.03,
0.46,
0.69,
0.48,
0.2,
0.29,
0.81,
0.93,
0.86,
0.46,
0.58,
0.98,
0.72,
0.62,
0.82,
0.95,
0.66,
0.65, 0.65,
0.77, 0.58,
0.27,
0.21,
0.61,
0.89,
0.92,
0.42,
0.55,
0.96,
0.64,
0.62,
0.96,
0.76,
0.56,
0.79, 0.79,
0.75, 0.8,
0.59, 0.62,
0.25, 0.55,
0.01,
0.03,
0.15,
0.01,
0.01,
0,
0,
0,
0,
0,
0,
0.23,
1,
0.94,
0.39,
0.02,
0,
0.26,
1,
0.94,
0.9,
0.99,
0.53,
0.51,
0.54,
0.13, 0.13,
0.03, 0.01,
0.03, 0.12,
0.09,
0.01,
0,
0,
0,
0,
0,
0,
0.44,
1,
0.73,
0.08,
0.01,
0.13,
1,
0.93,
0.87,
0.8,
0.47,
0.56,
0.33,
0.05,
0.01,
0.69,
0.97,
0.52,
0.17,
0.7,
0.39,
0.15,
0.17,
0.15,
0.16,
1,
0.77,
0.87, 0.87,
1, 1,
0.59, 0.61,
0.17, 0.09,
0.75, 0.45,
0.52, 0.48,
0.19, 0.67,
0.14, 0.83,
0.17, 0.77,
0.14,
0.46,
1,
0.66,
0.75,
1,
0.91,
0.13,
0.25,
0.64,
0.5,
0.78,
0.89,
0.78,
0.43, 0.43,
0.12, 0.14,
0.76, 0.77,
0.82, 0.82,
0.73, 0.63,
0.62, 0.57,
0.5, 0.4,
0.27, 0.05,
0.03, 0.07,
0.08,
0.08, 0.08,
0.04, 0.04,
0, 0,
@@ -384,170 +378,121 @@
0, 0,
0, 0,
0, 0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0.39, 0.39,
0.59, 0.59,
0.8, 0.88,
0.86,
1,
0.79,
0.7,
0.69,
0.62,
0.61,
0.68,
0.32,
0.02,
0.04,
0.67,
0.33,
0.14,
0.75,
1,
1,
1,
0.96,
0.9, 0.9,
0.76,
0.78,
0.99, 0.99,
0.97, 1,
0.77, 0.53,
0.71, 0.36,
0.21,
0.12,
0.51,
0.39,
0.25,
0.26,
0.43,
0.02,
0.04,
0.53,
0.66,
0.45,
0.1,
0.02,
0.17,
0.4,
0.7,
0.92,
1,
0.53,
0.6,
0.44,
0.67,
0.68, 0.68,
0.64, 0.64,
0.64,
0.7,
0.42,
0.04,
0.03,
0.54,
0.62, 0.62,
0.21,
0.23,
0.87,
1,
1,
1,
1,
1,
0.81,
0.75,
0.94,
1,
0.99,
0.48,
0.4,
0.23,
0.11,
0.53,
0.46,
0.35,
0.11,
0.4,
0.33,
0.01,
0.05,
0.57,
0.7,
0.49,
0.13,
0.05,
0.05,
0.47,
0.51,
0.83,
1,
1,
0.48,
0.63,
0.46,
0.59,
0.81,
0.65, 0.65,
0.63, 0.74,
0.65,
0.69,
0.78,
0.42,
0.21,
0.04,
0.05,
0.48,
0.34,
0.02,
0.33,
0.58,
0.5, 0.5,
0.55, 0.2,
0.13,
0.01,
0.12,
0.86,
0.75,
0.5,
0.15,
0.17,
0.92,
1,
0.62,
0.79,
0.31,
0.02,
0.05,
0.61,
0.55,
0.34,
0.36,
0.43,
0.56,
0.6,
0.78,
0.47,
0.44,
0.92,
0.43,
0.03, 0.03,
0.01, 0.06,
0.28, 0.55,
0.5,
0.79,
0.9,
0.62,
0.19,
0.18, 0.18,
0.94, 0.03,
0.76, 0.51,
0.55, 0.43,
0.63, 0.59,
0.84, 0.16,
0.5, 0.01,
0.48,
0.58,
0.53,
0.41,
0.29,
0.17, 0.17,
0.05, 0.81,
0.71,
0.31,
0.11,
0.64,
1,
0.61,
0.75,
0.36,
0.02,
0.09,
0.57,
0.48,
0.31,
0.39,
0.5,
0.55,
0.74,
0.48,
0.42,
0.8,
0.38,
0.01,
0.18,
0.4,
0.62,
0.91,
0.66,
0.2,
0.19,
0.93,
0.7,
0.46,
0.76,
0.62,
0.44,
0.53,
0.5,
0.45,
0.24,
0.13,
0.03, 0.03,
0.03, 0.03,
0.03, 0.03,
0, 0.02,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0, 0,
0 0
] ]
+195 -238
View File
@@ -3,7 +3,7 @@
"width": 1080, "width": 1080,
"height": 1920, "height": 1920,
"fps": 30, "fps": 30,
"durationS": 7.382, "durationS": 5.761,
"seed": 22, "seed": 22,
"scene": { "scene": {
"kind": "place", "kind": "place",
@@ -15,9 +15,9 @@
"elements": [ "elements": [
{ {
"kind": "ark_frame", "kind": "ark_frame",
"x": 0.55, "x": 0.5,
"z": 0.62, "z": 0.35,
"scale": 1.2 "scale": 1.35
}, },
{ {
"kind": "scaffold", "kind": "scaffold",
@@ -59,8 +59,9 @@
"actors": [ "actors": [
{ {
"kind": "person", "kind": "person",
"x": 0.34, "x": 0.15,
"y": 0.78, "y": 0.8,
"scale": 0.72,
"enterS": 0.15, "enterS": 0.15,
"character": { "character": {
"name": "Noé", "name": "Noé",
@@ -134,315 +135,271 @@
{ {
"text": "Ela", "text": "Ela",
"startS": 0, "startS": 0,
"endS": 0.36 "endS": 0.22
}, },
{ {
"text": "seria", "text": "seria",
"startS": 0.36, "startS": 0.22,
"endS": 0.68 "endS": 0.5
}, },
{ {
"text": "de", "text": "de",
"startS": 0.68, "startS": 0.5,
"endS": 0.84 "endS": 0.66
}, },
{ {
"text": "madeira", "text": "madeira",
"startS": 0.84, "startS": 0.66,
"endS": 1.24 "endS": 1
}, },
{ {
"text": "de", "text": "de",
"startS": 1.24, "startS": 1,
"endS": 1.36 "endS": 1.12
}, },
{ {
"text": "gofer,", "text": "gofer,",
"startS": 1.36, "startS": 1.12,
"endS": 1.72, "endS": 1.44,
"tone": "key" "tone": "key"
}, },
{ {
"text": "cuja", "text": "cuja",
"startS": 2, "startS": 1.72,
"endS": 2.4 "endS": 2.06
}, },
{ {
"text": "espécie", "text": "espécie",
"startS": 2.4, "startS": 2.06,
"endS": 2.82, "endS": 2.44,
"tone": "key" "tone": "key"
}, },
{ {
"text": "é", "text": "é",
"startS": 2.82, "startS": 2.44,
"endS": 2.92 "endS": 2.52
}, },
{ {
"text": "incerta,", "text": "incerta,",
"startS": 2.92, "startS": 2.52,
"endS": 3.44, "endS": 3,
"tone": "key" "tone": "key"
}, },
{ {
"text": "e", "text": "e",
"startS": 3.62, "startS": 3.16,
"endS": 3.88 "endS": 3.4
}, },
{ {
"text": "coberta", "text": "coberta",
"startS": 3.88, "startS": 3.4,
"endS": 4.4 "endS": 3.88
}, },
{ {
"text": "de", "text": "de",
"startS": 4.4, "startS": 3.88,
"endS": 4.5 "endS": 3.98
}, },
{ {
"text": "betume", "text": "betume",
"startS": 4.5, "startS": 3.98,
"endS": 4.9 "endS": 4.34
}, },
{ {
"text": "por", "text": "por",
"startS": 4.9, "startS": 4.34,
"endS": 5.16 "endS": 4.58
}, },
{ {
"text": "dentro", "text": "dentro",
"startS": 5.16, "startS": 4.58,
"endS": 5.48 "endS": 4.86
}, },
{ {
"text": "e", "text": "e",
"startS": 5.48, "startS": 4.86,
"endS": 5.64 "endS": 5.02
}, },
{ {
"text": "por", "text": "por",
"startS": 5.64, "startS": 5.02,
"endS": 5.82 "endS": 5.16
}, },
{ {
"text": "fora.", "text": "fora.",
"startS": 5.82, "startS": 5.16,
"endS": 6.14 "endS": 5.46
} }
], ],
"audioEnv": { "audioEnv": {
"fps": 30, "fps": 30,
"values": [ "values": [
0, 0,
0, 0.5,
0, 0.95,
0, 0.95,
0,
0.42,
0.89,
0.92,
0.7,
0.61,
0.91,
0.62,
0.09,
0.02,
0.04,
0.78,
0.82,
0.36,
0.49,
0.81,
1,
1,
0.35,
0.12,
0.36,
0.45,
0.47,
0.74,
0.82,
0.53,
0.13,
0.1,
0.75,
0.85,
0.85,
0.42,
0.77,
0.66,
0.12,
0.14,
0.62,
0.25,
0.32,
1,
0.78,
0.19,
0.03,
0.01,
0.05,
0.59,
0.83,
0.72,
0.27,
0.08,
0.03,
0.01,
0,
0,
0,
0.01,
0.01,
0.01,
0,
0,
0,
0.04,
0.29,
0.66,
0.7,
0.41,
0.17,
0.49,
0.48,
0.12,
0.09,
0.02,
0.14,
0.9,
0.64,
0.67,
0.38,
0.04,
0.02,
0.09,
0.65,
0.48,
0.4,
0.42,
0.39,
0.17,
0.03,
0.01,
0.02,
0.45,
0.99,
0.97,
1,
0.43,
0.13,
0.06,
0.01,
0.03,
0.15,
0.09,
0.01,
0,
0,
0,
0.01,
0,
0,
0,
0,
0.03,
0.41,
0.42,
0.02,
0.09,
0.67,
1,
0.9,
0.17,
0.24,
1,
0.85,
1,
0.79,
0.27,
0.1,
0.02,
0.05,
0.62,
0.34,
0.09,
0.31,
0.21,
0.15,
0.85,
1,
0.17,
0.02,
0,
0.51,
0.68,
0.59,
0.56,
0.85,
1,
0.27,
0.02,
0.16,
0.88,
0.54, 0.54,
0.33, 0.71,
0.22, 0.91,
0.06, 0.25,
0.19, 0.02,
0.72, 0.03,
0.72, 0.74,
0.61, 0.84,
0.64, 0.27,
0.55, 0.57,
0.38, 1,
0.05, 1,
0.36,
0.29,
0.35,
0.4,
0.32,
0.04,
0.01,
0.46,
0.65, 0.65,
0.11, 0.11,
0.06, 0.27,
0.47,
0.53,
0.8,
0.79,
0.42,
0.09,
0.46,
0.85,
0.85,
0.52,
0.75,
0.61,
0.11,
0.22,
0.56,
0.12,
0.9,
1,
0.35,
0.03,
0.02,
0.05,
0.6,
0.88,
0.54,
0.22,
0.04, 0.04,
0.02, 0.02,
0.26, 0,
0,
0,
0.01,
0.01,
0.01,
0,
0,
0.03,
0.04,
0.58,
0.69,
0.49,
0.17,
0.5,
0.4,
0.14,
0.07,
0.02,
0.85,
0.63,
0.69,
0.44,
0.04,
0.02,
0.18,
0.66,
0.43,
0.4,
0.45,
0.24,
0.03,
0.01,
0.02,
0.53,
1, 1,
1, 1,
0.87, 0.87,
0.59, 0.27,
0.31, 0.07,
0.2,
0.09,
0.02, 0.02,
0,
0.15,
0.1,
0.01,
0,
0,
0.01,
0.01, 0.01,
0, 0,
0, 0,
0, 0,
0, 0,
0, 0.39,
0, 0.27,
0, 0.01,
0, 0.15,
0, 1,
0, 1,
0, 0.3,
0, 0.14,
0, 1,
0, 0.87,
0, 0.99,
0, 0.8,
0, 0.23,
0, 0.09,
0, 0.01,
0, 0.38,
0, 0.52,
0, 0.12,
0, 0.25,
0.25,
0.16,
0.84,
0.95,
0.07,
0.01,
0.3,
0.7,
0.65,
0.55,
0.78,
0.99,
0.28,
0.02,
0.51,
0.8,
0.31,
0.34,
0.07,
0.08,
0.71,
0.67,
0.62,
0.61,
0.53,
0.27,
0.13,
0.3,
0.37,
0.37,
0.37,
0.05,
0.01,
0.51,
0.57,
0.07,
0.05,
0.02,
0.02,
0.91,
1,
0.85,
0.55,
0.31,
0.2,
0.03,
0.01,
0 0
] ]
} }
+187 -232
View File
@@ -3,7 +3,7 @@
"width": 1080, "width": 1080,
"height": 1920, "height": 1920,
"fps": 30, "fps": 30,
"durationS": 7.382, "durationS": 5.727,
"seed": 29, "seed": 29,
"scene": { "scene": {
"kind": "place", "kind": "place",
@@ -15,9 +15,9 @@
"elements": [ "elements": [
{ {
"kind": "ark_frame", "kind": "ark_frame",
"x": 0.55, "x": 0.5,
"z": 0.62, "z": 0.35,
"scale": 1.2 "scale": 1.35
}, },
{ {
"kind": "scaffold", "kind": "scaffold",
@@ -59,9 +59,9 @@
"actors": [ "actors": [
{ {
"kind": "person", "kind": "person",
"x": 0.3, "x": 0.15,
"y": 0.8, "y": 0.8,
"scale": 0.9, "scale": 0.72,
"enterS": 0.15, "enterS": 0.15,
"character": { "character": {
"name": "Noé", "name": "Noé",
@@ -116,9 +116,9 @@
}, },
{ {
"kind": "person", "kind": "person",
"x": 0.7, "x": 0.85,
"y": 0.8, "y": 0.8,
"scale": 0.9, "scale": 0.72,
"enterS": 0.35, "enterS": 0.35,
"character": { "character": {
"name": "Jafé", "name": "Jafé",
@@ -174,306 +174,261 @@
{ {
"text": "A", "text": "A",
"startS": 0, "startS": 0,
"endS": 0.3 "endS": 0.14
}, },
{ {
"text": "arca", "text": "arca",
"startS": 0.3, "startS": 0.14,
"endS": 0.68 "endS": 0.48
}, },
{ {
"text": "tinha", "text": "tinha",
"startS": 0.68, "startS": 0.48,
"endS": 0.9 "endS": 0.66
}, },
{ {
"text": "300", "text": "300",
"startS": 0.9, "startS": 0.66,
"endS": 1.28, "endS": 1.02,
"tone": "key" "tone": "key"
}, },
{ {
"text": "covados", "text": "covados",
"startS": 1.28, "startS": 1.02,
"endS": 1.92, "endS": 1.6,
"tone": "key" "tone": "key"
}, },
{ {
"text": "de", "text": "de",
"startS": 1.92, "startS": 1.6,
"endS": 2.08 "endS": 1.74
}, },
{ {
"text": "comprimento,", "text": "comprimento,",
"startS": 2.08, "startS": 1.74,
"endS": 2.64 "endS": 2.26
}, },
{ {
"text": "50", "text": "50",
"startS": 2.96, "startS": 2.56,
"endS": 3.38, "endS": 2.92,
"tone": "key" "tone": "key"
}, },
{ {
"text": "de", "text": "de",
"startS": 3.38, "startS": 2.92,
"endS": 3.6 "endS": 3.12
}, },
{ {
"text": "largura", "text": "largura",
"startS": 3.6, "startS": 3.12,
"endS": 4.02 "endS": 3.5
}, },
{ {
"text": "e", "text": "e",
"startS": 4.02, "startS": 3.5,
"endS": 4.1 "endS": 3.58
}, },
{ {
"text": "30", "text": "30",
"startS": 4.1, "startS": 3.58,
"endS": 4.34, "endS": 3.8,
"tone": "key" "tone": "key"
}, },
{ {
"text": "de", "text": "de",
"startS": 4.34, "startS": 3.8,
"endS": 4.5 "endS": 3.96
}, },
{ {
"text": "altura,", "text": "altura,",
"startS": 4.5, "startS": 3.96,
"endS": 4.88 "endS": 4.3
}, },
{ {
"text": "diz", "text": "diz",
"startS": 5.14, "startS": 4.54,
"endS": 5.46 "endS": 4.82
}, },
{ {
"text": "o", "text": "o",
"startS": 5.46, "startS": 4.82,
"endS": 5.62 "endS": 4.98
}, },
{ {
"text": "Gênesis.", "text": "Gênesis.",
"startS": 5.62, "startS": 4.98,
"endS": 6.12 "endS": 5.4
} }
], ],
"audioEnv": { "audioEnv": {
"fps": 30, "fps": 30,
"values": [ "values": [
0, 0.01,
0, 0.93,
0,
0,
0,
0.03,
0.99,
1, 1,
1, 1,
0.97, 0.97,
0.94, 0.82,
0.87, 0.95,
0.96,
0.91, 0.91,
0.63, 0.83,
0.29, 0.37,
0.12, 0.13,
0.05, 0.04,
0.09, 0.09,
0.73,
0.77, 0.77,
0.81, 0.12,
0.31, 0.14,
0.07,
0.18, 0.18,
0.49,
0.58,
0.48,
0.05,
0.46,
0.45,
1,
0.79,
0.14,
0.13,
0.68,
0.71,
0.6,
0.08,
0.41,
0.39,
0.07,
0.04,
0.16,
0.93,
1,
0.29,
0.09,
0.66,
1,
1,
0.88,
0.3,
0.17,
0.57,
0.38,
0.13,
0.11,
0.53,
0.24,
0.09,
0.51,
0.48,
0.21,
0.17,
0.59,
0.37,
0.47,
0.6,
0.68,
0.61,
0.42,
0.22,
0.01,
0.08,
0.08,
0.02,
0,
0.01,
0.01,
0.01,
0,
0,
0.01,
0.02,
0.3,
0.64,
0.62,
0.49,
0.06,
0.11,
0.62,
0.8,
0.98,
0.7,
0.37,
0.08,
0.81,
0.37,
0.14,
0.61,
0.46,
0.96,
0.74,
0.41,
0.35,
0.1,
0.23,
0.74,
1,
1,
0.48,
0.9,
0.7,
0.08,
0.17,
0.72,
0.55,
0.62,
0.52,
0.12,
0.67,
0.84,
0.19,
0.19,
1,
0.82,
0.53,
0.16,
0,
0.02,
0.36,
0.78,
0.86,
0.91,
0.38,
0.36,
0.03,
0.01,
0,
0.01,
0,
0,
0.08,
0.14,
0.13,
0.26, 0.26,
0.61, 0.61,
0.57, 0.59,
0.41,
0.04,
0.36,
0.46,
1,
1,
0.34,
0.06,
0.46,
0.78,
0.75,
0.5,
0.06,
0.38,
0.41,
0.08,
0.06,
0.06,
0.54, 0.54,
1,
0.83,
0.15,
0.1,
0.84,
1,
1,
0.92,
0.56,
0.15,
0.44,
0.54,
0.29,
0.09,
0.13,
0.56,
0.22, 0.22,
0.09, 0.17,
0.44,
0.58, 0.58,
0.31,
0.13,
0.33,
0.64,
0.39,
0.49,
0.63,
0.66,
0.59,
0.53,
0.31,
0.08,
0.04,
0.11,
0.03,
0.01,
0,
0.01,
0.01,
0.01,
0,
0,
0.01,
0.01,
0.04,
0.51,
0.62,
0.6,
0.45,
0.04,
0.1,
0.59,
0.74,
0.99,
0.89,
0.54,
0.22,
0.38,
0.81,
0.28,
0.15,
0.6,
0.5,
0.73,
1,
0.32,
0.41,
0.28,
0.08,
0.25,
0.79,
1,
1,
0.59,
0.8,
0.88,
0.35,
0.01,
0.23,
0.72,
0.6,
0.65,
0.53,
0.12,
0.55,
0.85,
0.52,
0.1,
0.68,
1,
0.83,
0.47,
0.11,
0.01,
0,
0.26,
0.71, 0.71,
0.9, 0.34,
0.99,
0.62,
0.44,
0.27,
0.03,
0.01,
0,
0.01,
0,
0,
0,
0.12,
0.11,
0.16,
0.38,
0.63,
0.59,
0.55,
0.24,
0.1,
0.48,
0.74,
0.55,
0.23,
0.16,
0.56,
0.89,
0.7,
0.43,
0.27,
0.32,
0.29,
0.1,
0.02,
0.09,
0.15, 0.15,
0.06, 0.39,
0.88,
0.69,
0.43,
0.25,
0.32,
0.27,
0.05,
0.02,
0.14,
0.11,
0.03, 0.03,
0.02, 0.02,
0.02, 0.02,
0.01, 0.01,
0, 0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0 0
] ]
} }
+245 -295
View File
@@ -3,7 +3,7 @@
"width": 1080, "width": 1080,
"height": 1920, "height": 1920,
"fps": 30, "fps": 30,
"durationS": 9.23, "durationS": 7.426,
"seed": 36, "seed": 36,
"scene": { "scene": {
"kind": "place", "kind": "place",
@@ -15,9 +15,9 @@
"elements": [ "elements": [
{ {
"kind": "ark", "kind": "ark",
"x": 0.6, "x": 0.5,
"z": 0.55, "z": 0.35,
"scale": 1.2 "scale": 1.35
}, },
{ {
"kind": "palm", "kind": "palm",
@@ -54,9 +54,9 @@
"actors": [ "actors": [
{ {
"kind": "person", "kind": "person",
"x": 0.3, "x": 0.15,
"y": 0.8, "y": 0.8,
"scale": 0.9, "scale": 0.72,
"enterS": 0.15, "enterS": 0.15,
"character": { "character": {
"name": "Noé", "name": "Noé",
@@ -117,9 +117,9 @@
}, },
{ {
"kind": "person", "kind": "person",
"x": 0.7, "x": 0.85,
"y": 0.8, "y": 0.8,
"scale": 0.9, "scale": 0.72,
"enterS": 0.35, "enterS": 0.35,
"character": { "character": {
"name": "Sem", "name": "Sem",
@@ -185,382 +185,332 @@
{ {
"text": "Com", "text": "Com",
"startS": 0, "startS": 0,
"endS": 0.3 "endS": 0.14
}, },
{ {
"text": "o", "text": "o",
"startS": 0.3, "startS": 0.14,
"endS": 0.44 "endS": 0.26
}, },
{ {
"text": "côvado", "text": "côvado",
"startS": 0.44, "startS": 0.26,
"endS": 0.72 "endS": 0.52
}, },
{ {
"text": "valendo", "text": "valendo",
"startS": 0.72, "startS": 0.52,
"endS": 1.1 "endS": 0.88
}, },
{ {
"text": "cerca", "text": "cerca",
"startS": 1.1, "startS": 0.88,
"endS": 1.42 "endS": 1.16
}, },
{ {
"text": "de", "text": "de",
"startS": 1.42, "startS": 1.16,
"endS": 1.58 "endS": 1.3
}, },
{ {
"text": "45", "text": "45",
"startS": 1.58, "startS": 1.3,
"endS": 2.12, "endS": 1.78,
"tone": "key" "tone": "key"
}, },
{ {
"text": "cm,", "text": "cm,",
"startS": 2.12, "startS": 1.78,
"endS": 2.68 "endS": 2.3
}, },
{ {
"text": "estima", "text": "estima",
"startS": 3.26, "startS": 2.82,
"endS": 3.5 "endS": 3.04
}, },
{ {
"text": "-se", "text": "-se",
"startS": 3.5, "startS": 3.04,
"endS": 3.68 "endS": 3.2
}, },
{ {
"text": "135", "text": "135",
"startS": 3.68, "startS": 3.2,
"endS": 4.2, "endS": 3.68,
"tone": "key" "tone": "key"
}, },
{ {
"text": "m", "text": "m",
"startS": 4.2, "startS": 3.68,
"endS": 4.82 "endS": 4.24
}, },
{ {
"text": "de", "text": "de",
"startS": 4.82, "startS": 4.24,
"endS": 5.12 "endS": 4.52
}, },
{ {
"text": "comprimento,", "text": "comprimento,",
"startS": 5.12, "startS": 4.52,
"endS": 5.68 "endS": 5.02
}, },
{ {
"text": "22", "text": "22",
"startS": 5.94, "startS": 5.3,
"endS": 6.34, "endS": 5.62,
"tone": "key" "tone": "key"
}, },
{ {
"text": "de", "text": "de",
"startS": 6.34, "startS": 5.62,
"endS": 6.64 "endS": 5.9
}, },
{ {
"text": "largura", "text": "largura",
"startS": 6.64, "startS": 5.9,
"endS": 7.06 "endS": 6.3
}, },
{ {
"text": "e", "text": "e",
"startS": 7.06, "startS": 6.3,
"endS": 7.2 "endS": 6.42
}, },
{ {
"text": "13", "text": "13",
"startS": 7.2, "startS": 6.42,
"endS": 7.48, "endS": 6.66,
"tone": "key" "tone": "key"
}, },
{ {
"text": "de", "text": "de",
"startS": 7.48, "startS": 6.66,
"endS": 7.62 "endS": 6.8
}, },
{ {
"text": "altura.", "text": "altura.",
"startS": 7.62, "startS": 6.8,
"endS": 7.9 "endS": 7.04
} }
], ],
"audioEnv": { "audioEnv": {
"fps": 30, "fps": 30,
"values": [ "values": [
0,
0,
0,
0,
0, 0,
0.06, 0.06,
0.57, 0.85,
0.89,
0.7,
0.63,
0.73,
0.14,
0.01,
0.09,
1,
1,
1,
0.36,
0.27,
0.78,
0.42,
0.26,
0.7,
0.28,
0.14,
0.84,
1,
0.59,
0.48,
0.63, 0.63,
0.57, 0.57,
0.47,
0.41,
0.64,
0.16,
0.04,
0.03,
0.04,
0.69, 0.69,
0.62,
0.29,
0.04,
0.09,
0.65,
0.45,
0.12,
0.36,
0.06,
0.06,
0.72,
0.98,
0.68,
0.53,
0.58,
0.47,
0.2,
0.14,
0.64,
0.33,
0.03,
0.03,
0.36,
0.39,
0.22,
0.13,
0.31,
0.07,
0.02,
0.4,
0.51,
0.42,
0.23,
0.05,
0.15, 0.15,
0.16,
0.32,
0.58,
0.57,
0.53,
0.41,
0.27,
0.02,
0.05,
0.11,
0.05,
0.04,
0.06,
0.04,
0.01,
0,
0.01,
0.01,
0,
0,
0,
0.29,
0.4,
0.07,
0.07,
0.11,
0.16,
0.62,
0.5,
0.43,
0.87,
0.58,
0.12,
0.02,
0.14,
0.6,
0.19,
0.02,
0.02,
0.01,
0.02,
0.37,
0.54,
0.59,
0.55,
0.31,
0.05,
0.46,
0.26,
0.04,
0.56,
0.43,
0.56,
0.26,
0.29,
0.7,
0.37,
0.03,
0.01,
0.26,
0.74,
0.46,
0.09,
0.5,
0.73,
0.45,
0.46,
0.65,
0.67,
0.6,
0.72,
0.4,
0.02,
0.21,
0.29,
0.38,
0.14,
0.13,
0.5,
0.23,
0.04,
0.45,
0.76,
0.41,
0.06,
0.24,
0.71,
0.4,
0.41,
0.54,
0.54,
0.45,
0.39,
0.26,
0.11,
0.01, 0.01,
0.1, 0.1,
0.05,
0.01,
0,
0,
0.01,
0.01,
0,
0,
0,
0.13,
0.09,
0.36,
0.57,
0.63,
0.53,
0.09,
0.14,
0.49,
0.26,
0.21,
0.79,
0.82,
0.9,
1, 1,
0.98, 1,
0.22, 1,
0.14, 0.13,
0.57,
0.59,
0.68, 0.68,
0.8, 0.46,
0.2,
0.58,
0.17,
0.34,
0.95,
0.82,
0.34,
0.52,
0.54,
0.44,
0.37,
0.52,
0.08,
0.03,
0.02,
0.4,
0.63,
0.37,
0.08,
0.1,
0.62,
0.36,
0.11,
0.28,
0.03,
0.26,
0.87,
0.74,
0.4,
0.57,
0.41,
0.18,
0.26,
0.55,
0.22,
0.02,
0.09,
0.39,
0.28,
0.1,
0.28,
0.04,
0.03,
0.41,
0.46,
0.3,
0.12,
0.12,
0.15,
0.27,
0.54,
0.5,
0.43, 0.43,
0.35, 0.35,
0.22, 0.13,
0.08, 0.03,
0.18, 0.1,
0.67, 0.04,
1, 0.03,
1, 0.05,
1, 0.04,
1,
1,
0.69,
0.16,
0.01, 0.01,
0, 0,
0.56, 0,
0.36, 0.01,
1, 0,
1, 0,
1, 0.19,
0.77, 0.4,
0.15, 0.11,
0.15, 0.07,
0.34,
0.12, 0.12,
0.17, 0.18,
1, 0.63,
0.72, 0.4,
0.55,
0.69,
0.27,
0.02,
0.03,
0.54,
0.22,
0.02,
0.01,
0.01,
0.03,
0.51,
0.49,
0.57,
0.32,
0.05,
0.4,
0.19,
0.19,
0.49,
0.53,
0.4,
0.05,
0.59,
0.41,
0.05,
0.01,
0.31,
0.65,
0.28,
0.08,
0.71,
0.39,
0.41,
0.55,
0.61,
0.63,
0.65,
0.27,
0.07,
0.23,
0.36,
0.21,
0.13,
0.46,
0.21,
0.04,
0.5,
0.64,
0.22,
0.2,
0.48,
0.52,
0.35,
0.44,
0.51,
0.42, 0.42,
0.32,
0.24,
0.05,
0.05,
0.08,
0.01,
0,
0,
0.01,
0.01,
0,
0,
0.07,
0.11,
0.2,
0.46,
0.58,
0.51,
0.16,
0.08,
0.48,
0.15,
0.42,
0.69,
0.79,
1,
1,
0.22,
0.15,
0.52,
0.58,
0.66,
0.66,
0.32,
0.29,
0.1,
0.14,
0.53,
1,
1,
0.99,
1,
1,
0.44,
0.04,
0,
0.46,
0.4,
1,
1,
0.93,
0.56,
0.1,
0.23,
0.23,
0.09,
0.88,
0.7,
0.43,
0.08, 0.08,
0, 0,
0.05, 0.12,
0.32, 0.38,
0.49, 0.5,
0.58, 0.41,
0.32, 0.26,
0.32, 0.19,
0.1,
0.02, 0.02,
0, 0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0 0
] ]
} }
+239 -300
View File
@@ -3,7 +3,7 @@
"width": 1080, "width": 1080,
"height": 1920, "height": 1920,
"fps": 30, "fps": 30,
"durationS": 9.614, "durationS": 7.423,
"seed": 43, "seed": 43,
"scene": { "scene": {
"kind": "place", "kind": "place",
@@ -148,153 +148,276 @@
{ {
"text": "Eram", "text": "Eram",
"startS": 0, "startS": 0,
"endS": 0.42 "endS": 0.24
}, },
{ {
"text": "três", "text": "três",
"startS": 0.42, "startS": 0.24,
"endS": 0.72 "endS": 0.52
}, },
{ {
"text": "andares,", "text": "andares,",
"startS": 0.72, "startS": 0.52,
"endS": 1.26, "endS": 1.02,
"tone": "key" "tone": "key"
}, },
{ {
"text": "uma", "text": "uma",
"startS": 1.52, "startS": 1.28,
"endS": 1.82 "endS": 1.52
}, },
{ {
"text": "porta", "text": "porta",
"startS": 1.82, "startS": 1.52,
"endS": 2.2, "endS": 1.88,
"tone": "key" "tone": "key"
}, },
{ {
"text": "na", "text": "na",
"startS": 2.2, "startS": 1.88,
"endS": 2.32 "endS": 2
}, },
{ {
"text": "lateral", "text": "lateral",
"startS": 2.32, "startS": 2,
"endS": 2.66 "endS": 2.3
}, },
{ {
"text": "e", "text": "e",
"startS": 2.66, "startS": 2.3,
"endS": 2.9 "endS": 2.52
}, },
{ {
"text": "uma", "text": "uma",
"startS": 2.9, "startS": 2.52,
"endS": 3.06 "endS": 2.66
}, },
{ {
"text": "janela.", "text": "janela.",
"startS": 3.06, "startS": 2.66,
"endS": 3.54, "endS": 3.1,
"tone": "key" "tone": "key"
}, },
{ {
"text": "Dá", "text": "Dá",
"startS": 4.04, "startS": 3.6,
"endS": 4.62 "endS": 3.74
}, },
{ {
"text": "para", "text": "para",
"startS": 4.62, "startS": 3.74,
"endS": 4.82 "endS": 3.92
}, },
{ {
"text": "imaginar", "text": "imaginar",
"startS": 4.82, "startS": 3.92,
"endS": 5.22 "endS": 4.3
}, },
{ {
"text": "Noé", "text": "Noé",
"startS": 5.22, "startS": 4.3,
"endS": 5.58 "endS": 4.58
}, },
{ {
"text": "dizendo", "text": "dizendo",
"startS": 5.58, "startS": 4.58,
"endS": 5.86 "endS": 4.86
}, },
{ {
"text": "aos", "text": "aos",
"startS": 5.86, "startS": 4.86,
"endS": 6.06 "endS": 5.04
}, },
{ {
"text": "filhos,", "text": "filhos,",
"startS": 6.06, "startS": 5.04,
"endS": 6.48 "endS": 5.4
}, },
{ {
"text": "vamos,", "text": "vamos,",
"startS": 6.62, "startS": 5.58,
"endS": 7.1 "endS": 5.96
}, },
{ {
"text": "tábua", "text": "tábua",
"startS": 7.48, "startS": 6.34,
"endS": 7.78 "endS": 6.6
}, },
{ {
"text": "por", "text": "por",
"startS": 7.78, "startS": 6.6,
"endS": 8.02 "endS": 6.82
}, },
{ {
"text": "tábua.", "text": "tábua.",
"startS": 8.02, "startS": 6.82,
"endS": 8.4 "endS": 7.18
} }
], ],
"audioEnv": { "audioEnv": {
"fps": 30, "fps": 30,
"values": [ "values": [
0, 0,
0, 0.62,
0, 0.95,
0,
0,
0.51,
0.84,
1, 1,
1, 0.82,
0.48, 0.63,
0.7, 0.5,
0.45, 0.35,
0.4, 0.37,
0.36, 0.1,
0.09,
0.01,
0.69,
0.56,
1,
1,
0.56,
0.38,
0.06,
0.69,
0.84,
0.58,
0.49,
0.33,
0.72,
0.81,
0.75,
0.68,
0.7,
0.48,
0.21,
0.24,
0.12,
0.04, 0.04,
0.77,
0.81,
1,
0.54,
0.48,
0.1,
0.54,
0.81,
0.57,
0.47,
0.33,
0.86,
0.77,
0.65,
0.69,
0.57,
0.23,
0.25,
0.1,
0.04,
0.04,
0.03,
0.01,
0,
0,
0,
0,
0,
0,
0,
0.12,
0.39,
0.47,
0.81,
1,
0.48,
0.02,
0,
0.49,
1,
1,
0.61,
0.19,
0.09,
0.05,
0.64,
0.39,
0.61,
0.73,
0.57,
1,
0.51,
0.03,
0.23,
0.8,
1,
0.67,
1,
1,
0.99,
0.86,
0.68,
0.81,
0.64,
0.93,
0.65,
0.39,
0.71,
0.91,
0.7,
0.18,
0.42,
0.85,
0.48,
0.38,
0.53,
0.44,
0.45,
0.41,
0.35,
0.24,
0.1,
0.04,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0.24,
0.16,
0.86,
0.81,
0.7,
0.2,
0.01,
0.66,
0.87,
0.62,
0.6,
0.47,
0.66,
0.7,
0.54,
0.15,
0.4,
0.39,
0.46,
0.64,
0.74,
0.62,
0.39,
0.36,
0.52,
0.64,
0.73,
0.8,
0.85,
0.56,
0.13,
0.27,
0.55,
0.19,
0.09,
0.65,
0.6,
0.48,
0.49,
0.8,
0.74,
0.35,
0.08,
0.08,
0.03,
0.06,
0.7,
0.88,
0.69,
0.2,
0.25,
0.18,
0.07,
0.04, 0.04,
0.04, 0.04,
0.02, 0.02,
@@ -303,237 +426,53 @@
0, 0,
0, 0,
0, 0,
0,
0,
0,
0.03,
0.29,
0.48,
0.63,
1,
0.88,
0.19,
0.01,
0,
0.47,
1,
1,
0.82,
0.26,
0.15,
0.04,
0.29,
0.73,
0.36,
0.68,
0.77,
0.47,
1,
0.81,
0.06,
0.03,
0.58,
0.89,
0.92,
0.82,
1,
1,
1,
0.92,
0.75,
0.78,
0.79,
0.69,
0.94,
0.58,
0.43,
0.7,
0.87,
0.83,
0.23,
0.29,
0.82,
0.75,
0.35,
0.41,
0.55,
0.48,
0.45,
0.41,
0.35,
0.26,
0.15,
0.06,
0.01,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0.21,
0.21,
0.56,
1,
0.79,
0.58,
0.05,
0.07,
0.76,
0.9,
0.56,
0.71,
0.45,
0.56,
0.68,
0.77,
0.4,
0.16,
0.48,
0.4,
0.49,
0.65,
0.75,
0.71,
0.47,
0.36,
0.42,
0.55,
0.67,
0.75,
0.86,
0.88,
0.71,
0.15,
0.16,
0.51,
0.42,
0.08,
0.29,
0.72,
0.64,
0.46,
0.45,
0.82,
0.81,
0.55,
0.09,
0.1, 0.1,
0.08, 0.16,
0.03,
0.08,
0.75,
0.91,
0.75,
0.35,
0.21,
0.28,
0.11,
0.05,
0.05,
0.04,
0.01,
0,
0,
0,
0,
0,
0,
0.17,
0.13,
0.54,
1,
0.83,
0.92,
0.53,
0.37,
0.35,
0.34,
0.11,
0.09,
0.08,
0.05,
0.01,
0,
0,
0,
0,
0,
0,
0,
0.88,
0.85,
0.77,
0.8,
0.94,
0.24, 0.24,
1,
0.87,
0.87,
0.53,
0.36,
0.33,
0.28,
0.08,
0.08,
0.05,
0.02,
0,
0,
0,
0,
0,
0,
0.25,
0.97,
0.79,
0.77,
0.87,
0.4,
0.15, 0.15,
1, 1,
0.88, 0.82,
0.51, 0.39,
0.05,
0,
0.45,
0.86,
0.11,
0.09,
0.03,
0.01, 0.01,
0.85,
1,
0.81,
0.78,
0.31,
0.06, 0.06,
0.14, 0.89,
0.38, 0.27,
0.16, 0.08,
0.03,
0.01,
0.83,
0.97,
0.83,
0.62,
0.08,
0.06,
0.31,
0.17,
0.03, 0.03,
0.01, 0.01,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0 0
] ]
} }
+176 -227
View File
@@ -3,7 +3,7 @@
"width": 1080, "width": 1080,
"height": 1920, "height": 1920,
"fps": 30, "fps": 30,
"durationS": 7.166, "durationS": 5.192,
"seed": 50, "seed": 50,
"scene": { "scene": {
"kind": "place", "kind": "place",
@@ -55,18 +55,20 @@
{ {
"kind": "animal", "kind": "animal",
"species": "elephant", "species": "elephant",
"x": 0.12000000000000005, "x": 0.13800000000000004,
"y": 0.76, "y": 0.76,
"pair": true, "pair": true,
"walk": { "walk": {
"to": 0.54, "to": 0.54,
"startS": 0 "startS": 0
} },
"scale": 1.35
}, },
{ {
"kind": "person", "kind": "person",
"x": 0.8, "x": 0.15,
"y": 0.78, "y": 0.8,
"scale": 0.72,
"enterS": 0.15, "enterS": 0.15,
"character": { "character": {
"name": "Noé", "name": "Noé",
@@ -120,24 +122,26 @@
{ {
"kind": "animal", "kind": "animal",
"species": "giraffe", "species": "giraffe",
"x": 0.020000000000000073, "x": 0.06800000000000006,
"y": 0.8200000000000001, "y": 0.8200000000000001,
"pair": true, "pair": true,
"walk": { "walk": {
"to": 0.44000000000000006, "to": 0.44000000000000006,
"startS": 0.25 "startS": 0.25
} },
"scale": 1.35
}, },
{ {
"kind": "animal", "kind": "animal",
"species": "lion", "species": "lion",
"x": -0.07999999999999996, "x": -0.001999999999999974,
"y": 0.88, "y": 0.88,
"pair": true, "pair": true,
"walk": { "walk": {
"to": 0.34, "to": 0.34,
"startS": 0.5 "startS": 0.5
} },
"scale": 1.35
} }
], ],
"props": [], "props": [],
@@ -155,294 +159,239 @@
{ {
"text": "Depois", "text": "Depois",
"startS": 0, "startS": 0,
"endS": 0.58 "endS": 0.42
}, },
{ {
"text": "vieram", "text": "vieram",
"startS": 0.58, "startS": 0.42,
"endS": 1.08 "endS": 0.88
}, },
{ {
"text": "os", "text": "os",
"startS": 1.08, "startS": 0.88,
"endS": 1.24 "endS": 1
}, },
{ {
"text": "animais.", "text": "animais.",
"startS": 1.24, "startS": 1,
"endS": 1.74 "endS": 1.44
}, },
{ {
"text": "O", "text": "O",
"startS": 2.22, "startS": 1.78,
"endS": 2.82 "endS": 2.1
}, },
{ {
"text": "Gênesis", "text": "Gênesis",
"startS": 2.82, "startS": 2.1,
"endS": 3.22 "endS": 2.46
}, },
{ {
"text": "fala", "text": "fala",
"startS": 3.22, "startS": 2.46,
"endS": 3.46 "endS": 2.66
}, },
{ {
"text": "em", "text": "em",
"startS": 3.46, "startS": 2.66,
"endS": 3.56 "endS": 2.76
}, },
{ {
"text": "um", "text": "um",
"startS": 3.56, "startS": 2.76,
"endS": 3.66 "endS": 2.84
}, },
{ {
"text": "casal", "text": "casal",
"startS": 3.66, "startS": 2.84,
"endS": 3.98, "endS": 3.14,
"tone": "key" "tone": "key"
}, },
{ {
"text": "de", "text": "de",
"startS": 3.98, "startS": 3.14,
"endS": 4.1 "endS": 3.26
}, },
{ {
"text": "cada", "text": "cada",
"startS": 4.1, "startS": 3.26,
"endS": 4.32, "endS": 3.46,
"tone": "key" "tone": "key"
}, },
{ {
"text": "espécie,", "text": "espécie,",
"startS": 4.32, "startS": 3.46,
"endS": 4.86, "endS": 3.94,
"tone": "key" "tone": "key"
}, },
{ {
"text": "macho", "text": "macho",
"startS": 5.1, "startS": 4.16,
"endS": 5.48 "endS": 4.5
}, },
{ {
"text": "e", "text": "e",
"startS": 5.48, "startS": 4.5,
"endS": 5.56 "endS": 4.6
}, },
{ {
"text": "fêmea.", "text": "fêmea.",
"startS": 5.56, "startS": 4.6,
"endS": 5.98 "endS": 4.96
} }
], ],
"audioEnv": { "audioEnv": {
"fps": 30, "fps": 30,
"values": [ "values": [
0, 0,
0, 0.17,
0, 0.12,
0, 1,
0, 0.83,
0.12,
0.01,
0.02,
0.57,
1,
0.94,
1,
1,
0.19, 0.19,
0.16, 0.11,
0.07,
0.36,
0.73,
0.79,
0.97, 0.97,
1, 1,
0.56, 0.7,
0.04,
0,
0.03,
0.74,
1,
1,
1,
1,
0.36,
0.13,
0.09,
0.09,
0.46,
0.8, 0.8,
0.84,
1,
1,
0.87,
0.82,
0.54,
0.74,
0.45,
0.33,
0.5,
0.53,
0.24,
0.07,
0.79,
0.75,
0.46,
0.79,
0.57,
0.47,
0.55,
0.74,
0.58,
0.46,
0.36,
0.27,
0.08,
0.04,
0.03,
0.02,
0.01,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0.77,
1,
0.56,
0.22,
0.19,
0.43,
1,
0.69,
0.48,
0.54,
0.4, 0.4,
0.12,
0.18,
0.51,
0.19,
0.12,
0.06,
0.02,
0.74,
1,
1,
0.81,
0.6, 0.6,
0.48, 0.29,
0.46,
0.4,
0.4,
0.34,
0.07,
0.39,
0.88,
0.71,
0.25,
0.05,
0.39,
0.94,
0.94,
0.74,
0.4,
0.09,
0.18,
0.42, 0.42,
0.06,
0.08,
0.48,
0.84,
0.76,
0.21,
0.44,
0.43,
0.08,
0.04,
0.07,
0.01,
0.32,
0.91,
0.94,
0.68,
0.51, 0.51,
0.18, 0.28,
0.02,
0.01,
0.02,
0.15,
0.08, 0.08,
0.74,
0.61,
0.47,
0.75,
0.47,
0.43,
0.68,
0.58,
0.42,
0.36,
0.21,
0.05,
0.05,
0.04,
0.02,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0.54,
0.94,
0.62,
0.23,
0.18,
0.56,
1,
0.51,
0.5,
0.47,
0.19,
0.1,
0.42,
0.18,
0.1,
0.03,
0.16,
1,
1,
0.94,
0.51,
0.49,
0.41,
0.38,
0.37,
0.26,
0.08,
0.53,
0.8,
0.42,
0.08,
0.23,
0.8,
0.87,
0.7,
0.3,
0.08,
0.27,
0.32,
0.01, 0.01,
0, 0.2,
0, 0.76,
0, 0.68,
0, 0.28,
0, 0.45,
0.34,
0.04,
0.04,
0.06, 0.06,
0.19, 0.19,
0.32, 0.75,
0.8, 0.91,
0.78, 0.68,
0.66,
0.55,
0.29,
0.13,
0.11,
0.06,
0.44,
0.47, 0.47,
0.3, 0.17,
0.02,
0.02,
0.05,
0.14,
0.04, 0.04,
0.02, 0,
0.02, 0,
0.44, 0,
0.61, 0,
0.54, 0,
0.42, 0.1,
0.26, 0.23,
0.24, 0.49,
0.18, 0.75,
0.64,
0.51,
0.32,
0.12, 0.12,
0.07, 0.11,
0.05,
0.42,
0.43,
0.18,
0.03,
0.02, 0.02,
0, 0.28,
0, 0.62,
0, 0.54,
0, 0.35,
0, 0.26,
0, 0.21,
0, 0.14,
0, 0.1,
0, 0.02,
0, 0.01,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0 0
] ]
} }
+199 -240
View File
@@ -3,7 +3,7 @@
"width": 1080, "width": 1080,
"height": 1920, "height": 1920,
"fps": 30, "fps": 30,
"durationS": 7.286, "durationS": 5.679,
"seed": 57, "seed": 57,
"scene": { "scene": {
"kind": "place", "kind": "place",
@@ -63,9 +63,9 @@
"actors": [ "actors": [
{ {
"kind": "person", "kind": "person",
"x": 0.3, "x": 0.15,
"y": 0.8, "y": 0.8,
"scale": 0.9, "scale": 0.72,
"enterS": 0.15, "enterS": 0.15,
"character": { "character": {
"name": "Noé", "name": "Noé",
@@ -130,9 +130,9 @@
}, },
{ {
"kind": "person", "kind": "person",
"x": 0.7, "x": 0.85,
"y": 0.8, "y": 0.8,
"scale": 0.9, "scale": 0.72,
"enterS": 0.35, "enterS": 0.35,
"character": { "character": {
"name": "Cam", "name": "Cam",
@@ -176,26 +176,29 @@
{ {
"kind": "animal", "kind": "animal",
"species": "camel", "species": "camel",
"x": 0.26, "x": 0.236,
"y": 0.82, "y": 0.82,
"pair": true, "pair": true,
"flip": false "flip": false,
"scale": 1.35
}, },
{ {
"kind": "animal", "kind": "animal",
"species": "horse", "species": "horse",
"x": 0.74, "x": 0.5720000000000001,
"y": 0.86, "y": 0.86,
"pair": true, "pair": true,
"flip": true "flip": true,
"scale": 1.35
}, },
{ {
"kind": "animal", "kind": "animal",
"species": "sheep", "species": "sheep",
"x": 0.5, "x": 0.40399999999999997,
"y": 0.95, "y": 0.95,
"pair": true, "pair": true,
"flip": false "flip": false,
"scale": 1.35
}, },
{ {
"kind": "animal", "kind": "animal",
@@ -225,316 +228,272 @@
{ {
"text": "Mas", "text": "Mas",
"startS": 0, "startS": 0,
"endS": 0.38 "endS": 0.22
}, },
{ {
"text": "há", "text": "há",
"startS": 0.38, "startS": 0.22,
"endS": 0.52 "endS": 0.36
}, },
{ {
"text": "um", "text": "um",
"startS": 0.52, "startS": 0.36,
"endS": 0.62 "endS": 0.44
}, },
{ {
"text": "detalhe,", "text": "detalhe,",
"startS": 0.62, "startS": 0.44,
"endS": 1.12 "endS": 0.9
}, },
{ {
"text": "dos", "text": "dos",
"startS": 1.28, "startS": 1.06,
"endS": 1.54 "endS": 1.32
}, },
{ {
"text": "animais", "text": "animais",
"startS": 1.54, "startS": 1.32,
"endS": 2 "endS": 1.7
}, },
{ {
"text": "puros", "text": "puros",
"startS": 2, "startS": 1.7,
"endS": 2.36, "endS": 2.02,
"tone": "key" "tone": "key"
}, },
{ {
"text": "e", "text": "e",
"startS": 2.36, "startS": 2.02,
"endS": 2.44 "endS": 2.1
}, },
{ {
"text": "das", "text": "das",
"startS": 2.44, "startS": 2.1,
"endS": 2.6 "endS": 2.24
}, },
{ {
"text": "aves,", "text": "aves,",
"startS": 2.6, "startS": 2.24,
"endS": 2.96, "endS": 2.56,
"tone": "key" "tone": "key"
}, },
{ {
"text": "o", "text": "o",
"startS": 3.14, "startS": 2.72,
"endS": 3.4 "endS": 2.96
}, },
{ {
"text": "texto", "text": "texto",
"startS": 3.4, "startS": 2.96,
"endS": 3.76 "endS": 3.3
}, },
{ {
"text": "fala", "text": "fala",
"startS": 3.76, "startS": 3.3,
"endS": 4.1 "endS": 3.6
}, },
{ {
"text": "em", "text": "em",
"startS": 4.1, "startS": 3.6,
"endS": 4.3 "endS": 3.78
}, },
{ {
"text": "sete", "text": "sete",
"startS": 4.3, "startS": 3.78,
"endS": 4.66 "endS": 4.12
}, },
{ {
"text": "pares,", "text": "pares,",
"startS": 4.66, "startS": 4.12,
"endS": 4.98 "endS": 4.4
}, },
{ {
"text": "não", "text": "não",
"startS": 5.22, "startS": 4.62,
"endS": 5.48 "endS": 4.86
}, },
{ {
"text": "em", "text": "em",
"startS": 5.48, "startS": 4.86,
"endS": 5.66 "endS": 5.02
}, },
{ {
"text": "um", "text": "um",
"startS": 5.66, "startS": 5.02,
"endS": 5.78 "endS": 5.14
}, },
{ {
"text": "só.", "text": "só.",
"startS": 5.78, "startS": 5.14,
"endS": 6.04 "endS": 5.34
} }
], ],
"audioEnv": { "audioEnv": {
"fps": 30, "fps": 30,
"values": [ "values": [
0, 0,
0, 0.34,
0,
0,
0,
0.35,
0.53,
0.99,
0.83,
0.74, 0.74,
0.55,
0.13,
0.11,
0.76,
0.73,
0.58,
0.6,
0.5,
0.31,
1, 1,
1,
0.4,
0.03,
0.01,
0.53,
1,
0.85,
0.81, 0.81,
0.65, 0.73,
0.37,
0.18,
0.22,
0.07,
0.01,
0,
0,
0,
0,
0,
0.01,
0.17,
0.12,
0.68,
1,
0.6,
0.57,
0.52,
0.15,
0.11,
0.88,
0.65,
0.41,
0.59,
0.42,
0.5,
0.64,
0.74,
0.56,
0.35,
0.1,
0.11,
0.02,
0,
0.1,
0.85,
1,
1,
0.35,
0.69,
0.37,
0.11,
0.47,
0.32, 0.32,
0.66,
0.99,
0.86,
0.36,
0.09,
0.31,
0.83,
0.83,
0.74,
0.67,
0.38,
0.07,
0.16,
0.18,
0.04,
0.04,
0.05,
0.02,
0,
0,
0,
0,
0,
0,
0,
0.04,
0.46,
0.62,
0.26,
0.01,
0,
0.08, 0.08,
0.63,
0.53,
0.6,
0.58,
0.33,
0.09,
0.04,
0.03,
0.59, 0.59,
0.62,
0.08,
0.02,
0.02,
0.78, 0.78,
1,
1,
0.69,
0.39,
0.42,
0.47,
0.38,
0.12,
0.02,
0.01,
0.01,
0.61,
1,
1,
0.66, 0.66,
0.05, 0.62,
0.08, 0.49,
0.13, 0.56,
1,
0.83,
0.11,
0.01,
0.27,
1,
0.95,
0.77,
0.69,
0.27,
0.23,
0.16,
0.04,
0,
0,
0,
0,
0,
0.09,
0.18,
0.27,
1,
0.82,
0.6,
0.59,
0.23,
0.06,
0.84,
0.67,
0.48,
0.55,
0.46,
0.55,
0.78,
0.61,
0.43,
0.12,
0.11,
0.01,
0,
0.4,
1,
1,
0.5,
0.71,
0.4,
0.1,
0.49,
0.25,
0.8,
1,
0.72,
0.2,
0.18,
0.78,
0.86,
0.82,
0.69,
0.27,
0.06,
0.2,
0.14,
0.03,
0.06,
0.03,
0,
0,
0,
0,
0,
0,
0,
0.31,
0.61,
0.35, 0.35,
0.02, 0.02,
0.17,
0.86,
0.84,
0.78,
0.65,
0.18,
0.23,
0.12,
0.03,
0.04,
0.03,
0.02,
0, 0,
0, 0.37,
0, 0.63,
0, 0.58,
0,
0,
0,
0.33,
0.62,
0.64, 0.64,
0.67, 0.55,
0.71, 0.2,
0.72, 0.07,
0.47, 0.03,
0.64,
0.65,
0.09,
0.02,
0.04,
1,
1,
0.91,
0.39,
0.44,
0.48,
0.42,
0.11,
0.02,
0.01,
0.03,
0.99,
0.98,
0.94,
0.25,
0.07,
0.28,
0.28,
0.01,
0.38,
0.89,
0.85,
0.75,
0.36,
0.22,
0.13,
0.03,
0.03,
0.03,
0.01,
0,
0,
0,
0,
0,
0,
0.38,
0.68,
0.64,
0.74,
0.74,
0.65,
0.48,
0.48,
0.44,
0.45, 0.45,
0.43, 0.43,
0.42,
0.4, 0.4,
0.41, 0.44,
0.4, 0.5,
0.41, 0.24,
0.47, 0.07,
0.35, 0.09,
0.27,
0.98,
0.97,
0.48,
0.06, 0.06,
0.06, 0.01,
0.08,
0.34,
1,
0.83,
0.43,
0.08,
0.02,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0 0
] ]
} }
+327 -372
View File
@@ -3,7 +3,7 @@
"width": 1080, "width": 1080,
"height": 1920, "height": 1920,
"fps": 30, "fps": 30,
"durationS": 7.982, "durationS": 6.301,
"seed": 64, "seed": 64,
"scene": { "scene": {
"kind": "place", "kind": "place",
@@ -15,9 +15,10 @@
"elements": [ "elements": [
{ {
"kind": "ark", "kind": "ark",
"x": 0.6, "x": 0.5,
"z": 0.55, "z": 0.12,
"scale": 1.2 "scale": 1.05,
"occupied": true
}, },
{ {
"kind": "palm", "kind": "palm",
@@ -54,9 +55,9 @@
"actors": [ "actors": [
{ {
"kind": "person", "kind": "person",
"x": 0.14, "x": 0.26094451666666674,
"y": 0.8, "y": 0.6914826562499999,
"scale": 0.6, "scale": 0.5,
"enterS": 0.15, "enterS": 0.15,
"character": { "character": {
"name": "Noé", "name": "Noé",
@@ -101,7 +102,64 @@
}, },
{ {
"do": "walk", "do": "walk",
"to": 0.28, "to": 0.40094451666666675,
"dur": 2.4,
"atP": 0.6
}
],
"framing": "full",
"flip": false
},
{
"kind": "person",
"x": 0.38047225833333337,
"y": 0.6914826562499999,
"scale": 0.5,
"enterS": 0.35,
"character": {
"name": "Esposa de Noé",
"look": {
"build": "average",
"height": 0.92,
"skin": "#d09a70",
"hair": {
"style": "long",
"color": "#c9c9cf"
},
"beard": {
"style": "none",
"color": "#a9a9b0"
},
"glasses": "none",
"brows": "thick",
"top": {
"style": "robe",
"color": "#8a6f9e",
"accent": "#6b4a2a"
},
"bottom": {
"style": "pants",
"color": "#2c3346"
},
"shoes": "#6b4a2a",
"footwear": "sandals",
"nose": "button",
"lids": 0.3,
"wrinkles": 0.7,
"head": "round"
}
},
"expression": "neutral",
"pose": "stand",
"timeline": [
{
"do": "express",
"atP": 0.6799999999999999,
"expression": "smile"
},
{
"do": "walk",
"to": 0.5204722583333334,
"dur": 2.4, "dur": 2.4,
"atP": 0.6 "atP": 0.6
} }
@@ -112,8 +170,8 @@
{ {
"kind": "person", "kind": "person",
"x": 0.5, "x": 0.5,
"y": 0.8, "y": 0.6914826562499999,
"scale": 0.6, "scale": 0.5,
"enterS": 0.55, "enterS": 0.55,
"character": { "character": {
"name": "Sem", "name": "Sem",
@@ -168,123 +226,9 @@
}, },
{ {
"kind": "person", "kind": "person",
"x": 0.86, "x": 0.6195277416666667,
"y": 0.8, "y": 0.6914826562499999,
"scale": 0.6, "scale": 0.5,
"enterS": 0.9500000000000001,
"character": {
"name": "Jafé",
"look": {
"build": "slim",
"height": 1.08,
"skin": "#d4a074",
"hair": {
"style": "side",
"color": "#6b4226"
},
"beard": {
"style": "goatee",
"color": "#6b4226"
},
"glasses": "none",
"brows": "thin",
"top": {
"style": "robe",
"color": "#c8443a",
"accent": "#6b4a2a"
},
"bottom": {
"style": "pants",
"color": "#2c3346"
},
"shoes": "#6b4a2a",
"footwear": "sandals",
"nose": "round",
"lids": 0.1,
"wrinkles": 0,
"head": "round"
}
},
"expression": "neutral",
"pose": "stand",
"timeline": [
{
"do": "express",
"atP": 0.6799999999999999,
"expression": "smile"
},
{
"do": "walk",
"to": 0.92,
"dur": 2.4,
"atP": 0.6
}
],
"framing": "full",
"flip": true
},
{
"kind": "person",
"x": 0.32,
"y": 0.8300000000000001,
"scale": 0.6,
"enterS": 0.35,
"character": {
"name": "Esposa de Noé",
"look": {
"build": "average",
"height": 0.92,
"skin": "#d09a70",
"hair": {
"style": "long",
"color": "#c9c9cf"
},
"beard": {
"style": "none",
"color": "#a9a9b0"
},
"glasses": "none",
"brows": "thick",
"top": {
"style": "robe",
"color": "#8a6f9e",
"accent": "#6b4a2a"
},
"bottom": {
"style": "pants",
"color": "#2c3346"
},
"shoes": "#6b4a2a",
"footwear": "sandals",
"nose": "button",
"lids": 0.3,
"wrinkles": 0.7,
"head": "round"
}
},
"expression": "neutral",
"pose": "stand",
"timeline": [
{
"do": "express",
"atP": 0.6799999999999999,
"expression": "smile"
},
{
"do": "walk",
"to": 0.46,
"dur": 2.4,
"atP": 0.6
}
],
"framing": "full",
"flip": false
},
{
"kind": "person",
"x": 0.68,
"y": 0.8300000000000001,
"scale": 0.6,
"enterS": 0.7500000000000001, "enterS": 0.7500000000000001,
"character": { "character": {
"name": "Cam", "name": "Cam",
@@ -330,7 +274,64 @@
}, },
{ {
"do": "walk", "do": "walk",
"to": 0.8200000000000001, "to": 0.7595277416666667,
"dur": 2.4,
"atP": 0.6
}
],
"framing": "full",
"flip": true
},
{
"kind": "person",
"x": 0.7390554833333334,
"y": 0.6914826562499999,
"scale": 0.5,
"enterS": 0.9500000000000001,
"character": {
"name": "Jafé",
"look": {
"build": "slim",
"height": 1.08,
"skin": "#d4a074",
"hair": {
"style": "side",
"color": "#6b4226"
},
"beard": {
"style": "goatee",
"color": "#6b4226"
},
"glasses": "none",
"brows": "thin",
"top": {
"style": "robe",
"color": "#c8443a",
"accent": "#6b4a2a"
},
"bottom": {
"style": "pants",
"color": "#2c3346"
},
"shoes": "#6b4a2a",
"footwear": "sandals",
"nose": "round",
"lids": 0.1,
"wrinkles": 0,
"head": "round"
}
},
"expression": "neutral",
"pose": "stand",
"timeline": [
{
"do": "express",
"atP": 0.6799999999999999,
"expression": "smile"
},
{
"do": "walk",
"to": 0.8790554833333334,
"dur": 2.4, "dur": 2.4,
"atP": 0.6 "atP": 0.6
} }
@@ -354,320 +355,274 @@
{ {
"text": "Entraram", "text": "Entraram",
"startS": 0, "startS": 0,
"endS": 0.64 "endS": 0.46
}, },
{ {
"text": "também", "text": "também",
"startS": 0.64, "startS": 0.46,
"endS": 0.88 "endS": 0.7
}, },
{ {
"text": "oito", "text": "oito",
"startS": 0.88, "startS": 0.7,
"endS": 1.2 "endS": 0.98
}, },
{ {
"text": "pessoas,", "text": "pessoas,",
"startS": 1.2, "startS": 0.98,
"endS": 1.78, "endS": 1.5,
"tone": "key" "tone": "key"
}, },
{ {
"text": "Noé,", "text": "Noé,",
"startS": 2, "startS": 1.72,
"endS": 2.44 "endS": 2.1
}, },
{ {
"text": "a", "text": "a",
"startS": 2.66, "startS": 2.28,
"endS": 2.88 "endS": 2.5
}, },
{ {
"text": "esposa,", "text": "esposa,",
"startS": 2.88, "startS": 2.5,
"endS": 3.38 "endS": 2.96
}, },
{ {
"text": "os", "text": "os",
"startS": 3.58, "startS": 3.14,
"endS": 3.84 "endS": 3.38
}, },
{ {
"text": "filhos", "text": "filhos",
"startS": 3.84, "startS": 3.38,
"endS": 4.2 "endS": 3.68
}, },
{ {
"text": "sem,", "text": "sem,",
"startS": 4.2, "startS": 3.68,
"endS": 4.4 "endS": 3.88
}, },
{ {
"text": "Cães", "text": "Cã",
"startS": 4.66, "startS": 4.1,
"endS": 5 "endS": 4.32
},
{
"text": "de",
"startS": 5,
"endS": 5.06
},
{
"text": "Afé,",
"startS": 5.06,
"endS": 5.36
}, },
{ {
"text": "e", "text": "e",
"startS": 5.54, "startS": 4.32,
"endS": 5.8 "endS": 4.42
},
{
"text": "Jafé,",
"startS": 4.42,
"endS": 4.76
},
{
"text": "e",
"startS": 4.88,
"endS": 5.16
}, },
{ {
"text": "as", "text": "as",
"startS": 5.8, "startS": 5.16,
"endS": 6.02 "endS": 5.34
}, },
{ {
"text": "três", "text": "três",
"startS": 6.02, "startS": 5.34,
"endS": 6.2 "endS": 5.52
}, },
{ {
"text": "noras.", "text": "noras.",
"startS": 6.2, "startS": 5.52,
"endS": 6.72 "endS": 5.98
} }
], ],
"audioEnv": { "audioEnv": {
"fps": 30, "fps": 30,
"values": [ "values": [
0, 0,
0, 0.51,
0,
0,
0,
0.55,
0.67,
0.64, 0.64,
0.65, 0.65,
0.39, 0.59,
0.03, 0.17,
0.21,
0.69,
0.97,
0.91,
0.83,
0.62, 0.62,
0.68, 0.47,
0.97, 0.13,
0.97, 0.34,
0.79, 0.71,
0.63, 0.64,
0.52, 0.57,
0.29, 0.26,
0.03, 0.74,
0.68, 0.66,
0.65,
0.55,
0.54,
0.27,
0.88,
0.68,
0.51,
0.51, 0.51,
0.5,
0.58, 0.58,
0.82, 0.82,
0.97,
1,
0.58,
0.04,
0.4,
0.1,
0.02,
0.63,
0.76,
0.28,
0.12,
0.09,
0.11,
0.81,
1,
0.61,
0.53,
0.39,
0.14,
0.05,
0.05,
0.03,
0.01,
0,
0,
0,
0,
0.11,
0.49,
0.6,
0.63,
0.58,
0.76,
0.83,
0.68,
0.64,
0.43,
0.15,
0.03,
0,
0,
0,
0,
0,
0,
0,
0,
0.05,
0.73,
0.84,
0.58,
0.26,
0.03,
0.09,
0.01,
0,
0.89, 0.89,
1, 1,
1, 1,
0.19, 1,
0.05, 0.88,
0.51, 0.32,
0.11,
0.01,
0.67,
0.76,
0.45,
0.1,
0.13,
0.11, 0.11,
0.23, 0.23,
0.93,
1,
0.64,
0.54,
0.44,
0.18,
0.06,
0.06,
0.04,
0.03,
0,
0,
0,
0,
0,
0.08,
0.41,
0.62,
0.69,
0.57,
0.63,
0.82,
0.83,
0.68,
0.67,
0.52,
0.18,
0.05,
0.01,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0.61,
0.96,
0.74,
0.52,
0.12,
0.06,
0.08,
0.01,
0,
0.7,
1,
1,
1,
0.99,
0.65,
0.13,
0.17,
0.19,
0.07, 0.07,
0.01, 0.01,
0, 0,
0, 0,
0, 0,
0, 0,
0,
0.24,
0.77,
0.56,
0.12,
0.07,
0.1,
0.08,
0.02,
0.39,
0.65,
0.66,
0.48,
0.33,
0.43,
0.47,
0.31,
0.03, 0.03,
0.02, 0.53,
0.04,
0.54,
0.67,
0.39,
0.21,
0.14,
0.03,
0,
0,
0,
0,
0,
0,
0.05,
0.2,
0.87,
0.59,
0.76,
0.69,
0.6,
0.51,
0.24,
0.16,
0.8,
1,
0.72, 0.72,
0.1, 0.18,
0.06,
0.09,
0.06,
0.02,
0.54,
0.61,
0.61,
0.32,
0.4,
0.43,
0.35,
0.04,
0.02,
0.04,
0.69,
0.49,
0.27,
0.19,
0.04,
0,
0,
0,
0,
0,
0,
0.07,
0.65,
0.69,
0.66,
0.69,
0.58,
0.53,
0.23,
0.17,
0.83,
1,
0.37,
0.04,
0.02,
0.33,
0.95,
1,
0.63,
0.19,
0.03,
0,
0,
0,
0,
0,
0,
0,
0,
0.32,
0.94,
1,
1,
0.7,
0.14,
0.07,
0.01,
0.03,
1,
0.59,
0.79,
0.37,
0.43,
0.39,
0.15,
0.15,
0.51,
0.75,
0.81,
0.72,
0.62,
0.25,
0.32,
0.16,
0.03,
0.03, 0.03,
0.02, 0.02,
0.4,
1,
1,
0.76,
0.24,
0.04,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0.31,
0.61,
1,
1,
1,
0.52,
0.11,
0.04,
0.01,
0,
0.74,
0.79,
0.95,
0.38,
0.43,
0.44,
0.31,
0.12,
0.18,
0.54,
0.76,
0.84,
0.83,
0.68,
0.46,
0.29,
0.28,
0.13,
0.02, 0.02,
0.02,
0.02,
0.01,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0, 0,
0 0
] ]
+205 -249
View File
@@ -3,7 +3,7 @@
"width": 1080, "width": 1080,
"height": 1920, "height": 1920,
"fps": 30, "fps": 30,
"durationS": 8.246, "durationS": 6.529,
"seed": 71, "seed": 71,
"scene": { "scene": {
"kind": "place", "kind": "place",
@@ -14,15 +14,17 @@
"ground": "water", "ground": "water",
"weather": "storm", "weather": "storm",
"flood": { "flood": {
"from": 0.8, "from": 0.5,
"to": 0.5 "to": 0.5
}, },
"elements": [ "elements": [
{ {
"kind": "ark", "kind": "ark",
"x": 0.5, "x": 0.5,
"z": 0.4, "z": 0.12,
"float": true "float": true,
"occupied": true,
"scale": 1.05
}, },
{ {
"kind": "house", "kind": "house",
@@ -53,8 +55,9 @@
"actors": [ "actors": [
{ {
"kind": "person", "kind": "person",
"x": 0.5, "x": 0.4146230416666667,
"y": 0.78, "y": 0.55064265625,
"scale": 0.66,
"enterS": 0.15, "enterS": 0.15,
"character": { "character": {
"name": "Noé", "name": "Noé",
@@ -103,7 +106,7 @@
"atP": 0.6 "atP": 0.6
} }
], ],
"framing": "medium", "framing": "full",
"flip": false "flip": false
} }
], ],
@@ -122,96 +125,96 @@
{ {
"text": "A", "text": "A",
"startS": 0, "startS": 0,
"endS": 0.32 "endS": 0.18
}, },
{ {
"text": "chuva,", "text": "chuva,",
"startS": 0.32, "startS": 0.18,
"endS": 0.7 "endS": 0.5
}, },
{ {
"text": "diz", "text": "diz",
"startS": 0.88, "startS": 0.7,
"endS": 1.16 "endS": 0.94
}, },
{ {
"text": "o", "text": "o",
"startS": 1.16, "startS": 0.94,
"endS": 1.34 "endS": 1.1
}, },
{ {
"text": "texto,", "text": "texto,",
"startS": 1.34, "startS": 1.1,
"endS": 1.66 "endS": 1.4
}, },
{ {
"text": "durou", "text": "durou",
"startS": 2.02, "startS": 1.7,
"endS": 2.32 "endS": 1.98
}, },
{ {
"text": "40", "text": "40",
"startS": 2.32, "startS": 1.98,
"endS": 2.7, "endS": 2.34,
"tone": "key" "tone": "key"
}, },
{ {
"text": "dias", "text": "dias",
"startS": 2.7, "startS": 2.34,
"endS": 3, "endS": 2.62,
"tone": "key" "tone": "key"
}, },
{ {
"text": "e", "text": "e",
"startS": 3, "startS": 2.62,
"endS": 3.16 "endS": 2.76
}, },
{ {
"text": "40", "text": "40",
"startS": 3.16, "startS": 2.76,
"endS": 3.5, "endS": 3.06,
"tone": "key" "tone": "key"
}, },
{ {
"text": "noites,", "text": "noites,",
"startS": 3.5, "startS": 3.06,
"endS": 3.96 "endS": 3.48
}, },
{ {
"text": "e", "text": "e",
"startS": 4.14, "startS": 3.66,
"endS": 4.4 "endS": 3.88
}, },
{ {
"text": "as", "text": "as",
"startS": 4.4, "startS": 3.88,
"endS": 4.6 "endS": 4.06
}, },
{ {
"text": "águas", "text": "águas",
"startS": 4.6, "startS": 4.06,
"endS": 4.9 "endS": 4.34
}, },
{ {
"text": "prevaleceram", "text": "prevaleceram",
"startS": 4.9, "startS": 4.34,
"endS": 5.56 "endS": 4.94
}, },
{ {
"text": "por", "text": "por",
"startS": 5.56, "startS": 4.94,
"endS": 5.76 "endS": 5.16
}, },
{ {
"text": "150", "text": "150",
"startS": 5.76, "startS": 5.16,
"endS": 6.28, "endS": 5.62,
"tone": "key" "tone": "key"
}, },
{ {
"text": "dias.", "text": "dias.",
"startS": 6.28, "startS": 5.62,
"endS": 6.9, "endS": 6.14,
"tone": "key" "tone": "key"
} }
], ],
@@ -219,241 +222,194 @@
"fps": 30, "fps": 30,
"values": [ "values": [
0, 0,
0,
0,
0,
0,
0.67,
1,
0.69,
0.33,
0.16,
0.18,
0.16,
0.12,
0.45,
0.91,
1,
0.96,
0.21,
0.11,
0.47,
0.28,
0.05,
0,
0,
0,
0,
0,
0,
0.14,
0.09,
0.1,
0.29,
0.63,
0.59,
0.46,
0.14,
0.2,
0.93,
0.76,
0.06,
0.01,
0.19,
0.73,
0.83,
0.81, 0.81,
0.73, 1,
0.39, 0.62,
0.09, 0.28,
0.03,
0.01,
0.07,
0.26,
0.08,
0.01,
0,
0.01,
0,
0,
0,
0,
0.17,
0.19, 0.19,
0.53, 0.17,
0.62,
0.42,
1,
1,
1,
0.36,
0.01,
0.1,
0.66,
1,
1,
0.64,
0.5,
0.47,
0.57,
0.56,
0.29,
0.04,
0.62,
0.62,
0.31,
0.11, 0.11,
0.12, 0.45,
0.16,
0.37,
1,
0.99,
0.62,
0.15,
0.08,
0.4,
0.16,
0.03,
0.29,
0.9, 0.9,
0.84, 1,
0.5, 0.95,
0.46, 0.19,
0.54, 0.16,
0.5,
0.31,
0.04,
0.67,
0.72,
0.34,
0.38,
0.4,
0.56,
0.58,
0.51, 0.51,
0.47, 0.15,
0.18,
0.03,
0.11,
0.1,
0.07,
0.04,
0.02,
0.02,
0.01, 0.01,
0, 0,
0, 0,
0, 0,
0, 0,
0, 0,
0,
0.1,
0.54,
1,
1,
0.79,
0.53,
0.15, 0.15,
0.05, 0.08,
0.38, 0.14,
0.92, 0.5,
1, 0.58,
1,
0.54,
0.16,
0.37,
0.81,
0.55, 0.55,
0.24,
0.12, 0.12,
0.93,
0.81,
0.02,
0.01,
0.47,
0.79,
0.85,
0.81,
0.45,
0.09,
0.06, 0.06,
0.01, 0.01,
0.36, 0.13,
0.25,
0.04,
0,
0,
0,
0,
0,
0,
0.18,
0.28,
0.57,
0.63, 0.63,
0.72, 0.6,
0.15, 1,
0.41, 1,
0.83, 0.55,
0.06,
0.1,
0.75,
1,
1,
0.45, 0.45,
0.56, 0.53,
0.77, 0.54,
0.59,
0.42,
0.06,
0.67,
0.62,
0.27,
0.1,
0.13,
0.22,
0.71,
1,
0.71,
0.23,
0.09,
0.42,
0.14,
0.05,
0.68,
0.91,
0.65,
0.44,
0.49,
0.55,
0.36,
0.19,
0.73,
0.64,
0.36,
0.4,
0.46,
0.62,
0.57,
0.47,
0.2,
0.03,
0.12,
0.09,
0.07,
0.03,
0.02,
0.01,
0,
0,
0,
0,
0,
0,
0.25,
0.96,
1,
0.9,
0.63,
0.19,
0.05,
0.35,
1,
1,
0.85,
0.35,
0.19,
0.7,
0.72,
0.16,
0.07,
0.04,
0.37,
0.78,
0.58,
0.14,
0.75,
0.63,
0.5,
0.75,
0.26, 0.26,
0.03, 0.03,
0.02, 0.02,
0.18, 0.45,
0.75, 0.78,
0.65, 0.48,
0.43, 0.52,
0.55, 0.52,
0.41,
0.06,
0.1,
0.53,
0.22,
0.06,
0.08,
0.02,
0.02,
0.03,
0.57,
0.5,
0.47,
0.34,
0.04,
0.35,
0.3,
0.05,
0.03,
0.35,
0.65,
0.36,
0.07,
0.12,
0.59,
0.62,
0.58,
0.31,
0.02,
0.53,
0.74,
0.34,
0.1,
0.12,
0.17, 0.17,
0.28, 0.05,
0.37, 0.52,
0.46, 0.22,
0.39, 0.07,
0.28,
0.07, 0.07,
0.02, 0.02,
0.02, 0.02,
0.33,
0.57,
0.51,
0.38,
0.04,
0.32,
0.3,
0.02,
0.03, 0.03,
0.59,
0.5,
0.17,
0.09,
0.54,
0.64,
0.58,
0.28,
0.04,
0.68,
0.59,
0.15,
0.11,
0.14,
0.27,
0.38,
0.43,
0.36,
0.24,
0.07,
0.02,
0.02,
0.01, 0.01,
0, 0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0 0
] ]
} }
+136 -175
View File
@@ -3,7 +3,7 @@
"width": 1080, "width": 1080,
"height": 1920, "height": 1920,
"fps": 30, "fps": 30,
"durationS": 5.558, "durationS": 4.095,
"seed": 78, "seed": 78,
"scene": { "scene": {
"kind": "place", "kind": "place",
@@ -21,9 +21,10 @@
{ {
"kind": "ark", "kind": "ark",
"x": 0.5, "x": 0.5,
"z": 0.4, "z": 0.12,
"float": true, "float": true,
"scale": 1.05 "scale": 1.05,
"occupied": true
}, },
{ {
"kind": "waves", "kind": "waves",
@@ -62,9 +63,9 @@
"actors": [ "actors": [
{ {
"kind": "person", "kind": "person",
"x": 0.3, "x": 0.26094451666666674,
"y": 0.8, "y": 0.60064265625,
"scale": 0.9, "scale": 0.66,
"enterS": 0.15, "enterS": 0.15,
"character": { "character": {
"name": "Noé", "name": "Noé",
@@ -122,9 +123,9 @@
}, },
{ {
"kind": "person", "kind": "person",
"x": 0.7, "x": 0.7390554833333334,
"y": 0.8, "y": 0.60064265625,
"scale": 0.9, "scale": 0.66,
"enterS": 0.35, "enterS": 0.35,
"character": { "character": {
"name": "Esposa de Noé", "name": "Esposa de Noé",
@@ -196,207 +197,113 @@
{ {
"text": "Pelas", "text": "Pelas",
"startS": 0, "startS": 0,
"endS": 0.48 "endS": 0.3
}, },
{ {
"text": "datas", "text": "datas",
"startS": 0.48, "startS": 0.3,
"endS": 0.74 "endS": 0.54
}, },
{ {
"text": "do", "text": "do",
"startS": 0.74, "startS": 0.54,
"endS": 0.96 "endS": 0.76
}, },
{ {
"text": "Gênesis,", "text": "Gênesis,",
"startS": 0.96, "startS": 0.76,
"endS": 1.48 "endS": 1.2
}, },
{ {
"text": "a", "text": "a",
"startS": 1.66, "startS": 1.38,
"endS": 1.88 "endS": 1.54
}, },
{ {
"text": "família", "text": "família",
"startS": 1.88, "startS": 1.54,
"endS": 2.18 "endS": 1.86
}, },
{ {
"text": "ficou", "text": "ficou",
"startS": 2.18, "startS": 1.86,
"endS": 2.54 "endS": 2.18
}, },
{ {
"text": "cerca", "text": "cerca",
"startS": 2.54, "startS": 2.18,
"endS": 2.88 "endS": 2.48
}, },
{ {
"text": "de", "text": "de",
"startS": 2.88, "startS": 2.48,
"endS": 3.06 "endS": 2.64
}, },
{ {
"text": "um", "text": "um",
"startS": 3.06, "startS": 2.64,
"endS": 3.22 "endS": 2.78
}, },
{ {
"text": "ano", "text": "ano",
"startS": 3.22, "startS": 2.78,
"endS": 3.48 "endS": 3.02
}, },
{ {
"text": "dentro", "text": "dentro",
"startS": 3.48, "startS": 3.02,
"endS": 3.82 "endS": 3.34
}, },
{ {
"text": "da", "text": "da",
"startS": 3.82, "startS": 3.34,
"endS": 4.02 "endS": 3.52
}, },
{ {
"text": "arca.", "text": "arca.",
"startS": 4.02, "startS": 3.52,
"endS": 4.32 "endS": 3.8
} }
], ],
"audioEnv": { "audioEnv": {
"fps": 30, "fps": 30,
"values": [ "values": [
0, 0,
0,
0,
0,
0,
0.27,
0.85,
1,
0.47, 0.47,
0.69,
0.94,
0.96,
0.31,
0.12,
0.07,
0.63,
1, 1,
1,
1,
0.62,
0.03,
0.15,
0.64,
0.62,
0.2,
0.04,
0.34,
0.91,
0.78,
0.34,
0.17,
0.21,
0.64,
0.82,
0.78,
0.54,
0.38,
0.41,
0.22,
0.05,
0.06,
0.11,
0.04,
0.03,
0.02,
0.01,
0,
0,
0,
0,
0,
0,
0.01,
0.77,
0.53,
0.08,
0.02,
0.35,
0.95,
0.74,
0.48,
0.57,
0.69,
0.53,
0.36,
0.67,
1,
0.35,
0.03,
0.03,
0.63,
0.26,
0.05,
0.48,
0.86,
0.85,
0.39,
0.07,
0.03,
0.02,
0.4,
0.84,
0.61,
0.26,
0.02,
0.12,
0.77,
0.76,
0.2,
0.12,
0.21,
0.56, 0.56,
0.7, 0.59,
0.85,
0.84,
0.3,
0.1,
0.08,
0.95,
1,
1,
0.87,
0.06,
0.08,
0.55,
0.46,
0.14,
0.04,
0.57,
0.82, 0.82,
0.55, 0.55,
0.5, 0.14,
0.55, 0.17,
0.65, 0.58,
0.7, 0.79,
0.66, 0.69,
0.6, 0.44,
0.52, 0.36,
0.42,
0.76,
0.65,
0.23,
0.12,
0.06,
0.64,
0.95,
0.86,
0.71,
0.54,
0.34,
0.1,
0.32, 0.32,
0.34, 0.1,
0.12, 0.02,
1, 0.1,
1,
1,
0.84,
0.63,
0.5,
0.18,
0.09,
0.04, 0.04,
0.05, 0.02,
0.16,
0.15,
0.02, 0.02,
0.01, 0.01,
0, 0,
@@ -405,23 +312,77 @@
0, 0,
0, 0,
0, 0,
0, 0.55,
0, 0.6,
0, 0.11,
0, 0.03,
0, 0.52,
0, 0.96,
0, 0.57,
0, 0.51,
0, 0.66,
0, 0.53,
0, 0.4,
0, 0.53,
0, 0.95,
0, 0.27,
0, 0.03,
0, 0.13,
0, 0.59,
0.07,
0.17,
0.77,
0.82,
0.45,
0.07,
0.03,
0.03,
0.55,
0.75,
0.39,
0.09,
0.1,
0.7,
0.74,
0.21,
0.13,
0.22,
0.56,
0.74,
0.69,
0.45,
0.47,
0.6,
0.65,
0.65,
0.56,
0.48,
0.49,
0.71,
0.45,
0.11,
0.08,
0.41,
0.96,
0.8,
0.67,
0.49,
0.23,
0.22,
0.34,
0.13,
1,
1,
1,
0.75,
0.62,
0.42,
0.15,
0.07,
0.01,
0.08,
0.19,
0.04,
0, 0,
0 0
] ]
+170 -198
View File
@@ -3,7 +3,7 @@
"width": 1080, "width": 1080,
"height": 1920, "height": 1920,
"fps": 30, "fps": 30,
"durationS": 6.206, "durationS": 4.697,
"seed": 85, "seed": 85,
"scene": { "scene": {
"kind": "place", "kind": "place",
@@ -21,9 +21,10 @@
{ {
"kind": "ark", "kind": "ark",
"x": 0.5, "x": 0.5,
"z": 0.4, "z": 0.12,
"float": true, "float": true,
"scale": 1.05 "scale": 1.05,
"occupied": true
}, },
{ {
"kind": "waves", "kind": "waves",
@@ -62,8 +63,9 @@
"actors": [ "actors": [
{ {
"kind": "person", "kind": "person",
"x": 0.5, "x": 0.4146230416666667,
"y": 0.78, "y": 0.60064265625,
"scale": 0.66,
"enterS": 0.15, "enterS": 0.15,
"character": { "character": {
"name": "Noé", "name": "Noé",
@@ -115,6 +117,17 @@
"framing": "full", "framing": "full",
"flip": false "flip": false
}, },
{
"kind": "animal",
"species": "raven",
"x": 0.06,
"y": 0.3,
"scale": 2.4,
"fly": true,
"walk": {
"to": 0.82
}
},
{ {
"kind": "animal", "kind": "animal",
"species": "raven", "species": "raven",
@@ -142,264 +155,223 @@
{ {
"text": "Com", "text": "Com",
"startS": 0, "startS": 0,
"endS": 0.28 "endS": 0.12
}, },
{ {
"text": "as", "text": "as",
"startS": 0.28, "startS": 0.12,
"endS": 0.54 "endS": 0.36
}, },
{ {
"text": "águas", "text": "águas",
"startS": 0.54, "startS": 0.36,
"endS": 0.86 "endS": 0.66
}, },
{ {
"text": "baixando,", "text": "baixando,",
"startS": 0.86, "startS": 0.66,
"endS": 1.38 "endS": 1.12
}, },
{ {
"text": "Noé", "text": "Noé",
"startS": 1.72, "startS": 1.38,
"endS": 1.92 "endS": 1.62
}, },
{ {
"text": "soltou", "text": "soltou",
"startS": 1.92, "startS": 1.62,
"endS": 2.26 "endS": 1.92
}, },
{ {
"text": "um", "text": "um",
"startS": 2.26, "startS": 1.92,
"endS": 2.42 "endS": 2.04
}, },
{ {
"text": "corvo,", "text": "corvo,",
"startS": 2.42, "startS": 2.04,
"endS": 2.78, "endS": 2.4,
"tone": "key" "tone": "key"
}, },
{ {
"text": "que", "text": "que",
"startS": 2.88, "startS": 2.5,
"endS": 3.18 "endS": 2.76
}, },
{ {
"text": "ia", "text": "ia",
"startS": 3.18, "startS": 2.76,
"endS": 3.42 "endS": 3
}, },
{ {
"text": "e", "text": "e",
"startS": 3.42, "startS": 3,
"endS": 3.56 "endS": 3.1
}, },
{ {
"text": "voltava", "text": "voltava",
"startS": 3.56, "startS": 3.1,
"endS": 3.98, "endS": 3.48,
"tone": "key" "tone": "key"
}, },
{ {
"text": "até", "text": "até",
"startS": 3.98, "startS": 3.48,
"endS": 4.18 "endS": 3.66
}, },
{ {
"text": "a", "text": "a",
"startS": 4.18, "startS": 3.66,
"endS": 4.34 "endS": 3.82
}, },
{ {
"text": "terra", "text": "terra",
"startS": 4.34, "startS": 3.82,
"endS": 4.52 "endS": 3.94
}, },
{ {
"text": "secar.", "text": "secar.",
"startS": 4.52, "startS": 3.94,
"endS": 5.02 "endS": 4.42
} }
], ],
"audioEnv": { "audioEnv": {
"fps": 30, "fps": 30,
"values": [ "values": [
0, 0,
0,
0,
0,
0,
0.06,
0.45,
0.95,
0.63,
0.62,
0.91,
0.93,
0.79,
0.36,
0.1,
0.06,
0.52,
0.91,
1,
0.94,
0.66,
0.18,
0.31,
0.85,
0.66,
0.17,
0.11,
0.32,
1,
0.77,
0.47,
0.16,
0.16,
0.12,
0.29,
0.67,
0.63,
0.45,
0.35,
0.15,
0.12,
0.06,
0.02,
0,
0,
0.01,
0.01,
0.01,
0,
0,
0.15,
0.42,
0.65,
0.62,
0.64,
0.67,
0.64,
0.28,
0.06,
0.08,
0.77,
1,
0.37,
0.06,
0,
0.77,
1,
1,
0.88,
0.69,
0.48,
0.2,
0.01,
0.08,
0.43,
0.93,
1,
0.92,
0.29,
0.18,
0.06,
0.03,
0.08,
0.01,
0.01,
0,
0,
0,
0,
0,
0,
0.02,
0.03,
0.5,
0.62,
0.57,
0.45,
0.43,
0.44,
0.49,
0.49,
0.68,
0.77,
0.52,
0.64,
0.39,
0.12,
0.78,
1,
0.81,
0.31,
0.02,
0.05, 0.05,
0.76,
0.98,
1,
0.96,
0.32,
0.24,
0.77,
0.42,
0.02,
0,
0.38,
0.66,
1,
0.94, 0.94,
0.71, 0.58,
0.08, 0.55,
0, 0.84,
0.28, 0.82,
0.67, 0.74,
0.59,
0.68,
0.42,
0.44,
0.47,
0.21,
0.02,
0.02,
0.56,
0.68,
0.09,
0.01,
0.38,
0.79,
0.8,
0.5,
0.27, 0.27,
0.08, 0.08,
0.11,
0.71,
1,
1,
0.66,
0.17,
0.34,
0.79,
0.42,
0.12,
0.11,
0.74,
0.86,
0.5,
0.16,
0.18,
0.16,
0.35,
0.57,
0.57,
0.37,
0.23,
0.06,
0.1,
0.02, 0.02,
0,
0,
0.01,
0.01,
0.01,
0,
0,
0.31,
0.57,
0.56,
0.6,
0.63,
0.59,
0.23,
0.07,
0.45,
1,
0.51,
0.08,
0,
0.71,
1,
1,
0.75,
0.57,
0.35,
0.04,
0.05,
0.27,
0.77,
1,
0.86,
0.26,
0.12,
0.03,
0.07,
0.03,
0.01, 0.01,
0, 0,
0, 0,
0, 0,
0, 0,
0, 0,
0.01,
0.02,
0.24,
0.56,
0.56,
0.43,
0.41,
0.39,
0.43,
0.48,
0.69,
0.58,
0.55,
0.53,
0.12,
0.53,
1,
0.75,
0.23,
0.01,
0.35,
0.81,
0.89,
0.98,
0.57,
0.13,
0.66,
0.4,
0.02,
0, 0,
0, 0.42,
0, 0.79,
0, 0.91,
0, 0.8,
0, 0.25,
0, 0.01,
0, 0.29,
0, 0.61,
0, 0.54,
0, 0.61,
0, 0.38,
0, 0.44,
0, 0.34,
0, 0.08,
0, 0.01,
0, 0.35,
0, 0.69,
0.09,
0.05,
0.36,
0.75,
0.6,
0.38,
0.15,
0.04,
0.01,
0 0
] ]
} }
+291 -343
View File
@@ -3,7 +3,7 @@
"width": 1080, "width": 1080,
"height": 1920, "height": 1920,
"fps": 30, "fps": 30,
"durationS": 11.078, "durationS": 8.747,
"seed": 92, "seed": 92,
"scene": { "scene": {
"kind": "place", "kind": "place",
@@ -21,9 +21,10 @@
{ {
"kind": "ark", "kind": "ark",
"x": 0.5, "x": 0.5,
"z": 0.4, "z": 0.12,
"float": true, "float": true,
"scale": 1.05 "scale": 1.05,
"occupied": true
}, },
{ {
"kind": "waves", "kind": "waves",
@@ -62,8 +63,9 @@
"actors": [ "actors": [
{ {
"kind": "person", "kind": "person",
"x": 0.34, "x": 0.4146230416666667,
"y": 0.78, "y": 0.60064265625,
"scale": 0.66,
"enterS": 0.15, "enterS": 0.15,
"character": { "character": {
"name": "Noé", "name": "Noé",
@@ -116,6 +118,18 @@
"item": "olive", "item": "olive",
"flip": false "flip": false
}, },
{
"kind": "animal",
"species": "dove",
"x": 0.06,
"y": 0.3,
"scale": 2.4,
"fly": true,
"walk": {
"to": 0.82
},
"carry": "olive"
},
{ {
"kind": "animal", "kind": "animal",
"species": "dove", "species": "dove",
@@ -144,445 +158,379 @@
{ {
"text": "Depois,", "text": "Depois,",
"startS": 0, "startS": 0,
"endS": 0.62 "endS": 0.44
}, },
{ {
"text": "Noé", "text": "Noé",
"startS": 1.06, "startS": 0.86,
"endS": 1.28 "endS": 1.04
}, },
{ {
"text": "soltou", "text": "soltou",
"startS": 1.28, "startS": 1.04,
"endS": 1.72 "endS": 1.44
}, },
{ {
"text": "uma", "text": "uma",
"startS": 1.72, "startS": 1.44,
"endS": 1.92 "endS": 1.62
}, },
{ {
"text": "pomba.", "text": "pomba.",
"startS": 1.92, "startS": 1.62,
"endS": 2.44, "endS": 2.1,
"tone": "key" "tone": "key"
}, },
{ {
"text": "Ela", "text": "Ela",
"startS": 3.12, "startS": 2.22,
"endS": 3.48 "endS": 2.66
}, },
{ {
"text": "voltou", "text": "voltou",
"startS": 3.48, "startS": 2.66,
"endS": 3.9 "endS": 3.04
}, },
{ {
"text": "sem", "text": "sem",
"startS": 3.9, "startS": 3.04,
"endS": 4.12 "endS": 3.26
}, },
{ {
"text": "achar", "text": "achar",
"startS": 4.12, "startS": 3.26,
"endS": 4.54 "endS": 3.64
}, },
{ {
"text": "onde", "text": "onde",
"startS": 4.54, "startS": 3.64,
"endS": 4.66 "endS": 3.74
}, },
{ {
"text": "pousar,", "text": "pousar.",
"startS": 4.66, "startS": 3.74,
"endS": 5.16 "endS": 4.2
}, },
{ {
"text": "na", "text": "Na",
"startS": 5.28, "startS": 4.32,
"endS": 5.44 "endS": 4.44
}, },
{ {
"text": "segunda", "text": "segunda",
"startS": 5.44, "startS": 4.44,
"endS": 5.8 "endS": 4.76
}, },
{ {
"text": "vez,", "text": "vez,",
"startS": 5.8, "startS": 4.76,
"endS": 6.24 "endS": 5.18
}, },
{ {
"text": "trouxe", "text": "trouxe",
"startS": 6.42, "startS": 5.4,
"endS": 6.82 "endS": 5.7
}, },
{ {
"text": "uma", "text": "uma",
"startS": 6.82, "startS": 5.7,
"endS": 6.98 "endS": 5.84
}, },
{ {
"text": "folha", "text": "folha",
"startS": 6.98, "startS": 5.84,
"endS": 7.34 "endS": 6.18
}, },
{ {
"text": "de", "text": "de",
"startS": 7.34, "startS": 6.18,
"endS": 7.44 "endS": 6.28
}, },
{ {
"text": "oliveira,", "text": "oliveira.",
"startS": 7.44, "startS": 6.28,
"endS": 7.92, "endS": 6.7,
"tone": "key" "tone": "key"
}, },
{ {
"text": "na", "text": "Na",
"startS": 8.14, "startS": 6.9,
"endS": 8.34 "endS": 7.08
}, },
{ {
"text": "terceira,", "text": "terceira,",
"startS": 8.34, "startS": 7.08,
"endS": 8.86 "endS": 7.56
}, },
{ {
"text": "não", "text": "não",
"startS": 9.04, "startS": 7.74,
"endS": 9.36 "endS": 8.02
}, },
{ {
"text": "voltou.", "text": "voltou.",
"startS": 9.36, "startS": 8.02,
"endS": 9.82 "endS": 8.42
} }
], ],
"audioEnv": { "audioEnv": {
"fps": 30, "fps": 30,
"values": [ "values": [
0, 0,
0, 0.17,
0,
0,
0,
0.18,
0.13, 0.13,
1, 1,
1, 1,
0.59,
0.04,
0.01,
0,
0.35,
0.97,
1,
0.94,
0.93,
0.8,
0.21,
0.1,
0.08,
0.05,
0.01,
0,
0,
0,
0,
0,
0,
0.19,
0.55,
0.61,
0.69,
0.7,
0.59,
0.43,
0.57,
0.4,
0.07,
0.06,
0.22,
1,
0.62,
0.32, 0.32,
0.06, 0.02,
0.01, 0,
0.27, 0.3,
1,
1,
1,
0.7,
0.69,
0.51,
0.31,
0.52,
0.91, 0.91,
0.86, 0.95,
0.19, 0.91,
0.02, 0.93,
0,
0.17,
0.61,
0.61,
0.52,
0.43,
0.29,
0.17,
0.23,
0.18,
0.05,
0.01,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0.45,
0.76,
0.89,
0.55,
0.82,
0.9,
0.55,
0.1,
0.61,
0.75,
0.6,
0.29,
0.03,
0,
0.61,
0.8,
0.75,
0.62,
0.25,
0.05,
0.03,
0.03,
0.57,
0.44,
0.37,
0.47,
0.69,
0.49,
0.14,
0.13,
0.17,
0.12,
0.63,
0.97,
1,
0.71,
0.59,
0.51,
0.5,
0.32,
0.17,
0.41,
0.05,
0.01,
0.45,
0.71,
0.59,
0.26,
0.08,
0.2,
0.65, 0.65,
0.74,
0.68,
0.39,
0.11, 0.11,
0.04, 0.09,
0.02,
0.01,
0,
0,
0.01,
0.2,
0.51,
0.55,
0.13,
0.02,
0.03,
0.52,
0.35,
0.15,
0.3,
0.76,
0.49,
0.49,
0.41,
0.8,
0.82,
0.84,
0.22,
0.08,
0.27,
0.93,
1,
1,
0.67,
0.38,
0.07,
0.04,
0.04,
0.02,
0.01,
0,
0,
0,
0,
0,
0,
0.04,
0.38,
0.63,
0.86,
0.66,
0.23,
0.06,
0.1,
0.31,
0.49,
0.36,
0.81,
0.97,
0.37,
0.05, 0.05,
0.02, 0.02,
0.02,
0.36,
1,
1,
0.97,
0.39,
0.8,
1,
0.83,
0.13,
0.33,
0.94,
0.65,
0.39,
0.83,
0.6,
0.22,
0.1,
0.42,
1,
1,
0.7,
0.36,
0.24,
0.26,
0.07,
0.01,
0,
0,
0.01,
0.01,
0, 0,
0, 0,
0, 0,
0.12, 0,
0,
0,
0.3, 0.3,
0.74, 0.56,
0.81, 0.62,
0.14, 0.66,
0.01, 0.6,
0.37, 0.45,
1, 0.54,
0.55, 0.39,
0.17,
0.06, 0.06,
0.02, 0.05,
0.02, 0.57,
0.42, 1,
0.82, 0.45,
0.82, 0.13,
0.81, 0.01,
0.5, 0.03,
0.94,
1,
1,
0.62,
0.68,
0.37,
0.3,
0.77,
0.85,
0.36, 0.36,
0.02,
0,
0.27, 0.27,
0.56,
0.58,
0.47,
0.35,
0.21,
0.14,
0.24,
0.05,
0.01,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0.42,
0.71,
0.83,
0.52,
0.81,
0.8,
0.22,
0.25,
0.77,
0.61,
0.33,
0.03, 0.03,
0.01, 0.01,
0,
0,
0,
0,
0,
0.08,
0.25,
0.5,
0.59,
0.99,
0.72,
0.56,
0.6, 0.6,
0.75,
0.7,
0.43, 0.43,
0.2, 0.1,
0.42, 0.03,
0.93, 0.02,
0.63, 0.56,
0.39,
0.34,
0.53,
0.64,
0.34,
0.12,
0.15,
0.13,
0.49,
0.9,
1,
0.71,
0.6,
0.48,
0.45,
0.11,
0.4,
0.11,
0.01,
0.33,
0.68,
0.53,
0.22,
0.06,
0.34,
0.7,
0.65,
0.53,
0.17,
0.04,
0.02,
0.01,
0,
0,
0.06,
0.32,
0.58,
0.37,
0.02,
0.03,
0.43,
0.29,
0.14,
0.48,
0.66,
0.45,
0.46,
0.53,
0.8,
0.81,
0.23,
0.08,
0.31,
0.99,
1,
1,
0.46,
0.14,
0.03,
0.03,
0.02,
0.01,
0,
0,
0,
0,
0,
0.02,
0.36,
0.51,
0.83,
0.62,
0.21,
0.05,
0.09,
0.47, 0.47,
0.34, 0.34,
0.54,
1,
0.46,
0.07,
0.02, 0.02,
0.01, 0.01,
0.4,
1, 1,
0.73, 1,
0.45, 1,
0.17, 0.71,
0.38,
1,
0.97,
0.14,
0.39,
0.91,
0.54,
0.55,
0.77,
0.39,
0.11,
0.26,
0.95,
1,
0.67,
0.23,
0.28,
0.16,
0.01,
0,
0,
0,
0.01,
0,
0,
0,
0.2,
0.49,
0.84,
0.47,
0.02,
0.26,
0.94,
0.59,
0.16,
0.05,
0.01,
0.03, 0.03,
0.62,
0.81,
0.73,
0.57,
0.33,
0.26,
0.02,
0.01, 0.01,
0, 0,
0, 0,
0, 0,
0, 0,
0, 0.05,
0, 0.19,
0, 0.46,
0, 0.56,
0, 0.95,
0, 0.67,
0, 0.53,
0, 0.55,
0, 0.31,
0, 0.21,
0, 0.77,
0, 0.71,
0, 0.43,
0, 0.36,
0, 0.02,
0, 0.02,
0, 0.53,
0, 0.9,
0, 0.51,
0, 0.27,
0.06,
0.01,
0 0
] ]
} }
+266 -316
View File
@@ -3,7 +3,7 @@
"width": 1080, "width": 1080,
"height": 1920, "height": 1920,
"fps": 30, "fps": 30,
"durationS": 10.118, "durationS": 8.253,
"seed": 99, "seed": 99,
"scene": { "scene": {
"kind": "place", "kind": "place",
@@ -35,9 +35,9 @@
}, },
{ {
"kind": "ark", "kind": "ark",
"x": 0.46, "x": 0.5,
"z": 0.82, "z": 0.82,
"scale": 0.8, "scale": 1.35,
"lift": 0.1 "lift": 0.1
}, },
{ {
@@ -60,8 +60,9 @@
"actors": [ "actors": [
{ {
"kind": "person", "kind": "person",
"x": 0.5, "x": 0.15,
"y": 0.78, "y": 0.8,
"scale": 0.72,
"enterS": 0.15, "enterS": 0.15,
"character": { "character": {
"name": "Noé", "name": "Noé",
@@ -116,7 +117,7 @@
"atP": 0.55 "atP": 0.55
} }
], ],
"framing": "medium", "framing": "full",
"flip": false "flip": false
} }
], ],
@@ -135,414 +136,363 @@
{ {
"text": "A", "text": "A",
"startS": 0, "startS": 0,
"endS": 0.28 "endS": 0.14
}, },
{ {
"text": "arca", "text": "arca",
"startS": 0.28, "startS": 0.14,
"endS": 0.68 "endS": 0.5
}, },
{ {
"text": "pousou,", "text": "pousou,",
"startS": 0.68, "startS": 0.5,
"endS": 1.08 "endS": 0.86
}, },
{ {
"text": "diz", "text": "diz",
"startS": 1.3, "startS": 1.06,
"endS": 1.56 "endS": 1.3
}, },
{ {
"text": "o", "text": "o",
"startS": 1.56, "startS": 1.3,
"endS": 1.72 "endS": 1.44
}, },
{ {
"text": "Gênesis,", "text": "Gênesis,",
"startS": 1.72, "startS": 1.44,
"endS": 2.22 "endS": 1.9
}, },
{ {
"text": "sobre", "text": "sobre",
"startS": 2.46, "startS": 2.12,
"endS": 2.74 "endS": 2.36
}, },
{ {
"text": "os", "text": "os",
"startS": 2.74, "startS": 2.36,
"endS": 2.92 "endS": 2.52
}, },
{ {
"text": "montes", "text": "montes",
"startS": 2.92, "startS": 2.52,
"endS": 3.32 "endS": 2.88
}, },
{ {
"text": "de", "text": "de",
"startS": 3.32, "startS": 2.88,
"endS": 3.42 "endS": 2.98
}, },
{ {
"text": "Ararat,", "text": "Ararat,",
"startS": 3.42, "startS": 2.98,
"endS": 3.84 "endS": 3.36
}, },
{ {
"text": "uma", "text": "uma",
"startS": 4.06, "startS": 3.6,
"endS": 4.4 "endS": 3.88
}, },
{ {
"text": "região,", "text": "região,",
"startS": 4.4, "startS": 3.88,
"endS": 4.84, "endS": 4.28,
"tone": "key" "tone": "key"
}, },
{ {
"text": "não", "text": "não",
"startS": 5.08, "startS": 4.46,
"endS": 5.38 "endS": 4.78
}, },
{ {
"text": "necessariamente", "text": "necessariamente",
"startS": 5.38, "startS": 4.78,
"endS": 6 "endS": 5.36
}, },
{ {
"text": "o", "text": "o",
"startS": 6, "startS": 5.36,
"endS": 6.26 "endS": 5.56
}, },
{ {
"text": "pico", "text": "pico",
"startS": 6.26, "startS": 5.56,
"endS": 6.5 "endS": 5.78
}, },
{ {
"text": "hoje", "text": "hoje",
"startS": 6.5, "startS": 5.78,
"endS": 6.76 "endS": 6.02
}, },
{ {
"text": "chamado", "text": "chamado",
"startS": 6.76, "startS": 6.02,
"endS": 7.2 "endS": 6.44
}, },
{ {
"text": "Monte", "text": "Monte",
"startS": 7.2, "startS": 6.44,
"endS": 7.58 "endS": 6.76
}, },
{ {
"text": "Arara,", "text": "Arara,",
"startS": 7.58, "startS": 6.76,
"endS": 7.98 "endS": 7.14
}, },
{ {
"text": "na", "text": "na",
"startS": 8.18, "startS": 7.3,
"endS": 8.36 "endS": 7.48
}, },
{ {
"text": "Turquia.", "text": "Turquia.",
"startS": 8.36, "startS": 7.48,
"endS": 8.88 "endS": 7.94
} }
], ],
"audioEnv": { "audioEnv": {
"fps": 30, "fps": 30,
"values": [ "values": [
0,
0,
0,
0,
0.01,
0.51,
1,
0.97,
1,
1,
0.85,
0.9,
0.8,
0.68,
0.36,
0.22,
0.02, 0.02,
0.12,
0.76, 0.76,
1,
0.95,
1,
0.88,
0.85, 0.85,
0.12, 0.82,
0.01, 0.65,
0.31,
0.83,
0.94,
0.47,
0.21,
0.08,
0.3,
0.96,
0.99,
0.7,
0.34,
0.07,
0.02,
0,
0,
0,
0,
0,
0.17,
0.11,
0.14,
0.54,
0.78,
0.58,
0.17,
0.27,
0.98,
0.91,
0.35, 0.35,
0.2, 0.14,
0.31,
0.83,
0.75,
0.68,
0.44,
0.49,
0.47,
0.38,
0.08,
0.04,
0.18,
0.16,
0.03,
0.02,
0.03,
0.01, 0.01,
0,
0,
0.01,
0.01,
0,
0,
0.01,
0.04,
0.08,
0.4,
1,
1,
0.21, 0.21,
0.39, 0.92,
0.62, 0.5,
0.02,
0.18,
0.82,
0.91,
0.42,
0.15,
0.09,
0.58,
1, 1,
0.7, 0.85,
0.23, 0.42,
0.1, 0.12,
0.03,
0,
0,
0,
0,
0.01,
0.15, 0.15,
0.41, 0.12,
0.62, 0.37,
0.81, 0.74,
0.76, 0.59,
0.9, 0.17,
0.84, 0.26,
0.79, 1,
0.16, 0.69,
0.15,
0.41,
0.41,
0.21, 0.21,
0.19, 0.19,
0.83, 0.64,
1, 0.78,
0.92, 0.69,
0.85,
1,
0.77,
0.38,
0.73,
0.68,
0.77,
0.74,
0.6,
0.12,
0.06,
0.16,
0.09,
0.06,
0.01,
0,
0,
0,
0,
0,
0,
0,
0,
0.38,
0.53,
0.51, 0.51,
1,
1,
0.79,
0.63,
0.7,
0.86,
0.73,
0.35,
0.18,
0.22,
0.39,
0.88,
0.89,
0.76,
0.68,
0.39,
0.2,
0.04,
0,
0,
0.01,
0.01,
0,
0,
0,
0,
0.4,
0.55,
0.86,
0.92,
0.49,
0.6,
0.52,
0.52,
0.82,
0.75,
0.1,
0.04,
0.44,
0.48, 0.48,
0.46,
0.31,
0.07,
0.07,
0.19,
0.06, 0.06,
0.03, 0.03,
0.65, 0.03,
0.82,
0.49,
0.87,
0.6,
0.5,
0.59,
0.61,
0.51,
0.54,
0.31,
0.09,
0.22,
0.48,
0.05,
0.01, 0.01,
0.4, 0,
0,
0.01,
0.01,
0,
0,
0.03,
0.08,
0.45,
1,
0.9,
0.2,
0.38,
0.86,
1,
0.34,
0.11,
0.12,
0.32,
0.62,
0.79,
0.8,
0.85,
0.86,
0.6,
0.09,
0.19,
0.5,
0.25,
0.19,
0.76,
0.98,
0.8, 0.8,
1, 1,
0.78,
0.06,
0.08,
0.54,
0.95,
0.95,
1,
1,
0.94, 0.94,
0.72, 0.59,
0.33,
0.18,
0.37,
0.26,
0.17,
0.16,
0.46,
0.9,
0.74,
0.47,
0.72,
0.93,
1,
0.62,
0.18,
0.69,
0.6,
0.47,
0.47,
0.57, 0.57,
0.7,
0.7,
0.72, 0.72,
0.81, 0.58,
0.09,
0.07,
0.14,
0.07,
0.04,
0,
0,
0,
0,
0,
0,
0,
0.07,
0.5,
0.49,
0.62,
1,
0.8,
0.61,
0.66,
0.79,
0.72,
0.26,
0.18,
0.31,
0.77,
0.9,
0.7,
0.66,
0.39,
0.18,
0.04,
0,
0,
0.01,
0,
0,
0,
0,
0.36,
0.55,
0.91,
0.79,
0.55,
0.56,
0.5,
0.72,
0.8,
0.2,
0.03,
0.54,
0.34,
0.03,
0.06,
0.78,
0.48,
0.85,
0.66,
0.48,
0.56,
0.61,
0.51,
0.52,
0.19,
0.11,
0.44,
0.12,
0.01,
0.44,
0.82,
1,
0.68,
0.06,
0.19,
0.86,
0.89,
1,
1,
0.93,
0.72,
0.31,
0.22,
0.36,
0.19,
0.18,
0.28,
0.84,
0.8,
0.45,
0.73, 0.73,
0.92,
0.96,
0.42,
0.3,
0.76,
0.44,
0.46,
0.51,
0.75,
0.75,
0.72,
0.58,
0.29,
0.13,
0.39,
1,
1,
0.64,
0.96,
0.89,
0.88,
0.79,
0.38,
0.5,
0.33,
0.11,
0.04,
0.01,
0,
0,
0,
0.06,
0.23,
0.7,
0.85,
0.13,
0.01,
0.16,
0.59, 0.59,
0.39, 0.39,
0.08, 0.08,
0.13,
0.79,
1,
0.77,
0.83,
1,
0.91,
0.88,
0.85,
0.51,
0.47,
0.45,
0.25,
0.08,
0.03,
0.01, 0.01,
0, 0.02,
0, 0.04,
0, 0.33,
0.05, 0.69,
0.18, 0.69,
0.49, 0.61,
0.93, 0.22,
0.54,
0.03,
0,
0.32,
0.64,
0.39,
0.08,
0.03,
0.01,
0.03,
0.1,
0.62,
0.68,
0.79,
0.53,
0.21,
0.07, 0.07,
0.01, 0.02,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0, 0,
0 0
] ]
+330 -377
View File
@@ -3,7 +3,7 @@
"width": 1080, "width": 1080,
"height": 1920, "height": 1920,
"fps": 30, "fps": 30,
"durationS": 8.006, "durationS": 6.304,
"seed": 106, "seed": 106,
"scene": { "scene": {
"kind": "place", "kind": "place",
@@ -61,7 +61,7 @@
"actors": [ "actors": [
{ {
"kind": "person", "kind": "person",
"x": 0.14, "x": 0.15,
"y": 0.8, "y": 0.8,
"scale": 0.6, "scale": 0.6,
"enterS": 0.15, "enterS": 0.15,
@@ -127,9 +127,75 @@
}, },
{ {
"kind": "person", "kind": "person",
"x": 0.5, "x": 0.85,
"y": 0.8, "y": 0.8,
"scale": 0.6, "scale": 0.6,
"enterS": 0.35,
"character": {
"name": "Esposa de Noé",
"look": {
"build": "average",
"height": 0.92,
"skin": "#d09a70",
"hair": {
"style": "long",
"color": "#c9c9cf"
},
"beard": {
"style": "none",
"color": "#a9a9b0"
},
"glasses": "none",
"brows": "thick",
"top": {
"style": "robe",
"color": "#8a6f9e",
"accent": "#6b4a2a"
},
"bottom": {
"style": "pants",
"color": "#2c3346"
},
"shoes": "#6b4a2a",
"footwear": "sandals",
"nose": "button",
"lids": 0.3,
"wrinkles": 0.7,
"head": "round"
}
},
"expression": "neutral",
"pose": "arms_up",
"timeline": [
{
"do": "express",
"atP": 0.6699999999999999,
"expression": "happy"
},
{
"do": "look",
"dir": "up",
"atP": 0.48
},
{
"do": "pose",
"pose": "celebrate",
"atP": 0.62
},
{
"do": "bounce",
"times": 2,
"atP": 0.62
}
],
"framing": "full",
"flip": true
},
{
"kind": "person",
"x": 0.25,
"y": 0.8300000000000001,
"scale": 0.6,
"enterS": 0.55, "enterS": 0.55,
"character": { "character": {
"name": "Sem", "name": "Sem",
@@ -193,139 +259,7 @@
}, },
{ {
"kind": "person", "kind": "person",
"x": 0.86, "x": 0.75,
"y": 0.8,
"scale": 0.6,
"enterS": 0.9500000000000001,
"character": {
"name": "Jafé",
"look": {
"build": "slim",
"height": 1.08,
"skin": "#d4a074",
"hair": {
"style": "side",
"color": "#6b4226"
},
"beard": {
"style": "goatee",
"color": "#6b4226"
},
"glasses": "none",
"brows": "thin",
"top": {
"style": "robe",
"color": "#c8443a",
"accent": "#6b4a2a"
},
"bottom": {
"style": "pants",
"color": "#2c3346"
},
"shoes": "#6b4a2a",
"footwear": "sandals",
"nose": "round",
"lids": 0.1,
"wrinkles": 0,
"head": "round"
}
},
"expression": "neutral",
"pose": "arms_up",
"timeline": [
{
"do": "express",
"atP": 0.6699999999999999,
"expression": "happy"
},
{
"do": "look",
"dir": "up",
"atP": 0.48
},
{
"do": "pose",
"pose": "celebrate",
"atP": 0.62
},
{
"do": "bounce",
"times": 2,
"atP": 0.62
}
],
"framing": "full",
"flip": true
},
{
"kind": "person",
"x": 0.32,
"y": 0.8300000000000001,
"scale": 0.6,
"enterS": 0.35,
"character": {
"name": "Esposa de Noé",
"look": {
"build": "average",
"height": 0.92,
"skin": "#d09a70",
"hair": {
"style": "long",
"color": "#c9c9cf"
},
"beard": {
"style": "none",
"color": "#a9a9b0"
},
"glasses": "none",
"brows": "thick",
"top": {
"style": "robe",
"color": "#8a6f9e",
"accent": "#6b4a2a"
},
"bottom": {
"style": "pants",
"color": "#2c3346"
},
"shoes": "#6b4a2a",
"footwear": "sandals",
"nose": "button",
"lids": 0.3,
"wrinkles": 0.7,
"head": "round"
}
},
"expression": "neutral",
"pose": "arms_up",
"timeline": [
{
"do": "express",
"atP": 0.6699999999999999,
"expression": "happy"
},
{
"do": "look",
"dir": "up",
"atP": 0.48
},
{
"do": "pose",
"pose": "celebrate",
"atP": 0.62
},
{
"do": "bounce",
"times": 2,
"atP": 0.62
}
],
"framing": "full",
"flip": false
},
{
"kind": "person",
"x": 0.68,
"y": 0.8300000000000001, "y": 0.8300000000000001,
"scale": 0.6, "scale": 0.6,
"enterS": 0.7500000000000001, "enterS": 0.7500000000000001,
@@ -389,6 +323,72 @@
], ],
"framing": "full", "framing": "full",
"flip": true "flip": true
},
{
"kind": "person",
"x": 0.25,
"y": 0.8300000000000001,
"scale": 0.6,
"enterS": 0.9500000000000001,
"character": {
"name": "Jafé",
"look": {
"build": "slim",
"height": 1.08,
"skin": "#d4a074",
"hair": {
"style": "side",
"color": "#6b4226"
},
"beard": {
"style": "goatee",
"color": "#6b4226"
},
"glasses": "none",
"brows": "thin",
"top": {
"style": "robe",
"color": "#c8443a",
"accent": "#6b4a2a"
},
"bottom": {
"style": "pants",
"color": "#2c3346"
},
"shoes": "#6b4a2a",
"footwear": "sandals",
"nose": "round",
"lids": 0.1,
"wrinkles": 0,
"head": "round"
}
},
"expression": "neutral",
"pose": "arms_up",
"timeline": [
{
"do": "express",
"atP": 0.6699999999999999,
"expression": "happy"
},
{
"do": "look",
"dir": "up",
"atP": 0.48
},
{
"do": "pose",
"pose": "celebrate",
"atP": 0.62
},
{
"do": "bounce",
"times": 2,
"atP": 0.62
}
],
"framing": "full",
"flip": false
} }
], ],
"props": [], "props": [],
@@ -406,346 +406,299 @@
{ {
"text": "Depois", "text": "Depois",
"startS": 0, "startS": 0,
"endS": 0.52 "endS": 0.36
}, },
{ {
"text": "do", "text": "do",
"startS": 0.52, "startS": 0.36,
"endS": 0.7 "endS": 0.52
}, },
{ {
"text": "dilúvio,", "text": "dilúvio,",
"startS": 0.7, "startS": 0.52,
"endS": 1.18 "endS": 0.94
}, },
{ {
"text": "o", "text": "o",
"startS": 1.34, "startS": 1.1,
"endS": 1.56 "endS": 1.3
}, },
{ {
"text": "arco", "text": "arco",
"startS": 1.56, "startS": 1.3,
"endS": 1.82, "endS": 1.54,
"tone": "key" "tone": "key"
}, },
{ {
"text": "-íris", "text": "-íris",
"startS": 1.82, "startS": 1.54,
"endS": 2.04, "endS": 1.74,
"tone": "key" "tone": "key"
}, },
{ {
"text": "surge", "text": "surge",
"startS": 2.04, "startS": 1.74,
"endS": 2.4 "endS": 2.06
}, },
{ {
"text": "no", "text": "no",
"startS": 2.4, "startS": 2.06,
"endS": 2.56 "endS": 2.22
}, },
{ {
"text": "Gênesis", "text": "Gênesis",
"startS": 2.56, "startS": 2.22,
"endS": 2.98 "endS": 2.58
}, },
{ {
"text": "como", "text": "como",
"startS": 2.98, "startS": 2.58,
"endS": 3.16 "endS": 2.76
}, },
{ {
"text": "sinal", "text": "sinal",
"startS": 3.16, "startS": 2.76,
"endS": 3.5 "endS": 3.06
}, },
{ {
"text": "de", "text": "de",
"startS": 3.5, "startS": 3.06,
"endS": 3.62 "endS": 3.18
}, },
{ {
"text": "uma", "text": "uma",
"startS": 3.62, "startS": 3.18,
"endS": 3.78 "endS": 3.3
}, },
{ {
"text": "aliança.", "text": "aliança.",
"startS": 3.78, "startS": 3.3,
"endS": 4.2, "endS": 3.7,
"tone": "key" "tone": "key"
}, },
{ {
"text": "Nunca", "text": "Nunca",
"startS": 4.52, "startS": 3.98,
"endS": 4.88, "endS": 4.32,
"tone": "danger" "tone": "danger"
}, },
{ {
"text": "mais", "text": "mais",
"startS": 4.88, "startS": 4.32,
"endS": 5.18 "endS": 4.6
}, },
{ {
"text": "um", "text": "um",
"startS": 5.18, "startS": 4.6,
"endS": 5.32 "endS": 4.72
}, },
{ {
"text": "dilúvio", "text": "dilúvio",
"startS": 5.32, "startS": 4.72,
"endS": 5.8 "endS": 5.14
}, },
{ {
"text": "destruiria", "text": "destruiria",
"startS": 5.8, "startS": 5.14,
"endS": 6.38 "endS": 5.68
}, },
{ {
"text": "a", "text": "a",
"startS": 6.38, "startS": 5.68,
"endS": 6.5 "endS": 5.78
}, },
{ {
"text": "Terra.", "text": "Terra.",
"startS": 6.5, "startS": 5.78,
"endS": 6.7 "endS": 5.92
} }
], ],
"audioEnv": { "audioEnv": {
"fps": 30, "fps": 30,
"values": [ "values": [
0, 0,
0,
0,
0,
0,
0.26,
0.16,
0.76,
1,
1,
0.07,
0.01,
0.03,
0.64,
0.86,
0.77,
0.48,
0.16,
0.03,
0.65,
0.9,
0.27,
0.12,
0.36,
0.83,
0.62,
0.42,
0.74,
0.88,
0.91,
1,
0.37,
0.11,
0.12,
0.25, 0.25,
0.11, 0.14,
0.01,
0,
0,
0.01,
0.01,
0,
0,
0,
0.2,
0.73,
1, 1,
0.63, 1,
0.2, 0.53,
0.01,
0.02,
0.54,
0.82,
0.76,
0.45,
0.13, 0.13,
0.26,
0.87,
0.66,
0.15,
0.21,
0.74,
0.67,
0.43,
0.73,
0.91,
0.95,
0.8,
0.18,
0.07,
0.24,
0.14,
0.01,
0,
0.01,
0.01,
0.01,
0,
0,
0.09,
0.52,
1,
0.68,
0.26,
0.08,
0.01, 0.01,
0.08, 0.08,
0.32,
0.7,
0.67,
0.52,
0.47,
0.51,
0.22,
0.43,
0.52,
0.16,
0.11,
0.13,
0.09,
0.24,
0.91,
1,
0.74,
0.41,
0.19,
0.29,
0.65,
0.38,
0.5,
0.76,
0.76,
0.38,
0.13,
0.33,
0.8,
0.62,
0.46,
0.58,
0.44,
0.12,
0.27,
0.27,
0.14,
0.07,
0.03,
0.44,
0.69,
0.45,
0.61,
0.46,
0.06,
0.05,
0.34,
0.7,
0.55,
0.62,
0.77,
0.92,
0.87,
0.73,
0.24,
0.13,
0.5, 0.5,
0.72,
0.53, 0.53,
0.46, 0.46,
0.6, 0.48,
0.68, 0.26,
0.63, 0.41,
0.57, 0.52,
0.74, 0.12,
0.93, 0.13,
0.98,
0.69,
0.65,
0.56,
0.4,
0.1, 0.1,
0.01, 0.17,
0.81,
1,
0.88,
0.46,
0.18,
0.31,
0.56,
0.39,
0.64,
0.79,
0.51,
0.15,
0.24,
0.75,
0.66,
0.46,
0.55,
0.32,
0.13,
0.33,
0.14,
0.12,
0.03, 0.03,
0.43,
0.68,
0.45,
0.62,
0.33,
0.04,
0.06,
0.62,
0.6,
0.59,
0.69,
0.9,
0.87,
0.62,
0.15,
0.24,
0.59,
0.45,
0.54,
0.66,
0.61,
0.55,
0.73,
1,
0.84,
0.65,
0.6,
0.45,
0.2, 0.2,
0.02,
0.02,
0.19,
0.08, 0.08,
0.01, 0.01,
0, 0,
0,
0.01, 0.01,
0.01, 0.01,
0.01, 0.01,
0, 0,
0, 0,
0.31, 0.31,
0.53, 0.54,
0.67, 0.63,
0.74,
0.76,
0.69,
0.64,
0.34,
0.03,
0.29,
1,
1,
0.69,
0.42,
0.59,
0.85,
0.75, 0.75,
0.88, 0.73,
0.78,
0.58,
0.15,
0.35,
0.53,
0.59,
0.59,
0.28,
0.15,
0.49,
0.82,
0.57,
0.45,
0.8,
0.98,
1,
1,
0.29,
0.11,
0.47,
0.67,
0.24,
0.24,
0.66, 0.66,
0.39, 0.55,
0.14, 0.1,
0.06, 0.13,
0.05,
0.67,
0.7,
1, 1,
1, 1,
0.92, 0.64,
0.26, 0.44,
0.65, 0.55,
0.46, 0.75,
1, 0.85,
0.81,
0.74,
0.25,
0.23,
0.54,
0.59,
0.56,
0.17,
0.18,
0.78,
0.66,
0.44,
0.57,
0.96, 0.96,
0.9, 1,
0.12, 0.95,
0.01, 0.25,
0.2, 0.15,
0.84, 0.6,
0.51,
0.16,
0.51,
0.41,
0.15,
0.07,
0.04,
0.67,
0.94,
1,
0.95, 0.95,
0.69, 0.69,
0.55, 0.54,
0.22, 0.49,
0.98,
1,
0.89,
0.11,
0,
0.37,
0.97,
0.75,
0.6,
0.29,
0.15, 0.15,
0.15, 0.13,
0.08, 0.07,
0.02, 0.02,
0.01, 0.01
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] ]
} }
} }
+166 -209
View File
@@ -3,7 +3,7 @@
"width": 1080, "width": 1080,
"height": 1920, "height": 1920,
"fps": 30, "fps": 30,
"durationS": 6.902, "durationS": 5.344,
"seed": 113, "seed": 113,
"scene": { "scene": {
"kind": "place", "kind": "place",
@@ -156,64 +156,64 @@
{ {
"text": "Noé", "text": "Noé",
"startS": 0, "startS": 0,
"endS": 0.58 "endS": 0.4
}, },
{ {
"text": "tinha", "text": "tinha",
"startS": 0.58, "startS": 0.4,
"endS": 0.76 "endS": 0.58
}, },
{ {
"text": "600", "text": "600",
"startS": 0.76, "startS": 0.58,
"endS": 1.12, "endS": 0.96,
"tone": "key" "tone": "key"
}, },
{ {
"text": "anos", "text": "anos",
"startS": 1.12, "startS": 0.96,
"endS": 1.68, "endS": 1.42,
"tone": "key" "tone": "key"
}, },
{ {
"text": "no", "text": "no",
"startS": 1.68, "startS": 1.42,
"endS": 1.86 "endS": 1.58
}, },
{ {
"text": "dilúvio", "text": "dilúvio",
"startS": 1.86, "startS": 1.58,
"endS": 2.36 "endS": 2.02
}, },
{ {
"text": "e,", "text": "e,",
"startS": 2.36, "startS": 2.02,
"endS": 2.52 "endS": 2.14
}, },
{ {
"text": "segundo", "text": "segundo",
"startS": 2.72, "startS": 2.38,
"endS": 3.08 "endS": 2.7
}, },
{ {
"text": "Gênesis,", "text": "Gênesis,",
"startS": 3.08, "startS": 2.7,
"endS": 3.66 "endS": 3.22
}, },
{ {
"text": "morreu", "text": "morreu",
"startS": 3.92, "startS": 3.44,
"endS": 4.3 "endS": 3.8
}, },
{ {
"text": "aos", "text": "aos",
"startS": 4.3, "startS": 3.8,
"endS": 4.48 "endS": 3.96
}, },
{ {
"text": "950.", "text": "950.",
"startS": 4.48, "startS": 3.96,
"endS": 5.48, "endS": 4.74,
"tone": "key" "tone": "key"
} }
], ],
@@ -221,201 +221,158 @@
"fps": 30, "fps": 30,
"values": [ "values": [
0, 0,
0, 0.45,
0,
0,
0.03,
0.55,
0.67,
0.9,
1,
1,
0.78,
0.66,
0.71,
0.7,
0.53,
0.08,
0.06,
0.26,
0.25,
0.26,
0.56,
0.58,
0.66,
0.5,
0.06,
0.04,
0.53,
0.81,
0.57,
0.11,
0.02,
0.02,
0.05,
0.61,
0.67,
0.62,
0.47,
0.1,
0.08,
0.74,
0.62,
0.27,
0.06,
0.3,
0.84,
0.69,
0.67,
0.59,
0.51,
0.64,
0.59,
0.2,
0.05,
0.19,
0.71,
0.59,
0.12,
0.15,
0.68,
0.88,
0.58,
0.47,
1,
1,
1,
0.89,
0.32,
0.08,
0.28,
0.49,
0.44,
0.33,
0.18,
0.05,
0.01,
0,
0,
0.01,
0,
0,
0.01,
0.01,
0.02,
0.05,
0.74,
0.55,
0.23,
0.15,
0.44,
0.57,
0.63, 0.63,
0.47, 0.85,
0.61,
1, 1,
0.53, 1,
0.18, 0.69,
0.17, 0.64,
0.61, 0.66,
0.91, 0.55,
0.81, 0.24,
0.51,
0.47,
0.42,
0.33,
0.05, 0.05,
0.05, 0.22,
0.17,
0.06,
0.03,
0.03,
0.03,
0.01,
0,
0.01,
0.01,
0.01,
0,
0,
0.16,
0.46,
0.8,
1,
0.76,
0.65,
0.6,
0.76,
0.98,
1,
0.76,
1,
0.98,
1,
0.42,
0.11,
0.03,
0.49,
0.84,
0.81,
0.21, 0.21,
0.18, 0.39,
0.47,
0.18,
0.02,
0.02,
0.03,
0.58,
0.73,
0.59,
0.43,
0.09,
0.14,
0.51,
0.14,
0.15,
0.48,
0.32,
0.03,
0.04,
0.56, 0.56,
0.51,
0.62,
0.19,
0.03,
0.26,
0.76,
0.54,
0.07,
0.02,
0.02,
0.31,
0.7, 0.7,
0.41,
0.09,
0.35,
0.75,
0.57, 0.57,
0.49, 0.47,
0.09,
0.1,
0.72,
0.57,
0.16,
0.06,
0.58,
0.72,
0.62,
0.61,
0.44,
0.59,
0.56,
0.18,
0.04,
0.32, 0.32,
0.7,
0.29,
0.1,
0.42,
0.84,
0.55,
0.53,
1,
1,
1,
0.6,
0.1,
0.16,
0.43,
0.42,
0.31,
0.17,
0.03,
0,
0,
0.01,
0,
0,
0.01,
0.01,
0.02,
0.05,
0.7,
0.46,
0.19,
0.19,
0.49,
0.63,
0.44,
0.48,
0.93,
0.49,
0.15,
0.19,
0.72,
0.84,
0.61,
0.4,
0.42,
0.31,
0.06,
0.07,
0.15,
0.04,
0.03,
0.03,
0.01,
0,
0.01,
0.01,
0.01,
0,
0,
0.24,
0.5,
1,
1,
0.64,
0.55,
0.65,
0.87,
1,
0.71,
0.99,
0.92,
0.85,
0.15,
0.04,
0.3,
0.74,
0.79,
0.25,
0.23,
0.41,
0.07,
0.02,
0.02,
0.45,
0.74,
0.55,
0.45,
0.12,
0.26,
0.43,
0.13,
0.3,
0.45,
0.07,
0.02,
0.52,
0.65,
0.42,
0.08,
0.47,
0.71,
0.51,
0.36,
0.15,
0.01,
0.11,
0.1, 0.1,
0.02, 0.02,
0.14,
0.07,
0.01,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0 0
] ]
} }
+182 -228
View File
@@ -3,7 +3,7 @@
"width": 1080, "width": 1080,
"height": 1920, "height": 1920,
"fps": 30, "fps": 30,
"durationS": 8.03, "durationS": 6.351,
"seed": 120, "seed": 120,
"scene": { "scene": {
"kind": "place", "kind": "place",
@@ -90,338 +90,292 @@
{ {
"text": "Uma", "text": "Uma",
"startS": 0, "startS": 0,
"endS": 0.32 "endS": 0.18
}, },
{ {
"text": "história", "text": "história",
"startS": 0.32, "startS": 0.18,
"endS": 0.7 "endS": 0.52
}, },
{ {
"text": "antiga", "text": "antiga",
"startS": 0.7, "startS": 0.52,
"endS": 1.06 "endS": 0.86
}, },
{ {
"text": "lembra", "text": "lembra",
"startS": 1.06, "startS": 0.86,
"endS": 1.42 "endS": 1.18
}, },
{ {
"text": "essa.", "text": "essa.",
"startS": 1.42, "startS": 1.18,
"endS": 1.76 "endS": 1.48
}, },
{ {
"text": "Na", "text": "Na",
"startS": 1.94, "startS": 1.64,
"endS": 2.12 "endS": 1.82
}, },
{ {
"text": "epopeia", "text": "epopeia",
"startS": 2.12, "startS": 1.82,
"endS": 2.62, "endS": 2.26,
"tone": "key" "tone": "key"
}, },
{ {
"text": "de", "text": "de",
"startS": 2.62, "startS": 2.26,
"endS": 2.76 "endS": 2.42
}, },
{ {
"text": "Gilgami,", "text": "Gilgami,",
"startS": 2.76, "startS": 2.42,
"endS": 3.24 "endS": 2.84
}, },
{ {
"text": "o", "text": "o",
"startS": 3.54, "startS": 3.08,
"endS": 3.64 "endS": 3.18
}, },
{ {
"text": "Tnapishim", "text": "Tnapishim",
"startS": 3.64, "startS": 3.18,
"endS": 4.16 "endS": 3.66
}, },
{ {
"text": "sobrevive", "text": "sobrevive",
"startS": 4.16, "startS": 3.66,
"endS": 4.7 "endS": 4.16
}, },
{ {
"text": "a", "text": "a",
"startS": 4.7, "startS": 4.16,
"endS": 4.78 "endS": 4.24
}, },
{ {
"text": "um", "text": "um",
"startS": 4.78, "startS": 4.24,
"endS": 4.9 "endS": 4.34
}, },
{ {
"text": "dilúvio", "text": "dilúvio",
"startS": 4.9, "startS": 4.34,
"endS": 5.32 "endS": 4.72
}, },
{ {
"text": "num", "text": "num",
"startS": 5.32, "startS": 4.72,
"endS": 5.46 "endS": 4.86
}, },
{ {
"text": "barco", "text": "barco",
"startS": 5.46, "startS": 4.86,
"endS": 5.92 "endS": 5.26
}, },
{ {
"text": "e", "text": "e",
"startS": 5.92, "startS": 5.26,
"endS": 6.02 "endS": 5.36
}, },
{ {
"text": "solta", "text": "solta",
"startS": 6.02, "startS": 5.36,
"endS": 6.4 "endS": 5.68
}, },
{ {
"text": "aves.", "text": "aves.",
"startS": 6.4, "startS": 5.68,
"endS": 6.74 "endS": 6
} }
], ],
"audioEnv": { "audioEnv": {
"fps": 30, "fps": 30,
"values": [ "values": [
0, 0,
0, 0.52,
0, 0.72,
0, 0.64,
0, 0.68,
0.54, 0.79,
0.75, 0.37,
0.65,
0.65,
0.8,
0.61,
0.19,
0.16,
0.06,
0,
0.82,
1,
1,
1,
0.83,
0.66,
0.74,
0.44,
0.36,
0.25,
0.07,
0.15, 0.15,
0.18, 0.11,
0.87, 0.01,
0.46, 0.86,
0.12,
0.89,
1, 1,
1,
0.97,
0.65,
0.73, 0.73,
0.5,
0.61,
0.66,
0.67,
0.56, 0.56,
0.27, 0.33,
0.6, 0.3,
0.77, 0.07,
0.91, 0.16,
0.7, 0.21,
0.69, 0.89,
0.4,
0.57,
1,
0.88,
0.58,
0.56,
0.63,
0.66,
0.59,
0.26,
0.51,
0.86,
0.81,
0.74, 0.74,
0.68, 0.68,
0.49, 0.66,
0.17, 0.58,
0.15,
0.01, 0.01,
0.01, 0.01,
0.11,
0.07,
0.01,
0,
0,
0,
0,
0,
0,
0.18,
0.54,
0.71,
0.64,
0.04,
0.18,
0.99,
0.58,
0.03, 0.03,
0.15,
0.02,
0.01, 0.01,
0, 0.62,
0, 0.8,
0,
0,
0,
0,
0.15,
0.46,
0.67,
0.79,
0.2,
0.01,
0.38,
1,
0.36,
0.02,
0,
0.48,
0.81,
0.78, 0.78,
0.88, 0.89,
0.9, 0.8,
0.74, 0.77,
0.78, 0.47,
0.32,
0.14, 0.14,
0.21, 0.21,
0.29, 0.29,
0.16, 0.16,
0.14, 0.21,
0.5, 0.65,
0.86, 0.84,
0.69, 0.27,
0.18,
0.12,
0.77,
0.93,
0.74,
0.55,
0.41,
0.25,
0.19,
0.11,
0.04,
0.01,
0,
0,
0,
0.01,
0,
0,
0.35,
0.58,
0.09,
0.1, 0.1,
0.3, 0.57,
0.9,
0.69, 0.69,
0.76, 0.57,
0.28, 0.33,
0.01, 0.26,
0.18,
0.61,
0.32,
0.15, 0.15,
0.23, 0.06,
0.02,
0,
0,
0,
0.01,
0,
0,
0.46,
0.46,
0.06,
0.18,
0.55,
0.75,
0.43,
0.01,
0.29,
0.57,
0.27,
0.19, 0.19,
0.25, 0.21,
0.16,
0.47,
0.54, 0.54,
0.54, 0.42,
0.37,
0.06, 0.06,
0.07, 0.07,
0.57, 0.72,
1, 0.88,
0.17, 0.33,
0.59, 0.64,
0.7, 0.87,
0.9, 0.68,
0.37, 0.1,
0.07,
0.2,
0.69,
0.8,
0.7,
0.15,
0.38,
0.92,
0.53,
0.37,
0.43,
0.45,
0.12, 0.12,
0.25,
0.66, 0.66,
0.5, 0.79,
0.45, 0.68,
0.51, 0.12,
0.95, 0.62,
1, 0.75,
1, 0.4,
0.84, 0.41,
0.17, 0.48,
0.18,
0.21, 0.21,
0.64,
0.47,
0.4,
0.68,
1,
1,
1,
0.33,
0.15,
0.74, 0.74,
0.57, 0.59,
0.4,
0.42, 0.42,
0.41, 0.41,
0.39, 0.4,
0.42, 0.42,
0.42, 0.32,
0.42, 0.22,
0.18,
0.28,
1, 1,
1, 1,
0.71, 0.71,
0.73,
0.41,
0.18,
0.11,
0.01,
0.03,
0.38,
0.73,
0.64, 0.64,
0.08, 0.35,
0.07, 0.17,
0.07,
0.27,
1,
1,
0.84,
0.75,
0.06, 0.06,
0.04, 0.02,
0.8, 0.23,
0.99, 0.62,
0.77, 0.73,
0.7,
0.63,
0.46,
0.12, 0.12,
0.07,
0.05,
0.83,
1,
0.97,
0.81,
0.41,
0.03, 0.03,
0.14, 0.77,
0.19, 1,
0.06, 0.71,
0.71,
0.56,
0.34,
0.05,
0.08,
0.17,
0.07,
0.03, 0.03,
0.03, 0.03,
0.02, 0.02,
0.01, 0.01,
0, 0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0 0
] ]
} }
+274 -327
View File
@@ -3,7 +3,7 @@
"width": 1080, "width": 1080,
"height": 1920, "height": 1920,
"fps": 30, "fps": 30,
"durationS": 10.718, "durationS": 8.803,
"seed": 127, "seed": 127,
"scene": { "scene": {
"kind": "place", "kind": "place",
@@ -102,364 +102,338 @@
{ {
"text": "A", "text": "A",
"startS": 0, "startS": 0,
"endS": 0.32 "endS": 0.18
}, },
{ {
"text": "Tábua", "text": "Tábua",
"startS": 0.32, "startS": 0.18,
"endS": 0.66, "endS": 0.48,
"tone": "key" "tone": "key"
}, },
{ {
"text": "do", "text": "do",
"startS": 0.66, "startS": 0.48,
"endS": 0.78 "endS": 0.6
}, },
{ {
"text": "Dilúvio,", "text": "Dilúvio,",
"startS": 0.78, "startS": 0.6,
"endS": 1.28 "endS": 1.04
}, },
{ {
"text": "do", "text": "do",
"startS": 1.44, "startS": 1.16,
"endS": 1.7 "endS": 1.42
}, },
{ {
"text": "século", "text": "século",
"startS": 1.7, "startS": 1.42,
"endS": 2.1 "endS": 1.78
}, },
{ {
"text": "VII", "text": "VII",
"startS": 2.1, "startS": 1.78,
"endS": 2.46 "endS": 2.12
}, },
{ {
"text": "a", "text": "a",
"startS": 2.46, "startS": 2.12,
"endS": 2.72 "endS": 2.36
}, },
{ {
"text": ".C.,", "text": ".C.,",
"startS": 2.72, "startS": 2.36,
"endS": 3.6 "endS": 3.2
}, },
{ {
"text": "achada", "text": "achada",
"startS": 3.6, "startS": 3.2,
"endS": 4.18, "endS": 3.68,
"tone": "key" "tone": "key"
}, },
{ {
"text": "em", "text": "em",
"startS": 4.18, "startS": 3.68,
"endS": 4.3 "endS": 3.78
}, },
{ {
"text": "Nínive", "text": "Nínive",
"startS": 4.3, "startS": 3.78,
"endS": 4.6 "endS": 4.06
}, },
{ {
"text": "e", "text": "e",
"startS": 4.6, "startS": 4.06,
"endS": 4.72 "endS": 4.16
}, },
{ {
"text": "identificada", "text": "identificada",
"startS": 4.72, "startS": 4.16,
"endS": 5.36 "endS": 4.76
}, },
{ {
"text": "por", "text": "por",
"startS": 5.36, "startS": 4.76,
"endS": 5.58 "endS": 4.94
}, },
{ {
"text": "George", "text": "George",
"startS": 5.58, "startS": 4.94,
"endS": 5.82 "endS": 5.2
}, },
{ {
"text": "Smith", "text": "Smith",
"startS": 5.82, "startS": 5.2,
"endS": 6.3 "endS": 5.6
}, },
{ {
"text": "em", "text": "em",
"startS": 6.3, "startS": 5.6,
"endS": 6.46 "endS": 5.74
}, },
{ {
"text": "1872,", "text": "1872,",
"startS": 6.46, "startS": 5.74,
"endS": 7.8, "endS": 6.98,
"tone": "key" "tone": "key"
}, },
{ {
"text": "está", "text": "está",
"startS": 8.26, "startS": 7.38,
"endS": 8.48 "endS": 7.6
}, },
{ {
"text": "no", "text": "no",
"startS": 8.48, "startS": 7.6,
"endS": 8.62 "endS": 7.72
}, },
{ {
"text": "Museu", "text": "Museu",
"startS": 8.62, "startS": 7.72,
"endS": 8.94 "endS": 8.02
}, },
{ {
"text": "Britânico.", "text": "Britânico.",
"startS": 8.94, "startS": 8.02,
"endS": 9.5 "endS": 8.5
} }
], ],
"audioEnv": { "audioEnv": {
"fps": 30, "fps": 30,
"values": [ "values": [
0, 0,
0.9,
0.91,
0.39,
0.02,
0, 0,
0.48,
1,
0.9,
0.83,
0.38,
0.14,
0.86,
1,
0.69,
0.15,
0.53,
0.91,
0.5,
0.13,
0.35,
0.78,
0.53,
0.28,
0.86,
0.9,
0.98,
0.61,
0.12,
0.11,
0.17,
0.13,
0.01,
0,
0,
0,
0,
0,
0.02,
0.17,
0.53,
0.64,
0.44,
0.08,
0.05,
0.03,
0.27,
0.85,
0.7,
0.3,
0.02,
0.57,
0.51,
0.85,
0.37,
0.05,
0.03,
0.38,
1,
0.8,
0.55,
0.03,
0.13,
0.18,
0.18,
0.43,
0.71,
0.6,
0.58,
0.5,
0.22,
0.12,
0.27,
0.2,
0.12,
0.53,
0.38,
0.01,
0.09,
0.37,
0.73,
0.83,
0.67,
0.3,
0.1,
0.02,
0.02,
0.14,
0.07,
0.01,
0, 0,
0, 0,
0.01, 0.01,
0.95, 0.01,
0.97, 0.01,
0.51, 0.01,
0.03,
0, 0,
0.03, 0,
0.13,
0.78,
0.57,
0.23,
0.16,
0.21,
0.18,
0.95,
0.94,
0.78,
0.19,
0.31,
0.72,
0.77,
0.47,
0.49,
0.55,
0.66,
0.93,
0.51,
0.69,
0.59,
0.15,
0.44,
0.6,
0.86,
0.29,
0.61,
1,
0.72,
0.4,
0.11,
0.11,
0.08,
0.67,
0.33,
0.01,
0.06,
0.66,
1,
0.96,
0.98,
0.48,
0.21,
0.95,
0.29,
0.01,
0.16,
0.62,
0.49,
0.44,
0.18,
0.29,
0.94,
1,
1, 1,
1, 1,
0.91, 0.91,
0.83,
0.28,
0.15,
0.88,
1,
0.96,
0.19,
0.22,
0.83,
0.97,
0.26,
0.14,
0.39,
0.85,
0.56,
0.31,
0.74,
0.94,
0.98,
0.96,
0.36,
0.08,
0.12,
0.19,
0.14,
0.01,
0,
0,
0,
0,
0,
0,
0.12,
0.15,
0.57,
0.67,
0.5,
0.1,
0.05,
0.03,
0.04,
0.87,
0.76,
0.67,
0.16,
0.01,
0.37,
0.7,
0.82,
0.58,
0.11,
0.04,
0.03,
0.55,
0.98,
0.86,
0.54,
0.03,
0.16,
0.24,
0.2,
0.21,
0.7,
0.71,
0.58,
0.6,
0.49,
0.22,
0.15,
0.29,
0.24,
0.13,
0.29,
0.65,
0.09,
0.02,
0.22,
0.34,
0.79,
0.89,
0.69,
0.39,
0.11,
0.08,
0.01,
0.13,
0.17,
0.06,
0.01,
0,
0,
0.01,
0.01,
0.01,
0.01,
0,
0,
0,
0.24,
0.82,
0.6,
0.25,
0.18,
0.21,
0.17,
0.6,
1,
0.97,
0.56,
0.17,
0.4,
0.73,
0.81,
0.49,
0.52,
0.55,
0.6,
0.84,
0.86,
0.54,
0.74,
0.56,
0.16,
0.41,
0.55,
0.83,
0.63, 0.63,
0.13,
1,
0.83,
0.69,
0.25,
0.14,
0.09,
0.02,
0.61,
0.5,
0.04,
0.01,
0.16,
0.96,
1,
0.99,
1,
0.52,
0.22,
0.97,
0.52,
0.03,
0.01,
0.45,
0.72,
0.45,
0.39,
0.17,
0.3,
1,
1,
1,
1,
1,
0.73,
0.57,
0.31,
0.17,
0.47,
0.58,
0.2,
0.09,
0.18,
0.55,
0.67,
0.78,
0.62,
0.05,
0.13,
0.19,
0.43,
0.5,
0.59,
0.61,
0.76,
0.98,
0.71,
0.67,
1,
1,
0.31,
0.04,
0.19,
0.44,
0.14,
0.06,
0.03,
0.05,
0.56,
0.65,
0.57,
0.6,
0.27,
0.04,
0.38, 0.38,
0.36,
0.17,
0.12,
0.08,
0.02,
0.28,
0.55,
0.09,
0.15, 0.15,
0.57, 0.43,
0.35, 0.6,
0.06, 0.17,
0.75, 0.1,
0.69, 0.26,
0.2, 0.6,
0.24, 0.71,
0.79, 0.74,
0.79, 0.16,
0.65, 0.09,
0.12,
0.41,
0.49, 0.49,
0.05, 0.56,
0.64,
0.81,
0.89,
0.62,
1,
1,
0.4,
0.04,
0.21,
0.37,
0.08,
0.04, 0.04,
0.03, 0.03,
0.15,
0.63,
0.61,
0.56,
0.36,
0.09,
0.44,
0.3,
0.14,
0.08,
0.03,
0.05,
0.55,
0.19,
0.15,
0.54,
0.26,
0.24,
0.78,
0.53,
0.14,
0.67,
0.75,
0.65,
0.48,
0.09,
0.04,
0.02, 0.02,
0, 0,
0, 0,
@@ -469,67 +443,40 @@
0, 0,
0, 0,
0.17, 0.17,
0.47, 0.43,
0.23, 0.17,
0.06, 0.03,
0.01, 0.01,
0.11, 0.8,
0.97, 0.88,
0.84,
0.41,
0.53, 0.53,
0.55, 0.45,
0.36,
0.36,
0.83,
0.57,
0.24,
0.09,
0.52,
1,
1,
1,
0.2,
0.71,
0.67,
1,
0.09,
0.01,
0.29,
0.73,
0.74,
0.54, 0.54,
0.37, 0.35,
0.23, 0.41,
0.28, 0.82,
0.08, 0.47,
0.01, 0.14,
0.12, 0.2,
0.11, 1,
1,
1,
0.24,
0.71,
0.81,
0.92,
0.02, 0.02,
0, 0.05,
0, 0.57,
0, 0.74,
0, 0.51,
0, 0.41,
0, 0.25,
0, 0.25,
0, 0.05,
0, 0.06,
0, 0.11,
0, 0.03,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0, 0,
0 0
] ]
+177 -221
View File
@@ -3,7 +3,7 @@
"width": 1080, "width": 1080,
"height": 1920, "height": 1920,
"fps": 30, "fps": 30,
"durationS": 7.55, "durationS": 5.93,
"seed": 134, "seed": 134,
"scene": { "scene": {
"kind": "place", "kind": "place",
@@ -69,118 +69,215 @@
{ {
"text": "No", "text": "No",
"startS": 0, "startS": 0,
"endS": 0.32 "endS": 0.18
}, },
{ {
"text": "século", "text": "século",
"startS": 0.32, "startS": 0.18,
"endS": 0.78 "endS": 0.6
}, },
{ {
"text": "XX,", "text": "XX,",
"startS": 0.78, "startS": 0.6,
"endS": 1.12 "endS": 0.9
}, },
{ {
"text": "expedições", "text": "expedições",
"startS": 1.54, "startS": 1.28,
"endS": 2.1 "endS": 1.8
}, },
{ {
"text": "procuraram", "text": "procuraram",
"startS": 2.1, "startS": 1.8,
"endS": 2.68 "endS": 2.32
}, },
{ {
"text": "a", "text": "a",
"startS": 2.68, "startS": 2.32,
"endS": 2.8 "endS": 2.44
}, },
{ {
"text": "arca", "text": "arca",
"startS": 2.8, "startS": 2.44,
"endS": 3.12 "endS": 2.72
}, },
{ {
"text": "no", "text": "no",
"startS": 3.12, "startS": 2.72,
"endS": 3.24 "endS": 2.84
}, },
{ {
"text": "Monte", "text": "Monte",
"startS": 3.24, "startS": 2.84,
"endS": 3.48 "endS": 3.06
}, },
{ {
"text": "Arara,", "text": "Arara,",
"startS": 3.48, "startS": 3.06,
"endS": 3.88 "endS": 3.42
}, },
{ {
"text": "sem", "text": "sem",
"startS": 4.06, "startS": 3.58,
"endS": 4.38 "endS": 3.86
}, },
{ {
"text": "sucesso,", "text": "sucesso,",
"startS": 4.38, "startS": 3.86,
"endS": 4.96 "endS": 4.4
}, },
{ {
"text": "segundo", "text": "segundo",
"startS": 5.26, "startS": 4.66,
"endS": 5.68 "endS": 5.04
}, },
{ {
"text": "a", "text": "a",
"startS": 5.68, "startS": 5.04,
"endS": 5.84 "endS": 5.18
}, },
{ {
"text": "Britannica.", "text": "Britannica.",
"startS": 5.84, "startS": 5.18,
"endS": 6.32 "endS": 5.62
} }
], ],
"audioEnv": { "audioEnv": {
"fps": 30, "fps": 30,
"values": [ "values": [
0, 0,
0, 0.34,
0,
0,
0.06,
0.41,
0.58, 0.58,
0.83, 0.8,
0.85, 0.84,
0.39, 0.29,
0.06, 0.05,
0.04,
0.03, 0.03,
0.32,
1,
1,
0.77,
0.08,
0.01,
0.35,
1,
0.7,
0.86,
0.89,
0.56,
0.13,
0.09, 0.09,
0.56, 1,
1,
0.81,
0.12,
0.01,
0.61,
1,
0.69,
0.9,
0.79,
0.18,
0.05,
0.44,
0.68, 0.68,
0.62, 0.61,
0.66, 0.66,
0.47, 0.39,
0.07, 0.07,
0.13, 0.11,
0.06,
0.01,
0,
0,
0,
0,
0,
0,
0.18,
0.05,
0.04,
0.04,
0.05,
0.73,
0.66,
0.21,
0.18,
0.61,
0.4,
0.1,
0.09,
0.09,
0.57,
0.59,
0.57,
0.37,
0.14,
0.07, 0.07,
0.05, 0.05,
0.83,
0.73,
0.08,
0.06,
0.55,
0.98,
0.57,
1,
1,
1,
0.54,
0.68,
0.49,
0.65,
0.78,
0.76,
0.76,
0.85,
0.95,
0.5,
0.23,
0.09,
0.01,
0.45,
0.68,
0.3,
0.62,
0.53,
0.44,
0.47,
0.62,
0.7,
0.57,
0.26,
0.11,
0.69,
1,
0.79,
0.73,
0.94,
0.88,
0.87,
0.64,
0.34,
0.45,
0.27,
0.08,
0.02,
0,
0,
0,
0,
0.01,
0.01,
0.01,
0.04,
0.6,
0.52,
0.5,
0.4,
0.05,
0.07,
0.67,
0.56,
0.07,
0.03,
0.03,
0.49,
0.98,
1,
0.81,
0.4,
0.04,
0.04,
0.06,
0.13,
0.01, 0.01,
0, 0,
0, 0,
@@ -188,177 +285,36 @@
0, 0,
0, 0,
0, 0,
0.14, 0.01,
0.11, 0.01,
0.04,
0.07,
0.02, 0.02,
0.18, 0.43,
0.78, 0.69,
0.6, 0.36,
0.21, 0.16,
0.17,
0.5,
0.59,
0.11,
0.08,
0.07,
0.1,
0.61,
0.61,
0.56,
0.35,
0.12,
0.08,
0,
0.28,
1,
0.42,
0.03,
0.07,
0.58,
0.97,
0.63,
1,
1,
1,
0.68,
0.75,
0.56,
0.49,
0.77,
0.79,
0.76,
0.74,
0.86,
0.92,
0.77,
0.29, 0.29,
0.15, 0.7,
0.07, 0.68,
0.08, 0.64,
0.6, 0.47,
0.63, 1,
0.3, 0.77,
0.63, 0.17,
0.52,
0.71,
1,
0.05,
0.47,
0.81,
0.53,
0.51,
0.56, 0.56,
0.47, 0.47,
0.41, 0.18,
0.63,
0.74,
0.6,
0.53,
0.12,
0.13,
0.51,
1,
0.95,
0.57,
0.99,
0.89,
0.85,
0.9,
0.52,
0.41,
0.46,
0.28,
0.07,
0.02,
0,
0,
0,
0,
0,
0.01, 0.01,
0.01,
0.01,
0.03,
0.55,
0.53,
0.51,
0.49,
0.11, 0.11,
0.07, 0.21,
0.1,
0.74,
0.52,
0.06,
0.03, 0.03,
0.03,
0.13,
0.88,
1,
0.95,
0.66,
0.19,
0.03,
0.04,
0.08,
0.12,
0.01,
0,
0,
0,
0,
0,
0,
0,
0.01,
0.01,
0.02,
0.36,
0.72,
0.44,
0.17,
0.19,
0.49,
0.73,
0.72,
0.54,
0.42,
1,
0.83,
0.19,
0.38,
0.46,
1,
0.29,
0.03,
0.72,
0.79,
0.52,
0.5,
0.58,
0.52,
0.28,
0.01,
0.09,
0.19,
0.15,
0.01,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0, 0,
0 0
] ]
+234 -296
View File
@@ -3,7 +3,7 @@
"width": 1080, "width": 1080,
"height": 1920, "height": 1920,
"fps": 30, "fps": 30,
"durationS": 9.926, "durationS": 7.712,
"seed": 141, "seed": 141,
"scene": { "scene": {
"kind": "place", "kind": "place",
@@ -75,99 +75,99 @@
{ {
"text": "Em", "text": "Em",
"startS": 0, "startS": 0,
"endS": 0.3 "endS": 0.18
}, },
{ {
"text": "Durupinar,", "text": "Durupinar,",
"startS": 0.3, "startS": 0.18,
"endS": 0.84 "endS": 0.66
}, },
{ {
"text": "perto", "text": "perto",
"startS": 1.14, "startS": 0.9,
"endS": 1.42 "endS": 1.18
}, },
{ {
"text": "do", "text": "do",
"startS": 1.42, "startS": 1.18,
"endS": 1.6 "endS": 1.34
}, },
{ {
"text": "Arara,", "text": "Arara,",
"startS": 1.6, "startS": 1.34,
"endS": 1.96 "endS": 1.68
}, },
{ {
"text": "uma", "text": "uma",
"startS": 2.26, "startS": 1.94,
"endS": 2.52 "endS": 2.18
}, },
{ {
"text": "formação", "text": "formação",
"startS": 2.52, "startS": 2.18,
"endS": 3.1 "endS": 2.7
}, },
{ {
"text": "lembra", "text": "lembra",
"startS": 3.1, "startS": 2.7,
"endS": 3.48 "endS": 3.06
}, },
{ {
"text": "um", "text": "um",
"startS": 3.48, "startS": 3.06,
"endS": 3.6 "endS": 3.14
}, },
{ {
"text": "barco.", "text": "barco.",
"startS": 3.6, "startS": 3.14,
"endS": 3.98 "endS": 3.52
}, },
{ {
"text": "Um", "text": "Um",
"startS": 4.4, "startS": 3.7,
"endS": 5.02 "endS": 4.1
}, },
{ {
"text": "estudo", "text": "estudo",
"startS": 5.02, "startS": 4.1,
"endS": 5.46 "endS": 4.48
}, },
{ {
"text": "de", "text": "de",
"startS": 5.46, "startS": 4.48,
"endS": 5.6 "endS": 4.62
}, },
{ {
"text": "1996", "text": "1996",
"startS": 5.6, "startS": 4.62,
"endS": 6.9, "endS": 5.8,
"tone": "key" "tone": "key"
}, },
{ {
"text": "a", "text": "a",
"startS": 6.9, "startS": 5.8,
"endS": 7.2 "endS": 6.08
}, },
{ {
"text": "descreve", "text": "descreve",
"startS": 7.2, "startS": 6.08,
"endS": 7.62 "endS": 6.46
}, },
{ {
"text": "como", "text": "como",
"startS": 7.62, "startS": 6.46,
"endS": 7.86 "endS": 6.68
}, },
{ {
"text": "rocha", "text": "rocha",
"startS": 7.86, "startS": 6.68,
"endS": 8.22, "endS": 7,
"tone": "key" "tone": "key"
}, },
{ {
"text": "natural.", "text": "natural.",
"startS": 8.22, "startS": 7,
"endS": 8.58, "endS": 7.32,
"tone": "key" "tone": "key"
} }
], ],
@@ -175,291 +175,229 @@
"fps": 30, "fps": 30,
"values": [ "values": [
0, 0,
0, 0.56,
0,
0,
0,
0.5,
0.8, 0.8,
0.73, 0.71,
0.67,
0.27,
0.43,
0.72,
0.66,
0.6,
0.7,
0.11,
0.02,
0.64,
0.72,
0.62, 0.62,
0.75, 0.22,
0.58,
0.77,
0.44,
0.77,
0.21,
0.02,
0.63,
0.69,
0.67,
0.76,
0.8, 0.8,
0.79, 0.8,
0.75, 0.61,
0.57, 0.25,
0.18, 0.06,
0.05, 0.02,
0.03,
0.01, 0.01,
0, 0,
0, 0,
0, 0,
0, 0,
0, 0,
0, 0.06,
0.48, 0.86,
1, 0.81,
0.79,
0.64, 0.64,
0.2,
0.14,
0.02,
0.05,
0.54,
0.23, 0.23,
0.33, 0.13,
1, 0.01,
1, 0.22,
1, 0.34,
1, 0.2,
0.97,
0.82, 0.82,
0.85, 1,
1,
1,
0.95,
0.88, 0.88,
0.83, 0.83,
0.77, 0.82,
0.52,
0.46,
0.53,
0.37,
0.17,
0.08,
0.01,
0,
0,
0,
0,
0,
0,
0,
0.19,
0.95,
0.53,
0.56,
0.86,
0.74,
0.23,
0.03,
0.03,
0.79,
0.92,
0.61,
0.53,
0.52,
0.97,
0.98,
0.48,
0.06,
0.03,
0.03,
0.06,
0.98,
0.75,
0.76,
0.64,
0.52,
0.46,
0.7,
0.68,
0.68,
0.55,
0.44,
0.56,
0.61,
0.64,
0.64,
0.56,
0.46,
0.18,
0.76,
0.89,
0.81,
0.56,
0.27,
0.1,
0.04,
0,
0.06,
0.16,
0.03,
0.01,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0.55,
0.73,
0.85, 0.85,
0.63,
0.32,
0.53,
0.4,
0.17,
0.07,
0.01,
0,
0,
0,
0,
0,
0,
0.06,
0.87, 0.87,
0.53,
0.55,
0.89,
0.61,
0.06,
0.02,
0.43,
1,
0.61,
0.52,
0.51,
1,
0.93,
0.27,
0.04,
0.02,
0.04,
0.85, 0.85,
0.31, 0.79,
0.13, 0.74,
0.17, 0.65,
0.51,
0.52,
0.69,
0.71,
0.62,
0.5,
0.4,
0.67,
0.61,
0.61,
0.6,
0.37,
0.16,
0.94,
0.86,
0.65,
0.39,
0.11,
0.05, 0.05,
0, 0,
0.2, 0.05,
0.71,
0.74,
0.64,
0.3,
0.27,
0.88,
0.38,
0.13, 0.13,
0.3,
0.49,
0.43,
0.74,
0.74,
0.8,
0.86,
0.67,
1,
1,
0.51,
0.16,
0.53,
0.33,
0.03,
0.02, 0.02,
0.03, 0.01,
0.72, 0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0.38,
0.65, 0.65,
0.66,
0.41,
0.03,
0.08,
0.17,
0.19,
0.36,
0.38,
0.67,
0.81,
0.62,
0.09,
0.56,
0.7,
0.62,
0.19,
0.13,
0.81,
0.58,
0.07,
0.02,
0.03,
0.69,
0.98,
0.77,
0.38,
0.1,
0.38,
1,
0.69,
0.13,
0.24,
0.16,
0.07,
0.07,
0.03,
0.39,
0.66,
1,
1,
1,
0.21,
0.25,
0.71,
0.21,
0.02,
0.61,
1,
0.46,
0.55,
0.91,
0.52,
0.28,
0.47,
1,
1,
1,
0.66,
0.14,
0.16,
0.34,
0.74,
0.63,
0.88,
0.95,
0.45,
0.02,
0.04,
0.79, 0.79,
0.63,
0.86, 0.86,
0.9,
0.87, 0.87,
0.69, 0.36,
0.12,
0.1,
0.01,
0.01,
0.52,
0.72,
0.71,
0.37,
0.27,
0.86,
0.43,
0.13,
0.4,
0.36,
0.58,
0.77,
0.76,
0.83,
0.63,
1,
1,
0.3,
0.24, 0.24,
0.54,
0.12,
0.02,
0.03,
0.59,
0.69,
0.62,
0.32,
0.03,
0.12,
0.16,
0.29,
0.3,
0.6,
0.8,
0.59,
0.16,
0.65,
0.68,
0.52,
0.06,
0.49,
0.75,
0.16,
0.02,
0.03,
0.64,
0.94,
0.71,
0.26,
0.1,
0.79,
1,
0.2,
0.23,
0.18,
0.05,
0.07, 0.07,
0, 0.04,
0, 0.61,
0, 0.6,
0, 1,
0, 1,
0, 0.67,
0, 0.15,
0, 0.68,
0, 0.2,
0, 0.05,
0, 0.81,
0, 0.99,
0, 0.44,
0, 0.79,
0, 0.73,
0, 0.3,
0, 0.38,
0, 1,
0, 1,
0, 0.97,
0, 0.53,
0, 0.17,
0, 0.14,
0, 0.63,
0, 0.63,
0.76,
0.94,
0.5,
0.02,
0.15,
0.78,
0.49,
0.94,
0.93,
0.83,
0.37,
0.07,
0.01,
0 0
] ]
} }
+271 -360
View File
@@ -3,7 +3,7 @@
"width": 1080, "width": 1080,
"height": 1920, "height": 1920,
"fps": 30, "fps": 30,
"durationS": 12.612, "durationS": 9.63,
"seed": 148, "seed": 148,
"scene": { "scene": {
"kind": "place", "kind": "place",
@@ -129,449 +129,275 @@
{ {
"text": "Qual", "text": "Qual",
"startS": 0, "startS": 0,
"endS": 0.34, "endS": 0.16,
"tone": "key" "tone": "key"
}, },
{ {
"text": "você", "text": "você",
"startS": 0.34, "startS": 0.16,
"endS": 0.66, "endS": 0.46,
"tone": "key" "tone": "key"
}, },
{ {
"text": "não", "text": "não",
"startS": 0.66, "startS": 0.46,
"endS": 0.84 "endS": 0.62
}, },
{ {
"text": "conhecia?", "text": "conhecia?",
"startS": 0.84, "startS": 0.62,
"endS": 1.5, "endS": 1.2,
"tone": "key" "tone": "key"
}, },
{ {
"text": "Grupos", "text": "Grupos",
"startS": 2.22, "startS": 1.56,
"endS": 2.86 "endS": 2.12
}, },
{ {
"text": "ainda", "text": "ainda",
"startS": 2.86, "startS": 2.12,
"endS": 3.1 "endS": 2.34
}, },
{ {
"text": "pesquisam", "text": "pesquisam",
"startS": 3.1, "startS": 2.34,
"endS": 3.66 "endS": 2.84
}, },
{ {
"text": "o", "text": "o",
"startS": 3.66, "startS": 2.84,
"endS": 3.76 "endS": 2.96
}, },
{ {
"text": "local,", "text": "local,",
"startS": 3.76, "startS": 2.96,
"endS": 4.08 "endS": 3.24
}, },
{ {
"text": "mas", "text": "mas",
"startS": 4.32, "startS": 3.46,
"endS": 4.62 "endS": 3.72
}, },
{ {
"text": "não", "text": "não",
"startS": 4.62, "startS": 3.72,
"endS": 4.78 "endS": 3.88
}, },
{ {
"text": "há", "text": "há",
"startS": 4.78, "startS": 3.88,
"endS": 4.94 "endS": 4.02
}, },
{ {
"text": "comprovação", "text": "comprovação",
"startS": 4.94, "startS": 4.02,
"endS": 5.58 "endS": 4.6
}, },
{ {
"text": "aceita.", "text": "aceita.",
"startS": 5.58, "startS": 4.6,
"endS": 6.08 "endS": 5.04
}, },
{ {
"text": "Qual", "text": "Qual",
"startS": 6.58, "startS": 5.34,
"endS": 7.16, "endS": 5.68,
"tone": "key" "tone": "key"
}, },
{ {
"text": "curiosidade", "text": "curiosidade",
"startS": 7.16, "startS": 5.68,
"endS": 7.8 "endS": 6.26
}, },
{ {
"text": "você", "text": "você",
"startS": 7.8, "startS": 6.26,
"endS": 8.1, "endS": 6.54,
"tone": "key" "tone": "key"
}, },
{ {
"text": "não", "text": "não",
"startS": 8.1, "startS": 6.54,
"endS": 8.3 "endS": 6.7
}, },
{ {
"text": "conhecia?", "text": "conhecia?",
"startS": 8.3, "startS": 6.7,
"endS": 8.9, "endS": 7.26,
"tone": "key" "tone": "key"
}, },
{ {
"text": "Comente", "text": "Comente",
"startS": 9.74, "startS": 7.68,
"endS": 10.38 "endS": 8.24
}, },
{ {
"text": "e", "text": "e",
"startS": 10.38, "startS": 8.24,
"endS": 10.58 "endS": 8.42
}, },
{ {
"text": "siga!", "text": "siga.",
"startS": 10.58, "startS": 8.42,
"endS": 10.84 "endS": 8.64
} }
], ],
"audioEnv": { "audioEnv": {
"fps": 30, "fps": 30,
"values": [ "values": [
0,
0,
0,
0,
0,
0.03,
0.03,
0.95,
1,
0.97,
0.77,
0.35,
0.11,
0.53,
1,
0.58,
0.04,
0.03,
0.06,
1,
0.7,
0.47,
0.54,
0.84,
0.78,
0.78,
0.5,
0.12,
0.1,
0.7,
1,
0.77,
0.6,
0.61,
0.4,
0.05,
0.02, 0.02,
0.03, 0.03,
0.06,
0.33,
0.45,
0.44,
0.46,
0.4,
0.21,
0.05,
0.02,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0.01,
0.25,
0.12,
0.57,
0.51,
0.79,
0.97,
0.89,
0.27,
0.01,
0.03,
0.54,
0.52,
0.17,
0.47,
0.89,
0.55,
0.42,
0.51,
0.57,
0.7,
1,
0.11,
0.01,
0.52,
0.7,
0.38,
0.04,
0.05,
0.01,
0.02,
0.41,
1,
0.76,
0.13,
0.55,
0.66,
0.53,
0.61,
0.62,
0.97,
1,
0.97,
0.25,
0.01,
0.12,
0.6,
1,
0.93,
0.82,
0.69,
0.39,
0.1,
0.01,
0,
0,
0,
0,
0,
0,
0.12,
0.43,
0.83,
0.74,
0.56,
0.29,
0.11,
0.12,
0.43,
0.88,
0.68,
0.52,
0.56,
0.79,
0.79,
0.62,
0.12,
0.01,
0.07,
0.62,
0.47,
0.18,
0.27,
0.55,
0.74,
0.17,
0.52,
1,
0.57,
0.13,
0.02,
0.02,
0.03,
0.71,
0.73,
0.56,
0.62,
0.74,
0.46,
0.06,
0.02,
0.02,
0.05,
0.73,
0.83,
0.58,
0.26,
0.01,
0.05,
0.13,
0.05,
0.01,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0.04,
0.75,
1,
1,
0.56,
0.09,
0,
0.07,
0.61,
0.54,
1,
1,
0.74,
0.16,
0.29,
0.64,
0.17,
0.35,
1,
1,
1,
0.86,
0.69,
0.17,
0.2,
0.48,
0.21,
0.24,
0.9,
0.7,
0.09,
0.02,
0.04,
0.83,
0.51,
0.42,
0.65,
0.73,
0.65,
0.3,
0.09,
0.36,
0.87,
1,
0.67,
0.58,
0.54,
0.16,
0.03,
0.02,
0.05,
0.18,
0.47,
0.44,
0.43,
0.4,
0.21,
0.06,
0.03,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0.09,
0.91, 0.91,
1, 1,
0.79, 0.93,
0.49, 0.67,
0.48, 0.23,
0.64, 0.21,
0.68, 1,
0.72, 0.96,
0.77, 0.07,
0.64, 0.03,
0.06,
1,
0.58, 0.58,
0.3, 0.48,
0.73,
0.77,
0.77,
0.58,
0.23,
0.1, 0.1,
0.78,
1,
0.75,
0.58,
0.55,
0.23,
0.02,
0.02,
0.05,
0.28,
0.47,
0.41,
0.49,
0.35,
0.11,
0.04,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0.23,
0.12,
0.58,
0.49,
0.81,
0.96,
0.68,
0.04,
0.01,
0.42,
0.52,
0.18,
0.63,
0.79,
0.53,
0.43,
0.55,
0.46,
1,
0.43,
0.01,
0.47,
0.69,
0.28,
0.04,
0.05,
0.01,
0.07,
0.86,
0.99,
0.17, 0.17,
0.42, 0.42,
0.76, 0.67,
0.49,
0.64,
0.62,
1,
1,
0.47,
0.04,
0.11,
0.51,
1,
0.88,
0.8,
0.58,
0.15, 0.15,
0.03, 0.03,
0.02, 0,
0.03, 0,
0.29, 0,
0.79, 0,
0,
0.01,
0.23,
0.66,
0.82,
0.65,
0.43,
0.14,
0.11,
0.41,
0.88,
0.66,
0.5,
0.64,
0.84,
0.72, 0.72,
0.17, 0.32,
0.06, 0.01,
0.36, 0.05,
0.36, 0.59,
0.1, 0.43,
0.16,
0.34,
0.71,
0.41,
0.22,
1,
0.75,
0.16,
0.02, 0.02,
0.02,
0.15,
0.82,
0.66,
0.54,
0.66,
0.62,
0.12,
0.02,
0.02,
0.07,
0.75,
0.78,
0.45,
0.05,
0.02,
0.12,
0.08,
0.01, 0.01,
0, 0,
0, 0,
@@ -586,6 +412,60 @@
0, 0,
0, 0,
0, 0,
0.07,
0.94,
1,
0.82,
0.3,
0,
0.06,
0.57,
0.55,
1,
1,
0.4,
0.16,
0.58,
0.35,
0.24,
0.87,
1,
1,
0.82,
0.56,
0.12,
0.43,
0.34,
0.18,
0.82,
0.82,
0.1,
0.02,
0.27,
0.81,
0.44,
0.49,
0.7,
0.69,
0.35,
0.09,
0.34,
0.93,
0.95,
0.61,
0.63,
0.32,
0.05,
0.02,
0.03,
0.26,
0.48,
0.43,
0.42,
0.34,
0.11,
0.04,
0.01,
0, 0,
0, 0,
0, 0,
@@ -596,7 +476,38 @@
0, 0,
0, 0,
0, 0,
0 0,
0,
0,
0.09,
0.83,
1,
0.71,
0.5,
0.52,
0.66,
0.69,
0.78,
0.66,
0.57,
0.3,
0.11,
0.15,
0.64,
0.56,
0.07,
0.02,
0.03,
0.14,
0.7,
0.66,
0.17,
0.09,
0.42,
0.27,
0.03,
0.01,
0.01
] ]
} }
} }
File diff suppressed because it is too large Load Diff