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>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
54eac7cebf
commit
377536f778
+17
-2
@@ -148,11 +148,22 @@ def output_words(project: dict) -> list[Word]:
|
||||
if p.start <= mid <= p.end:
|
||||
s = p.out + max(w["s"], p.start) - 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
|
||||
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]]:
|
||||
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}],
|
||||
"captions": {
|
||||
"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,
|
||||
"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
|
||||
e = round(s + 0.05, 3)
|
||||
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"):
|
||||
item["emph"] = True
|
||||
if w.get("hidden"):
|
||||
|
||||
+11
-13
@@ -21,7 +21,7 @@ from fastapi import FastAPI, Request
|
||||
from fastapi.responses import JSONResponse
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from . import editor, editor_render, layout, media
|
||||
from . import editor, editor_render, layout, media, speakers
|
||||
from .config import REPO_ROOT
|
||||
from .db import loads, now
|
||||
from .judge import JudgeError, _chat_block, _transcript
|
||||
@@ -151,9 +151,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)."""
|
||||
judge = _judge(clip)
|
||||
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",
|
||||
clip["session_id"], lo, hi)
|
||||
words = [Word(a, b, c) for r in rows for a, b, c in loads(r["words_json"], [])]
|
||||
words = engine.words_between(clip["session_id"], lo, hi) # já com quem fala cada palavra (FALANTES.md)
|
||||
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"],
|
||||
engine.intel.settings_for(session), model=judge.get("model") or "", generated_at=now())
|
||||
@@ -240,9 +238,7 @@ def register(app: FastAPI, engine, clip_view, get_clip) -> None:
|
||||
return round(lo, 3), round(hi, 3)
|
||||
|
||||
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",
|
||||
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]
|
||||
return [w for w in engine.words_between(session_id, lo, hi) if lo <= w.start <= hi]
|
||||
|
||||
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"
|
||||
@@ -282,7 +278,7 @@ def register(app: FastAPI, engine, clip_view, get_clip) -> None:
|
||||
"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,
|
||||
"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,
|
||||
"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],
|
||||
@@ -333,8 +329,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)
|
||||
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)
|
||||
return _cached_proxy(clip, lo, hi) | {"words": [{"s": w.start, "e": w.end, "w": w.word}
|
||||
for w in _words(clip["session_id"], lo, hi)]}
|
||||
return _cached_proxy(clip, lo, hi) | {"words": [editor.word_item(w) for w in _words(clip["session_id"], lo, hi)]}
|
||||
|
||||
@app.get("/v1/clips/{clip_id}/waveform")
|
||||
def get_waveform(clip_id: int, lo: float, hi: float):
|
||||
@@ -420,8 +415,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]}")
|
||||
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
|
||||
# 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),
|
||||
"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")
|
||||
def tts(clip_id: int, body: TtsIn):
|
||||
@@ -464,12 +462,12 @@ def register(app: FastAPI, engine, clip_view, get_clip) -> None:
|
||||
project = validate_for(engine, clip, session, data)
|
||||
lo, hi = project["source"]["lo"], project["source"]["hi"]
|
||||
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)
|
||||
analysis = (view["judge"] or {}).get("analysis") if isinstance(view["judge"], dict) else None
|
||||
cfg = editor.effective_settings(engine.intel.settings_for(session), project)
|
||||
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()
|
||||
try:
|
||||
raw = engine.judge.ask(editor.SUGGEST_SYSTEM, prompt, editor.SUGGEST_SCHEMA, [])
|
||||
|
||||
@@ -16,7 +16,9 @@ from pathlib import Path
|
||||
from . import layout, media, reframe
|
||||
from .editor import Piece, effective_settings, emphasized, output_duration, output_words, pieces, slice_pieces, to_output
|
||||
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)
|
||||
|
||||
W, H = layout.W, layout.H # quadro do vertical (padrão dos parâmetros); o formato real vem da configuração
|
||||
FPS = 30
|
||||
@@ -79,10 +81,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,
|
||||
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)].
|
||||
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
|
||||
out = []
|
||||
for o in project["overlays"]:
|
||||
@@ -94,10 +98,11 @@ def hook_dodges(project: dict, canvas: tuple[int, int], cap_y: int, cap_size: in
|
||||
else:
|
||||
cy, half = int(ch * o["y"]), int(o["size"] * 0.9)
|
||||
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
|
||||
below = bottom + cap_size + 12
|
||||
y = below if below + cap_size <= ch else max(cap_size, top - cap_size - 12)
|
||||
under = bottom + 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))
|
||||
return out
|
||||
|
||||
@@ -220,6 +225,17 @@ def build_project_ass(project: dict, cfg: dict, credit: str, t0: float = 0.0, t1
|
||||
tsize = max(30, int(size * 0.5))
|
||||
trans_style = (f"Style: Trans,Arial,{tsize},&H00FFE79B,&H00FFE79B,&H00000000,&H80000000,-1,0,0,0,100,100,0,0,1,"
|
||||
f"{max(3, ow // 2)},2,8,60,60,0,1\n") if 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]
|
||||
ScriptType: v4.00+
|
||||
PlayResX: {cw}
|
||||
@@ -231,7 +247,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
|
||||
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: 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: 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
|
||||
@@ -255,35 +271,61 @@ Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text
|
||||
emph = emphasized(project)
|
||||
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"])
|
||||
pos = f"\\pos({cw // 2},{layout.caption_y(cfg)})"
|
||||
dodges = hook_dodges(project, (cw, ch), layout.caption_y(cfg), int(cap["size"]), total)
|
||||
oth_c = layout.ass_inline_color(other_color(cap))
|
||||
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:
|
||||
"""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:
|
||||
if s <= t < e:
|
||||
return y
|
||||
return layout.caption_y(cfg)
|
||||
return cap_y
|
||||
|
||||
def at(t: float) -> str:
|
||||
"""Posição da legenda no instante t (saída)."""
|
||||
def oy_at(t: float) -> int:
|
||||
"""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)
|
||||
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
|
||||
# ORIGINAIS. Depois as palavras são saneadas (ordem, sem sobreposição, duração mínima) — `clean_words` devolve
|
||||
# a mesma quantidade, na mesma ordem — e os blocos abaixo nunca ficam dois na tela ao mesmo tempo.
|
||||
raw = sorted((w for w in output_words(project) if w.word.strip()), key=lambda w: (w.start, w.end))
|
||||
# ORIGINAIS. Depois as palavras são saneadas POR FAIXA (ordem, sem sobreposição, duração mínima) —
|
||||
# `clean_words` devolve a mesma quantidade, na mesma ordem — e os blocos de uma faixa nunca ficam dois na
|
||||
# tela ao mesmo tempo (as duas faixas, sim: cada uma na sua linha).
|
||||
raw = spoken
|
||||
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:
|
||||
return _escape(w.word.upper() if cap["uppercase"] else w.word)
|
||||
|
||||
def key(w: Word) -> tuple[float, str]:
|
||||
return round(w.start, 3), w.word # depois de clean_words, cada início é único
|
||||
def key(w: Word) -> tuple[float, str, str]:
|
||||
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}
|
||||
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":
|
||||
parts, cursor = [], group[0].start
|
||||
for w in group:
|
||||
@@ -292,40 +334,46 @@ Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text
|
||||
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)}")
|
||||
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
|
||||
style = "CaptionOther" if other else "Caption"
|
||||
for i, word in enumerate(group):
|
||||
start = word.start
|
||||
end = group[i + 1].start if i + 1 < len(group) else g_end
|
||||
if end <= start:
|
||||
continue
|
||||
if preset == "single":
|
||||
color = emph_c if key(word) in emph_keys else (hi_c if len(group) > 1 else base_c)
|
||||
event(0, start, end, "Caption", f"{{{at(start)}{_anim('pop')}\\c{color}}}{txt(word)}")
|
||||
color = emph_c if key(word) in emph_keys else (hi_c if len(group) > 1 else base_g)
|
||||
event(0, start, end, style, f"{{{at(start, other)}{_anim('pop')}\\c{color}}}{txt(word)}")
|
||||
continue
|
||||
parts = []
|
||||
for j, w in enumerate(group):
|
||||
is_emph = key(w) in emph_keys
|
||||
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:
|
||||
color = emph_c if is_emph else hi_c
|
||||
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:
|
||||
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 ""
|
||||
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,
|
||||
# logo embaixo da legenda em inglês (\\an8 = cresce para baixo; \\q0 = quebra a linha se for longa).
|
||||
for line in translation:
|
||||
# logo embaixo da legenda de QUEM FALA (`speaker` da linha; sem ele, o streamer) — \\an8 = cresce para
|
||||
# baixo; \\q0 = quebra a linha se for longa.
|
||||
for line in translation or []:
|
||||
a, _ = to_output(float(line["s"]), project["cuts"])
|
||||
b, _ = to_output(float(line["e"]), project["cuts"])
|
||||
if b - a < 0.2 or not str(line.get("pt") or "").strip():
|
||||
continue
|
||||
y = y_at(a) + int(size * 0.62)
|
||||
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']))}")
|
||||
|
||||
cuts = project["cuts"]
|
||||
|
||||
+88
-3
@@ -213,6 +213,61 @@ class MediaPipeTracker:
|
||||
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:
|
||||
"""Plano B (OpenSeeFace, só os .onnx no onnxruntime): presença e posição do rosto, SEM blendshapes.
|
||||
|
||||
@@ -449,8 +504,12 @@ class FaceService:
|
||||
detector_factory: Callable[[], Detector] | None = None,
|
||||
reader: Callable[..., Iterator[tuple[float, 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
|
||||
# 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")
|
||||
# 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
|
||||
@@ -592,12 +651,21 @@ class FaceService:
|
||||
started = time.perf_counter()
|
||||
tracker = self._tracker_factory(self.session_backend(sid)) # FaceUnavailable sobe: não marca o bloco
|
||||
self.backend = tracker.name
|
||||
mouth = self._mouth_meter()
|
||||
mouth_values: list[float | None] = []
|
||||
try:
|
||||
file = REPO_ROOT / segment["file"]
|
||||
crop = expand(cam)
|
||||
px, out = crop_geometry(crop, self._frame_size(sid, file))
|
||||
samples = [tracker.process(segment["start_s"] + t, rgb)
|
||||
for t, rgb in self._reader(self.e.settings.ffmpeg or "ffmpeg", file, px, out)]
|
||||
samples = []
|
||||
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:
|
||||
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
|
||||
@@ -616,10 +684,27 @@ class FaceService:
|
||||
data = {"cam": cam, "crop": crop, "fps": FPS, "backend": tracker.name, "frames": len(samples),
|
||||
"ms": int((time.perf_counter() - started) * 1000), "coords": "frame",
|
||||
"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.last_error = None
|
||||
self._after_block(sid, idx)
|
||||
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]:
|
||||
key = str(file)
|
||||
if key not in self._sizes:
|
||||
|
||||
+33
-9
@@ -660,16 +660,40 @@ def _game_context_en(game: str, screen_game: str, profile: dict | None, live_tit
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def _transcript(words: list[Word], lo: float, hi: float, lang: str = "pt") -> str:
|
||||
lines, current, current_t = [], [], None
|
||||
for word in sorted((w for w in words if lo <= w.start <= hi), key=lambda w: w.start):
|
||||
if current_t is None or word.start - current_t > 4 or len(current) >= 14:
|
||||
SPEAKER_NOTE = {
|
||||
"pt": "Quem fala vem marcado: [{s}] = o streamer; [other1], [other2]… = OUTRA pessoa (colega no Discord, outro "
|
||||
"jogador no chat de voz do jogo). Nunca atribua a {s} o que outra pessoa disse.",
|
||||
"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:
|
||||
lines.append(f"[{current_t:.0f}s] {' '.join(current)}")
|
||||
current, current_t = [], word.start
|
||||
flush()
|
||||
current, current_t, current_sp = [], word.start, sp
|
||||
current.append(word.word)
|
||||
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"]
|
||||
|
||||
|
||||
@@ -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['face']}: {face}\n" if face else "")
|
||||
+ f"{_frames_block(frames or [], lang)}\n\n"
|
||||
f"{L['transcript']}:\n{_transcript(words, lo, hi, lang)}\n\n"
|
||||
f"{L['transcript']}:\n{_transcript(words, lo, hi, lang, streamer)}\n\n"
|
||||
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['duration']}: {min_s:.0f} {to} {max_s:.0f} s. {L['done']}: {done}\n"
|
||||
f"{_frames_block(frames, lang)}\n\n"
|
||||
f"{L['transcript']}:\n{_transcript(words, back_lo, hi, lang)}\n\n"
|
||||
f"{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)}"
|
||||
)
|
||||
|
||||
|
||||
@@ -91,6 +91,9 @@ DEFAULTS: dict = {
|
||||
"caption": {
|
||||
"enabled": True, "font": "Arial Black", "size": 84, "color": "#FFFFFF", "highlight": "#FFE500",
|
||||
"outline": "#000000", "outlineWidth": 7, "y": None, "uppercase": True, "maxWords": 3,
|
||||
# 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).
|
||||
"translation": False,
|
||||
},
|
||||
@@ -171,7 +174,7 @@ def validate(settings: dict) -> dict:
|
||||
cap = settings.get("caption")
|
||||
if cap is not None:
|
||||
o = {}
|
||||
for key in ("color", "highlight", "outline"):
|
||||
for key in ("color", "highlight", "outline", "otherColor"):
|
||||
if key in cap:
|
||||
if not HEX_RE.match(str(cap[key])):
|
||||
raise LayoutError(f"caption.{key} precisa ser cor #RRGGBB")
|
||||
@@ -185,6 +188,10 @@ def validate(settings: dict) -> dict:
|
||||
o[key] = int(cap[key])
|
||||
if not lo <= o[key] <= 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:
|
||||
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:
|
||||
|
||||
@@ -391,6 +391,8 @@ def create_app(settings: Settings | None = None, engine: Engine | None = None, s
|
||||
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.
|
||||
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)
|
||||
out = settings.clips_dir / str(row["id"]) / "preview.jpg"
|
||||
try:
|
||||
@@ -419,6 +421,13 @@ def create_app(settings: Settings | None = None, engine: Engine | None = None, s
|
||||
raise UserError("`to` precisa ser maior que `from`.")
|
||||
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")
|
||||
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
|
||||
|
||||
@@ -90,6 +90,9 @@ class Word:
|
||||
start: float
|
||||
end: float
|
||||
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
|
||||
|
||||
@@ -0,0 +1,508 @@
|
||||
"""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)
|
||||
|
||||
TABLE_SQL = """
|
||||
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)
|
||||
)
|
||||
"""
|
||||
|
||||
|
||||
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
|
||||
with engine.db.lock:
|
||||
engine.db.conn.execute(TABLE_SQL)
|
||||
|
||||
@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
@@ -15,12 +15,23 @@ ativos ao mesmo tempo. Agora (usado pelo render do worker e pelo do editor):
|
||||
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
|
||||
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 . import layout
|
||||
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
|
||||
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))
|
||||
if out and out[-1].end > start + 1e-9:
|
||||
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()
|
||||
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
|
||||
|
||||
|
||||
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]]:
|
||||
"""Blocos da legenda (palavras já saneadas por `clean_words`)."""
|
||||
max_chars = MAX_CHARS + 6 * max(0, max_words - MAX_WORDS)
|
||||
groups: list[list[Word]] = []
|
||||
for word in clean_words(words):
|
||||
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
|
||||
room = len(current) < max_words or (
|
||||
# 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]]:
|
||||
"""(palavras do bloco, fim do bloco). O fim nunca passa do início do bloco seguinte: dois eventos de legenda
|
||||
ativos ao mesmo tempo seriam empilhados pelo libass (um em cima do outro)."""
|
||||
groups = group_words(words, max_words)
|
||||
"""(palavras do bloco, fim do bloco), em ordem de início. Cada faixa (streamer / outra pessoa; ver `lane`) é
|
||||
agrupada sozinha e um bloco nunca mistura falantes. O fim nunca passa do início do bloco seguinte DA MESMA FAIXA:
|
||||
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 = []
|
||||
for k, group in enumerate(groups):
|
||||
end = max(group[-1].end, group[-1].start + MIN_HOLD_S)
|
||||
if k + 1 < len(groups):
|
||||
end = min(end, groups[k + 1][0].start)
|
||||
out.append((group, round(end, 3)))
|
||||
for name in (STREAMER_LANE, OTHER_LANE):
|
||||
groups = group_words([w for w in words if lane(w.speaker) == name], max_words)
|
||||
for k, group in enumerate(groups):
|
||||
end = max(group[-1].end, group[-1].start + MIN_HOLD_S)
|
||||
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
|
||||
|
||||
|
||||
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
|
||||
_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
|
||||
(. ? !) com 4+ palavras, 16 palavras ou 6 s. A tradução de uma frase inteira sai melhor que a de blocos de 3."""
|
||||
out: list[tuple[float, float, str]] = []
|
||||
current: list[Word] = []
|
||||
for w in clean_words(words):
|
||||
if current and (w.start - current[-1].end > PHRASE_GAP_S or w.end - current[0].start > PHRASE_MAX_S
|
||||
or len(current) >= PHRASE_MAX_WORDS
|
||||
or (current[-1].word.endswith(_SENTENCE_END) and len(current) >= 4)):
|
||||
out.append((current[0].start, current[-1].end, " ".join(x.word for x in current)))
|
||||
current = []
|
||||
current.append(w)
|
||||
if current:
|
||||
out.append((current[0].start, current[-1].end, " ".join(x.word for x in current)))
|
||||
(. ? !) com 4+ palavras, 16 palavras ou 6 s. A tradução de uma frase inteira sai melhor que a de blocos de 3.
|
||||
Uma frase nunca mistura falantes (quem fala junto vira frase própria). `with_speaker` = devolve
|
||||
(início, fim, texto, falante), com falante "streamer" ou "otherN"."""
|
||||
out: list[tuple] = []
|
||||
|
||||
def flush(current: list[Word]) -> None:
|
||||
item = (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)
|
||||
|
||||
by_speaker: dict[str, list[Word]] = {}
|
||||
for w in words:
|
||||
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
|
||||
|
||||
|
||||
@@ -123,13 +186,19 @@ def build_ass(words: list[Word], clip_start: float, clip_end: float, credit: str
|
||||
cap, cred = cfg["caption"], cfg["credit"]
|
||||
duration = clip_end - clip_start
|
||||
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
|
||||
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"])
|
||||
credit_align, credit_side, credit_margin = layout.credit_placement(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]
|
||||
ScriptType: v4.00+
|
||||
PlayResX: {width}
|
||||
@@ -140,7 +209,7 @@ ScaledBorderAndShadow: yes
|
||||
[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
|
||||
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]
|
||||
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"]:
|
||||
lines.append(f"Dialogue: 1,{_ts(0)},{_ts(duration)},Credit,,0,0,0,,{_escape(credit)}")
|
||||
if cap["enabled"]:
|
||||
pos = f"{{\\pos({width // 2},{layout.caption_y(cfg)})}}"
|
||||
high, base = layout.ass_inline_color(cap["highlight"]), layout.ass_inline_color(cap["color"])
|
||||
y = layout.caption_y(cfg)
|
||||
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"]):
|
||||
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):
|
||||
# Cada palavra tem seu tempo na tela; o bloco inteiro aparece com a palavra atual destacada.
|
||||
start = word.start
|
||||
@@ -163,5 +240,5 @@ Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text
|
||||
for j, w in enumerate(group):
|
||||
text = _escape(w.word.upper() if cap["uppercase"] else w.word)
|
||||
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"
|
||||
|
||||
@@ -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
|
||||
+28
-9
@@ -40,6 +40,7 @@ from .intel import Intel
|
||||
from .judge import Judge, JudgeError, analysis_block, build_prompt
|
||||
from .scoring import ChatMessage, Params, Word, find_moments, overlaps
|
||||
from .sources import Source, parse_source
|
||||
from .speakers import SpeakerService, dump_words, parse_words
|
||||
from .subtitles import build_ass, phrases
|
||||
|
||||
log = logging.getLogger("cenaforge_clipper")
|
||||
@@ -353,6 +354,7 @@ class Engine:
|
||||
self._threads: list[threading.Thread] = []
|
||||
self.intel = Intel(self)
|
||||
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._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
|
||||
@@ -754,12 +756,18 @@ class Engine:
|
||||
for w in rel_words]
|
||||
except Exception as exc: # noqa: BLE001 - sem voz o corte segue pelo chat
|
||||
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:
|
||||
error = f"áudio: {exc}"[:300]
|
||||
self.db.run(
|
||||
"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,
|
||||
segment["session_id"], segment["idx"])
|
||||
json.dumps(loudness), dump_words(words), error, segment["session_id"], segment["idx"])
|
||||
|
||||
# ---------- linha do tempo de uma sessão
|
||||
def load_timeline(self, session_id: int, since_s: float = 0.0) -> dict:
|
||||
@@ -775,7 +783,7 @@ class Engine:
|
||||
if seg["analyzed"]:
|
||||
if analyzed_until >= seg["start_s"] - 0.01: # só o trecho contínuo desde o início conta
|
||||
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 = []
|
||||
if segments:
|
||||
first_wall = segments[0]["wall_end"] - (segments[0]["end_s"] - segments[0]["start_s"])
|
||||
@@ -789,9 +797,17 @@ class Engine:
|
||||
continue
|
||||
emotes = tuple(loads(r["emotes"], []))
|
||||
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,
|
||||
"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
|
||||
def _clip_loop(self) -> None:
|
||||
while not self.stop_event.is_set():
|
||||
@@ -816,7 +832,7 @@ class Engine:
|
||||
return 0
|
||||
offset = int(since)
|
||||
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
|
||||
# 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"]
|
||||
@@ -980,20 +996,23 @@ class Engine:
|
||||
hi = clip["end_s"] if hi is None else hi
|
||||
current = loads(clip.get("translation_json"), None)
|
||||
if (isinstance(current, dict) and not force and current.get("startS", 1e12) <= lo + 0.5
|
||||
and current.get("endS", -1) >= hi - 0.5):
|
||||
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
|
||||
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:
|
||||
return None
|
||||
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:
|
||||
log.warning("tradução da fala do corte %s falhou: %s", clip_id, exc)
|
||||
return None
|
||||
data = {"language": "pt-BR", "startS": round(lo, 2), "endS": round(hi, 2), "model": self.judge.responder(),
|
||||
"lines": [{"s": round(s, 3), "e": round(e, 3), "text": text, "pt": tr}
|
||||
for (s, e, text), tr in zip(items, pt)]}
|
||||
"lines": [{"s": round(s, 3), "e": round(e, 3), "text": text, "pt": tr, "speaker": speaker}
|
||||
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)
|
||||
return data
|
||||
|
||||
|
||||
@@ -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",
|
||||
"models": [
|
||||
{
|
||||
@@ -41,6 +41,16 @@
|
||||
"size": 568302,
|
||||
"license": "BSD-2-Clause",
|
||||
"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)"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -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
|
||||
Reference in New Issue
Block a user