CenaForge: primeira versão pública
Gerador de vídeos narrativos (Godot + FFmpeg), painel Next.js, serviço de voz, Clipador de lives e Publicador para YouTube, TikTok e Instagram. Inclui a leitura das visualizações dos posts para o Dashboard e o botão "Publicar no <rede>" nos cartões das publicações. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,264 @@
|
||||
"""Qualidade de gravação (`capture.quality`), escolha do stream no Streamlink, resolução gravada de fato, busca
|
||||
exata de quadro em .ts (H.264 e HEVC) e render que atravessa blocos de resolução/codec diferentes."""
|
||||
|
||||
import json
|
||||
import shutil
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from app import capture, editor, editor_render, layout, media
|
||||
from app.db import loads
|
||||
from app.scoring import Word
|
||||
|
||||
from .test_sources_and_api import KEY, env, seed_session # noqa: F401 - fixture reaproveitada
|
||||
|
||||
FFMPEG = shutil.which("ffmpeg")
|
||||
FFPROBE = shutil.which("ffprobe")
|
||||
needs_ffmpeg = pytest.mark.skipif(not (FFMPEG and FFPROBE), reason="FFmpeg não instalado")
|
||||
|
||||
|
||||
def auth():
|
||||
return {"X-Service-Key": KEY}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- configuração (camadas e validação)
|
||||
def test_capture_defaults_to_best_and_layers_field_by_field():
|
||||
assert layout.merge()["capture"] == {"quality": "best"}
|
||||
assert layout.merge({"capture": {"quality": "720p"}})["capture"]["quality"] == "720p"
|
||||
# canal 720p, sessão 1080p: a sessão vence
|
||||
assert layout.merge({"capture": {"quality": "720p"}}, {"capture": {"quality": "1080p"}})["capture"]["quality"] == "1080p"
|
||||
# configuração antiga (sem o grupo) segue o padrão
|
||||
assert layout.merge({"layout": {"mode": "blur"}})["capture"]["quality"] == "best"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("quality", ["best", "1440p", "1080p", "720p", "480p"])
|
||||
def test_capture_validate_accepts_each_quality(quality):
|
||||
assert layout.validate({"capture": {"quality": quality}}) == {"capture": {"quality": quality}}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("bad", [{"capture": {"quality": "4k"}}, {"capture": {"quality": "720p60"}},
|
||||
{"capture": "best"}, {"capture": {"quality": None}}])
|
||||
def test_capture_validate_rejects_unknown(bad):
|
||||
with pytest.raises(layout.LayoutError):
|
||||
layout.validate(bad)
|
||||
|
||||
|
||||
def test_capture_options_match_the_contract():
|
||||
assert [o["id"] for o in capture.OPTIONS] == list(capture.QUALITIES) == list(layout.CAPTURE_QUALITIES)
|
||||
for option in capture.OPTIONS:
|
||||
assert option["label"] and option["hint"] and option["gbPerHour"] > 0
|
||||
assert option["maxHeight"] == capture.CEILING_HEIGHT.get(option["id"])
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- argumentos do Streamlink
|
||||
@pytest.mark.parametrize("platform", ["twitch", "kick", "youtube"])
|
||||
@pytest.mark.parametrize("quality", ["best", "1440p", "1080p", "720p", "480p"])
|
||||
def test_stream_choice_per_option_and_platform(platform, quality):
|
||||
choice = capture.stream_choice(quality, platform)
|
||||
opts = list(choice.options)
|
||||
hevc = platform == "twitch" and quality in ("best", "1440p")
|
||||
assert ("--twitch-supported-codecs" in opts) == hevc
|
||||
if hevc:
|
||||
assert opts[opts.index("--twitch-supported-codecs") + 1] == "h264,h265" # sem av1: sem libdav1d no FFmpeg
|
||||
if quality == "best":
|
||||
assert choice.streams == "best" and "--stream-sorting-excludes" not in opts
|
||||
else:
|
||||
assert opts[opts.index("--stream-sorting-excludes") + 1] == f">{quality}60"
|
||||
assert choice.streams == "best,worst-unfiltered" # reserva: nunca falha por causa do teto
|
||||
url = "https://www.twitch.tv/x"
|
||||
assert choice.args(url)[-2:] == [url, choice.streams]
|
||||
|
||||
|
||||
def test_unknown_quality_falls_back_to_best():
|
||||
assert capture.stream_choice("4k", "kick") == capture.stream_choice("best", "kick")
|
||||
|
||||
|
||||
# Nomes medidos com `streamlink --json` (17/11/2026). O 2K da Twitch não estava no ar: lista do mesmo formato.
|
||||
TWITCH = ["audio_only", "160p30", "360p30", "480p30", "720p60", "1080p60"]
|
||||
TWITCH_PORTRAIT = TWITCH + ["284p30_portrait", "640p30_portrait", "852p30_portrait", "1280p60_portrait", "1920p60_portrait"]
|
||||
TWITCH_936 = ["audio_only", "160p30", "360p30", "480p30", "720p60", "936p60"]
|
||||
TWITCH_30 = ["audio_only", "160p30", "360p30", "480p30", "720p30", "1080p"]
|
||||
TWITCH_2K = ["audio_only", "160p30", "360p30", "480p30", "720p60", "1080p60", "1440p60"]
|
||||
KICK = ["160p", "360p", "480p", "720p60", "1080p60"]
|
||||
YOUTUBE = ["144p", "240p", "360p", "480p", "720p", "1080p"]
|
||||
YOUTUBE_60 = ["144p", "240p", "360p", "480p", "720p60", "1080p60"]
|
||||
|
||||
|
||||
def _pick(names: list[str], choice: capture.StreamChoice) -> str | None:
|
||||
"""Mesma escolha da CLI (1º nome da lista que existir), com o `Plugin.streams` de verdade do Streamlink."""
|
||||
from streamlink import Streamlink
|
||||
from streamlink.plugin import Plugin
|
||||
from streamlink.stream.http import HTTPStream
|
||||
|
||||
class Fake(Plugin):
|
||||
def _get_streams(self):
|
||||
return {n: HTTPStream(self.session, f"https://e.invalid/{n}") for n in names}
|
||||
|
||||
opts = list(choice.options)
|
||||
excludes = opts[opts.index("--stream-sorting-excludes") + 1].split(",") if "--stream-sorting-excludes" in opts else None
|
||||
streams = Fake(Streamlink(), "https://e.invalid/").streams(sorting_excludes=excludes)
|
||||
name = next((n for n in choice.streams.split(",") if n in streams), None)
|
||||
return streams[name].url.rsplit("/", 1)[1] if name else None
|
||||
|
||||
|
||||
@pytest.mark.parametrize("names,platform,expected", [
|
||||
(TWITCH, "twitch", {"best": "1080p60", "1440p": "1080p60", "1080p": "1080p60", "720p": "720p60", "480p": "480p30"}),
|
||||
(TWITCH_PORTRAIT, "twitch", {"best": "1080p60", "1440p": "1080p60", "1080p": "1080p60", "720p": "720p60", "480p": "480p30"}),
|
||||
(TWITCH_936, "twitch", {"best": "936p60", "1440p": "936p60", "1080p": "936p60", "720p": "720p60", "480p": "480p30"}),
|
||||
(TWITCH_30, "twitch", {"best": "1080p", "1440p": "1080p", "1080p": "1080p", "720p": "720p30", "480p": "480p30"}),
|
||||
(TWITCH_2K, "twitch", {"best": "1440p60", "1440p": "1440p60", "1080p": "1080p60", "720p": "720p60", "480p": "480p30"}),
|
||||
(KICK, "kick", {"best": "1080p60", "1440p": "1080p60", "1080p": "1080p60", "720p": "720p60", "480p": "480p"}),
|
||||
(YOUTUBE, "youtube", {"best": "1080p", "1440p": "1080p", "1080p": "1080p", "720p": "720p", "480p": "480p"}),
|
||||
(YOUTUBE_60, "youtube", {"best": "1080p60", "1440p": "1080p60", "1080p": "1080p60", "720p": "720p60", "480p": "480p"}),
|
||||
])
|
||||
def test_preference_picks_largest_under_the_ceiling(names, platform, expected):
|
||||
"""Medido nas lives reais com os mesmos argumentos (skipnho, kagura0mea, hpduketv, hotrodd, westcol): mesmo
|
||||
resultado. Variantes verticais (`*_portrait`) e `audio_only` nunca são escolhidas."""
|
||||
assert {q: _pick(names, capture.stream_choice(q, platform)) for q in capture.QUALITIES} == expected
|
||||
|
||||
|
||||
def test_ceiling_with_nothing_below_takes_the_closest_above():
|
||||
assert _pick(["audio_only", "1080p60"], capture.stream_choice("480p", "twitch")) == "1080p60"
|
||||
assert _pick(["720p60", "1080p60"], capture.stream_choice("480p", "kick")) == "720p60"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- resolução gravada de fato
|
||||
def _make_ts(path: Path, size: str, seconds: float, codec: str = "libx264", rate: int = 60, lum: str | None = None) -> Path:
|
||||
"""Bloco .ts sintético com GOP de 2 s (como a Twitch). `lum` = expressão do brilho no tempo (geq)."""
|
||||
src = f"color=c=gray:s={size}:r={rate}:d={seconds}" + (f",geq=lum='{lum}':cb=128:cr=128" if lum else "")
|
||||
codec_args = ["-c:v", codec, "-g", str(2 * rate), "-bf", "0"]
|
||||
if codec == "libx265":
|
||||
codec_args += ["-x265-params", f"keyint={2 * rate}:min-keyint={2 * rate}:open-gop=0:bframes=0:log-level=error"]
|
||||
subprocess.run([FFMPEG, "-y", "-v", "error", "-f", "lavfi", "-i", src, "-f", "lavfi", "-i",
|
||||
f"sine=frequency=440:sample_rate=48000:duration={seconds}", *codec_args, "-pix_fmt", "yuv420p",
|
||||
"-c:a", "aac", "-shortest", "-f", "mpegts", str(path)], check=True, capture_output=True)
|
||||
return path
|
||||
|
||||
|
||||
@needs_ffmpeg
|
||||
def test_probe_block_reads_resolution_fps_codec(tmp_path):
|
||||
info = capture.probe_block(FFPROBE, _make_ts(tmp_path / "a.ts", "320x180", 2))
|
||||
assert (info["width"], info["height"], info["fps"], info["codec"]) == (320, 180, 60, "h264")
|
||||
assert info["kbps"] and info["gbPerHour"] > 0
|
||||
|
||||
|
||||
def test_record_run_keeps_runs_and_flags_mixed_resolution():
|
||||
p1 = {"width": 1920, "height": 1080, "fps": 60, "codec": "h264", "kbps": 8000, "gbPerHour": 3.6}
|
||||
first = capture.record_run(None, "best", 0, p1, "t1")
|
||||
assert first["width"] == 1920 and first["quality"] == "best" and first["mixed"] is False and len(first["runs"]) == 1
|
||||
same = capture.record_run(first, "best", 40, p1, "t2")
|
||||
assert same["mixed"] is False and [r["fromIdx"] for r in same["runs"]] == [0, 40]
|
||||
p2 = {**p1, "width": 1280, "height": 720}
|
||||
mixed = capture.record_run(same, "720p", 80, p2, "t3")
|
||||
assert mixed["height"] == 720 and mixed["fromIdx"] == 80 and mixed["mixed"] is True
|
||||
assert capture.label(mixed) == "1280×720 · 60 qps"
|
||||
|
||||
|
||||
@needs_ffmpeg
|
||||
def test_capture_records_real_resolution_on_first_block(env, tmp_path, monkeypatch): # noqa: F811
|
||||
from dataclasses import replace
|
||||
|
||||
from app.sources import parse_source
|
||||
from app.worker import Capture
|
||||
|
||||
client, engine = env
|
||||
sid = seed_session(engine, duration=60)
|
||||
engine.db.run("DELETE FROM segments WHERE session_id = ?", sid)
|
||||
engine.settings = replace(engine.settings, ffprobe=FFPROBE)
|
||||
work = tmp_path / "cap"
|
||||
work.mkdir()
|
||||
_make_ts(work / "seg_00000.ts", "640x360", 2)
|
||||
(work / "segments.csv").write_text("seg_00000.ts,0.000000,2.000000\n", encoding="utf-8")
|
||||
cap = Capture(engine, sid, parse_source("https://www.twitch.tv/alanzoka"), work)
|
||||
cap.quality = "1440p"
|
||||
import app.worker as worker_module
|
||||
monkeypatch.setattr(worker_module, "rel", lambda path: path.as_posix()) # bloco fora do repositório (tmp)
|
||||
assert cap._collect(work / "segments.csv", 0) == 1
|
||||
info = loads(engine.db.get("SELECT capture_json FROM sessions WHERE id = ?", sid)["capture_json"], None)
|
||||
assert (info["quality"], info["width"], info["height"], info["fps"], info["fromIdx"]) == ("1440p", 640, 360, 60, 0)
|
||||
view = client.get(f"/v1/sessions/{sid}", headers=auth()).json()
|
||||
assert view["capture"]["width"] == 640 and view["capture"]["mixed"] is False
|
||||
|
||||
|
||||
def test_session_without_capture_info_reports_none(env): # noqa: F811
|
||||
client, engine = env
|
||||
sid = seed_session(engine, duration=60)
|
||||
assert client.get(f"/v1/sessions/{sid}", headers=auth()).json()["capture"] is None
|
||||
|
||||
|
||||
def test_engine_quality_follows_channel_then_session(env): # noqa: F811
|
||||
client, engine = env
|
||||
client.post("/v1/channels", json={"url": "https://www.twitch.tv/alanzoka"}, headers=auth())
|
||||
sid = seed_session(engine, duration=60)
|
||||
engine.db.run("UPDATE sessions SET channel_id = 'twitch-alanzoka' WHERE id = ?", sid)
|
||||
assert engine.capture_quality(sid) == "best" # padrão novo
|
||||
r = client.put("/v1/channels/twitch-alanzoka/settings", json={"capture": {"quality": "720p"}}, headers=auth())
|
||||
assert r.status_code == 200 and r.json()["effective"]["capture"]["quality"] == "720p"
|
||||
assert engine.capture_quality(sid) == "720p"
|
||||
r = client.put(f"/v1/sessions/{sid}/settings", json={"capture": {"quality": "1080p"}}, headers=auth())
|
||||
assert r.json()["effective"]["capture"]["quality"] == "1080p"
|
||||
assert engine.capture_quality(sid) == "1080p"
|
||||
assert client.put(f"/v1/sessions/{sid}/settings", json={"capture": {"quality": "8k"}}, headers=auth()).status_code == 400
|
||||
|
||||
|
||||
def test_settings_route_lists_capture_qualities(env): # noqa: F811
|
||||
client, engine = env
|
||||
sid = seed_session(engine, duration=60)
|
||||
body = client.get(f"/v1/sessions/{sid}/settings", headers=auth()).json()
|
||||
assert [o["id"] for o in body["captureQualities"]] == list(capture.QUALITIES)
|
||||
assert body["defaults"]["capture"] == {"quality": "best"}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- busca exata de quadro em .ts
|
||||
@needs_ffmpeg
|
||||
@pytest.mark.parametrize("codec", ["libx264", "libx265"])
|
||||
def test_grab_frame_is_exact_in_ts(tmp_path, codec):
|
||||
"""Antes: `-ss` antes do `-i` num .ts dava o PRÓXIMO quadro-chave no H.264 e um quadro CINZA no HEVC."""
|
||||
if codec == "libx265" and "libx265" not in subprocess.run([FFMPEG, "-hide_banner", "-encoders"],
|
||||
capture_output=True, text=True).stdout:
|
||||
pytest.skip("FFmpeg sem libx265")
|
||||
ts = _make_ts(tmp_path / "b.ts", "160x96", 12, codec=codec, rate=30, lum="min(235,16+T*18)")
|
||||
for t in (3.0, 7.5, 9.3):
|
||||
out = media.grab_frame(FFMPEG, [(ts, 0.0, 12.0)], t, tmp_path / f"f{t}.png", width=0)
|
||||
raw = subprocess.run([FFMPEG, "-v", "error", "-i", str(out), "-f", "rawvideo", "-pix_fmt", "gray", "-"],
|
||||
capture_output=True, check=True).stdout
|
||||
mean = sum(raw) / len(raw)
|
||||
expected = t * 18 * 255 / 219 # Y de faixa limitada (16 + 18·t) → cinza de faixa cheia
|
||||
assert abs(mean - expected) < 6, (t, mean, expected) # 6 ≈ 0,3 s; o próximo quadro-chave daria até 42
|
||||
|
||||
|
||||
def test_seek_args_prerolls_and_selects_absolute_time():
|
||||
assert media.seek_args(10.0) == (["-ss", "6.000", "-copyts", "-start_at_zero"], "select='gte(t,10.000)'")
|
||||
assert media.seek_args(1.5) == (["-ss", "0.000", "-copyts", "-start_at_zero"], "select='gte(t,1.500)'")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- render que atravessa a troca de resolução
|
||||
@needs_ffmpeg
|
||||
@pytest.mark.parametrize("second", [("640x360", "libx264"), ("960x540", "libx265")])
|
||||
def test_render_across_resolution_change_keeps_whole_video(tmp_path, second):
|
||||
"""Retomada em outra qualidade (ou fonte que muda de resolução). Antes o vídeo parava na emenda (corte de 35 s
|
||||
com 20 s de vídeo; 15 s na troca H.264 → HEVC)."""
|
||||
size, codec = second
|
||||
if codec == "libx265" and "libx265" not in subprocess.run([FFMPEG, "-hide_banner", "-encoders"],
|
||||
capture_output=True, text=True).stdout:
|
||||
pytest.skip("FFmpeg sem libx265")
|
||||
a = _make_ts(tmp_path / "seg_00000.ts", "320x180", 4)
|
||||
b = _make_ts(tmp_path / "seg_00001.ts", size, 4, codec=codec)
|
||||
segs = [(a, 0.0, 4.0), (b, 4.0, 8.0)]
|
||||
same, created = editor_render.uniform_segments(FFMPEG, FFPROBE, [(a, 0.0, 4.0), (a, 4.0, 8.0)], tmp_path, "x")
|
||||
assert created is None and same == [(a, 0.0, 4.0), (a, 4.0, 8.0)] # blocos iguais: caminho de sempre
|
||||
clip = {"session_id": 1, "start_s": 1.0, "end_s": 7.0, "peak_s": 4.0, "title": "Emenda"}
|
||||
project = editor.validate_project(editor.default_project(clip, [Word(1.2, 1.5, "oi")], 8.0), session_id=1,
|
||||
session_duration=8.0, repo_root=tmp_path, tts_dir=tmp_path, assets_dir=tmp_path)
|
||||
project["cover"]["enabled"] = False
|
||||
out = tmp_path / "clip.mp4"
|
||||
editor_render.render_project(FFMPEG, FFPROBE, ["-c:v", "libx264", "-preset", "ultrafast"], segs, project,
|
||||
layout.merge(), "canal", out, tmp_path)
|
||||
streams = json.loads(subprocess.run([FFPROBE, "-v", "error", "-select_streams", "v", "-show_entries",
|
||||
"stream=duration,width,height", "-of", "json", str(out)],
|
||||
capture_output=True, text=True, check=True).stdout)["streams"][0]
|
||||
assert (streams["width"], streams["height"]) == (1080, 1920)
|
||||
assert float(streams["duration"]) == pytest.approx(6.0, abs=0.15)
|
||||
assert not list(tmp_path.glob("*.uniform.mkv")) # intermediário apagado
|
||||
@@ -0,0 +1,291 @@
|
||||
"""Apagar cortes (um, vários, por aba): regras de estado, arquivos só dentro das pastas do Clipador e a marca que
|
||||
impede a IA de recriar o momento apagado."""
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
import app.clip_delete as clip_delete
|
||||
import app.worker as worker_module
|
||||
from app.scoring import Moment
|
||||
|
||||
from .test_sources_and_api import auth, env, seed_session # noqa: F401 - fixture reaproveitada
|
||||
|
||||
|
||||
def add_clip(engine, sid, cid, status, peak=100.0, start=90.0, end=150.0, source="chat", reasons=None):
|
||||
engine.db.run("INSERT INTO clips (id, session_id, peak_s, start_s, end_s, score, source, reasons_json, status, title, "
|
||||
"created_at, updated_at) VALUES (?, ?, ?, ?, ?, 5, ?, ?, ?, 't', 'x', ?)",
|
||||
cid, sid, peak, start, end, source, json.dumps(reasons or {}), status, worker_module.now())
|
||||
|
||||
|
||||
def touch(path: Path, data: bytes = b"x") -> Path:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_bytes(data)
|
||||
return path
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def repo(env, tmp_path, monkeypatch): # noqa: F811
|
||||
"""REPO_ROOT = tmp_path: os caminhos do banco (relativos à raiz) caem na pasta do teste."""
|
||||
monkeypatch.setattr(clip_delete, "REPO_ROOT", tmp_path)
|
||||
monkeypatch.setattr(worker_module, "REPO_ROOT", tmp_path)
|
||||
client, engine = env
|
||||
sid = seed_session(engine)
|
||||
engine.db.run("UPDATE sessions SET dir = ? WHERE id = ?", f"data/sessions/{sid}", sid)
|
||||
return client, engine, sid, tmp_path
|
||||
|
||||
|
||||
def clip_files(root: Path, sid: int, cid: int) -> dict[str, Path]:
|
||||
out = root / "clips" / str(sid)
|
||||
return {
|
||||
"mp4": touch(out / f"clip-{cid}.mp4"), "jpg": touch(out / f"clip-{cid}.jpg"),
|
||||
"cover": touch(out / f"clip-{cid}-cover.jpg"), "ass": touch(out / f"clip-{cid}.ass"),
|
||||
"tmp": touch(out / f"clip-{cid}.tmp.mp4"), "proxy": touch(out / f"edit-{cid}" / "proxy-1000-2000.mp4"),
|
||||
"tts": touch(out / f"edit-{cid}" / "tts-abcdef123456.wav"), "nested": touch(out / f"edit-{cid}" / "sub" / "a.json"),
|
||||
"frame": touch(root / "data" / "sessions" / str(sid) / "frames" / f"clip{cid}-120.jpg"),
|
||||
}
|
||||
|
||||
|
||||
def set_files(engine, cid: int, sid: int, cover: bool = True) -> None:
|
||||
engine.db.run("UPDATE clips SET file = ?, thumb = ? WHERE id = ?", f"clips/{sid}/clip-{cid}.mp4", f"clips/{sid}/clip-{cid}.jpg", cid)
|
||||
engine.db.run("INSERT INTO edits (clip_id, project_json, rev, cover, created_at, updated_at) VALUES (?, '{}', 1, ?, 'x', 'x')",
|
||||
cid, f"clips/{sid}/clip-{cid}-cover.jpg" if cover else None)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- um corte
|
||||
def test_delete_one_removes_row_edit_and_all_files(repo):
|
||||
client, engine, sid, root = repo
|
||||
add_clip(engine, sid, 1, "ready")
|
||||
add_clip(engine, sid, 12, "ready", peak=400, start=380, end=450) # vizinho com id que começa igual
|
||||
files = clip_files(root, sid, 1)
|
||||
neighbor = clip_files(root, sid, 12)
|
||||
set_files(engine, 1, sid)
|
||||
session_file = touch(root / "data" / "sessions" / str(sid) / "seg_00001.ts")
|
||||
r = client.delete("/v1/clips/1", headers=auth())
|
||||
assert r.status_code == 200, r.text
|
||||
body = r.json()
|
||||
assert body["id"] == 1 and body["status"] == "ready" and body["left"] == []
|
||||
assert body["removedFiles"] >= len(files)
|
||||
assert not any(p.exists() for p in files.values())
|
||||
assert not (root / "clips" / str(sid) / "edit-1").exists()
|
||||
assert all(p.exists() for p in neighbor.values()) and session_file.exists() # nada do corte 12 nem da gravação
|
||||
assert engine.db.get("SELECT 1 FROM clips WHERE id = 1") is None
|
||||
assert engine.db.get("SELECT 1 FROM edits WHERE clip_id = 1") is None
|
||||
assert client.get("/v1/clips/1", headers=auth()).status_code == 404
|
||||
mark = engine.db.get("SELECT * FROM deleted_clips WHERE clip_id = 1")
|
||||
assert mark["session_id"] == sid and mark["peak_s"] == 100 and mark["status"] == "ready"
|
||||
|
||||
|
||||
def test_nonexistent_id_is_404_and_listed_as_not_found(repo):
|
||||
client, engine, sid, _root = repo
|
||||
r = client.delete("/v1/clips/999", headers=auth())
|
||||
assert r.status_code == 404 and r.json()["code"] == "not_found"
|
||||
r = client.post("/v1/clips/delete", json={"ids": [999]}, headers=auth())
|
||||
assert r.status_code == 200 and r.json()["failed"] == [{"id": 999, "code": "not_found", "reason": "corte não encontrado"}]
|
||||
|
||||
|
||||
def test_rendering_and_candidate_are_refused(repo):
|
||||
client, engine, sid, root = repo
|
||||
add_clip(engine, sid, 1, "rendering")
|
||||
add_clip(engine, sid, 2, "candidate", peak=300, start=280, end=340)
|
||||
add_clip(engine, sid, 3, "pending", peak=500, start=480, end=540)
|
||||
mp4 = touch(root / "clips" / str(sid) / "clip-1.mp4")
|
||||
r = client.delete("/v1/clips/1", headers=auth())
|
||||
assert r.status_code == 409 and r.json()["code"] == "busy_rendering" and "renderizando" in r.json()["error"]
|
||||
assert client.delete("/v1/clips/2", headers=auth()).json()["code"] == "busy_candidate"
|
||||
engine._rendering.add(3) # o motor acabou de pegar o pendente para renderizar
|
||||
assert client.delete("/v1/clips/3", headers=auth()).json()["code"] == "busy_rendering"
|
||||
assert mp4.exists() and engine.db.get("SELECT COUNT(*) AS n FROM clips")["n"] == 3
|
||||
assert engine.db.get("SELECT COUNT(*) AS n FROM deleted_clips")["n"] == 0
|
||||
|
||||
|
||||
def test_published_needs_explicit_confirmation(repo):
|
||||
client, engine, sid, _root = repo
|
||||
add_clip(engine, sid, 1, "published")
|
||||
r = client.delete("/v1/clips/1", headers=auth())
|
||||
assert r.status_code == 409 and r.json()["code"] == "published"
|
||||
assert client.post("/v1/clips/delete", json={"ids": [1]}, headers=auth()).json()["failed"][0]["code"] == "published"
|
||||
assert client.delete("/v1/clips/1?confirmPublished=true", headers=auth()).status_code == 200
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- vários e por aba
|
||||
def test_delete_many_reports_what_was_and_was_not_deleted(repo):
|
||||
client, engine, sid, root = repo
|
||||
for cid, st, peak in ((1, "discarded", 100), (2, "ready", 200), (3, "rendering", 300), (4, "rejected", 400), (5, "error", 500)):
|
||||
add_clip(engine, sid, cid, st, peak=peak, start=peak - 10, end=peak + 50)
|
||||
touch(root / "clips" / str(sid) / "clip-2.mp4")
|
||||
r = client.post("/v1/clips/delete", json={"ids": [1, 2, 3, 4, 2, 999, 5]}, headers=auth())
|
||||
assert r.status_code == 200, r.text
|
||||
body = r.json()
|
||||
assert body["requested"] == 6 and body["remaining"] == 0 # o 2 repetido conta uma vez
|
||||
assert [d["id"] for d in body["deleted"]] == [1, 2, 4, 5]
|
||||
assert {f["id"]: f["code"] for f in body["failed"]} == {3: "busy_rendering", 999: "not_found"}
|
||||
assert [r["id"] for r in engine.db.all("SELECT id FROM clips")] == [3]
|
||||
assert not (root / "clips" / str(sid) / "clip-2.mp4").exists()
|
||||
|
||||
|
||||
def test_delete_whole_tab_respects_session_filter(repo):
|
||||
client, engine, sid, _root = repo
|
||||
other = seed_session(engine)
|
||||
add_clip(engine, sid, 1, "discarded", peak=100)
|
||||
add_clip(engine, sid, 2, "discarded", peak=200)
|
||||
add_clip(engine, sid, 3, "ready", peak=300)
|
||||
add_clip(engine, other, 4, "discarded", peak=100)
|
||||
r = client.post("/v1/clips/delete", json={"statuses": ["discarded"], "sessionId": sid}, headers=auth())
|
||||
body = r.json()
|
||||
assert sorted(d["id"] for d in body["deleted"]) == [1, 2] and body["failed"] == []
|
||||
assert sorted(r["id"] for r in engine.db.all("SELECT id FROM clips")) == [3, 4]
|
||||
# Sem sessão: todas as sessões, inclusive "para aprovar".
|
||||
r = client.post("/v1/clips/delete", json={"statuses": ["ready", "discarded"]}, headers=auth())
|
||||
assert sorted(d["id"] for d in r.json()["deleted"]) == [3, 4]
|
||||
assert engine.db.get("SELECT COUNT(*) AS n FROM clips")["n"] == 0
|
||||
|
||||
|
||||
def test_batch_validation_and_limit(repo, monkeypatch):
|
||||
client, engine, sid, _root = repo
|
||||
assert client.post("/v1/clips/delete", json={}, headers=auth()).status_code == 400
|
||||
assert client.post("/v1/clips/delete", json={"ids": [1], "statuses": ["ready"]}, headers=auth()).status_code == 400
|
||||
assert client.post("/v1/clips/delete", json={"ids": [1], "sessionId": sid}, headers=auth()).status_code == 400
|
||||
assert client.post("/v1/clips/delete", json={"ids": list(range(1, 502))}, headers=auth()).status_code == 422
|
||||
assert client.post("/v1/clips/delete", json={"statuses": ["nada"]}, headers=auth()).status_code == 422
|
||||
for cid in range(1, 6):
|
||||
add_clip(engine, sid, cid, "discarded", peak=cid * 100)
|
||||
monkeypatch.setattr(clip_delete, "MAX_BATCH", 3)
|
||||
ids, remaining = clip_delete.select_ids(engine.db, None, ["discarded"], clip_delete.MAX_BATCH)
|
||||
assert ids == [5, 4, 3] and remaining == 2
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- arquivos fora da pasta
|
||||
def test_files_outside_clipper_folders_are_never_touched(repo):
|
||||
client, engine, sid, root = repo
|
||||
outside = touch(root / "outside" / "importante.mp4", b"nao apague")
|
||||
add_clip(engine, sid, 1, "ready")
|
||||
engine.db.run("UPDATE clips SET file = ?, thumb = ? WHERE id = 1", "outside/importante.mp4", "../fora.jpg")
|
||||
fora = touch(root.parent / "fora.jpg", b"tambem nao")
|
||||
try:
|
||||
body = client.delete("/v1/clips/1", headers=auth()).json()
|
||||
assert outside.read_bytes() == b"nao apague" and fora.read_bytes() == b"tambem nao"
|
||||
assert {x["file"] for x in body["left"]} >= {"outside/importante.mp4"}
|
||||
assert all("fora das pastas" in x["reason"] for x in body["left"])
|
||||
finally:
|
||||
fora.unlink(missing_ok=True)
|
||||
|
||||
|
||||
@pytest.mark.skipif(sys.platform != "win32", reason="junção é do Windows")
|
||||
def test_junction_inside_edit_folder_is_not_followed(repo):
|
||||
import _winapi
|
||||
|
||||
client, engine, sid, root = repo
|
||||
target = root / "outside" / "pasta"
|
||||
keep = touch(target / "nao-apague.txt", b"alvo")
|
||||
add_clip(engine, sid, 1, "ready")
|
||||
edit = root / "clips" / str(sid) / "edit-1"
|
||||
touch(edit / "proxy-1-2.mp4")
|
||||
_winapi.CreateJunction(str(target), str(edit / "link"))
|
||||
# A própria pasta da sessão nos cortes trocada por junção para fora: nada dela é apagado.
|
||||
other = seed_session(engine)
|
||||
elsewhere = root / "outside" / "sessao"
|
||||
keep2 = touch(elsewhere / "clip-2.mp4", b"alvo2")
|
||||
(root / "clips").mkdir(exist_ok=True)
|
||||
_winapi.CreateJunction(str(elsewhere), str(root / "clips" / str(other)))
|
||||
add_clip(engine, other, 2, "ready")
|
||||
body = client.delete("/v1/clips/1", headers=auth()).json()
|
||||
assert keep.read_bytes() == b"alvo" and not edit.exists() and body["left"] == []
|
||||
body = client.post("/v1/clips/delete", json={"ids": [2]}, headers=auth()).json()
|
||||
assert keep2.read_bytes() == b"alvo2" and body["deleted"][0]["left"][0]["reason"] == "fora das pastas do Clipador"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- o momento apagado não volta
|
||||
@pytest.mark.parametrize("session_status", ["recording", "stopped"])
|
||||
def test_deleted_discard_is_not_recreated(repo, monkeypatch, session_status):
|
||||
"""Ao vivo (passada da janela recente) e no fim (passada final da sessão inteira): o pico apagado não vira
|
||||
candidato de novo, nem com o juiz tendo recuado o trecho para longe do pico."""
|
||||
client, engine, sid, _root = repo
|
||||
engine.db.run("UPDATE sessions SET status = ?, duration_s = 1300 WHERE id = ?", session_status, sid)
|
||||
moment = Moment(peak_s=1149.0, start_s=1095.0, end_s=1155.0, score=5.0, source="chat", reasons={"onsetS": 1142})
|
||||
monkeypatch.setattr(worker_module, "find_moments", lambda *a, **k: [moment])
|
||||
analyzed = {"until": 1300.0}
|
||||
real = engine.load_timeline
|
||||
monkeypatch.setattr(engine, "load_timeline", lambda *a, **k: {**real(*a, **k), "duration": 1300.0,
|
||||
"analyzedUntil": analyzed["until"]})
|
||||
monkeypatch.setattr(engine.face, "for_scoring", lambda *a, **k: (None, 0.0))
|
||||
session = lambda: engine.db.get("SELECT * FROM sessions WHERE id = ?", sid) # noqa: E731
|
||||
assert engine.find_new_clips(session()) == 1
|
||||
clip = engine.db.get("SELECT * FROM clips WHERE session_id = ?", sid)
|
||||
engine.db.run("UPDATE clips SET start_s = 1012, end_s = 1100, status = 'discarded' WHERE id = ?", clip["id"])
|
||||
assert client.delete(f"/v1/clips/{clip['id']}", headers=auth()).status_code == 200
|
||||
for _ in range(3):
|
||||
assert engine.find_new_clips(session()) == 0
|
||||
assert engine.db.get("SELECT COUNT(*) AS n FROM clips WHERE session_id = ?", sid)["n"] == 0
|
||||
# Outro momento, longe do apagado, continua nascendo normalmente.
|
||||
monkeypatch.setattr(worker_module, "find_moments", lambda *a, **k: [
|
||||
Moment(peak_s=400.0, start_s=340.0, end_s=405.0, score=5.0, source="chat", reasons={})])
|
||||
assert engine.find_new_clips(session()) == 1
|
||||
|
||||
|
||||
def test_judge_backtrack_onto_deleted_kept_or_rejected_clip_is_vetoed(repo):
|
||||
"""O juiz recua um candidato novo para cima de um corte que você apagou: pronto/rejeitado apagado veta (como
|
||||
vetava enquanto existia); descartado pela IA apagado não veta (como não vetava)."""
|
||||
from .test_render_and_duplicates import RecuoJudge
|
||||
|
||||
_client, engine, sid, _root = repo
|
||||
engine.db.run("UPDATE sessions SET duration_s = 1300 WHERE id = ?", sid)
|
||||
add_clip(engine, sid, 9, "rejected", peak=1084, start=1045, end=1100)
|
||||
add_clip(engine, sid, 10, "discarded", peak=600, start=560, end=620)
|
||||
clip_delete.delete_clip(engine, 9)
|
||||
clip_delete.delete_clip(engine, 10)
|
||||
engine.judge = RecuoJudge(back_to=1012)
|
||||
add_clip(engine, sid, 42, "candidate", peak=1149, start=1095, end=1155)
|
||||
engine.judge_clip(engine.db.get("SELECT * FROM clips WHERE id = 42"))
|
||||
row = engine.db.get("SELECT status, judge_json FROM clips WHERE id = 42")
|
||||
judge = json.loads(row["judge_json"])
|
||||
assert row["status"] == "discarded" and judge["duplicateOf"] == 9 and "que você apagou" in judge["reason"]
|
||||
engine.judge = RecuoJudge(back_to=548)
|
||||
add_clip(engine, sid, 43, "candidate", peak=660, start=630, end=690)
|
||||
engine.judge_clip(engine.db.get("SELECT * FROM clips WHERE id = 43"))
|
||||
assert engine.db.get("SELECT status FROM clips WHERE id = 43")["status"] == "pending"
|
||||
|
||||
|
||||
def test_scan_does_not_propose_a_deleted_moment(repo):
|
||||
_client, engine, sid, _root = repo
|
||||
add_clip(engine, sid, 7, "discarded", peak=200, start=150, end=230, reasons={"candidateStartS": 180, "candidateEndS": 240})
|
||||
clip_delete.delete_clip(engine, 7)
|
||||
assert clip_delete.mark_spans(engine.db, sid, 0, 600) == [(150, 240, "apagado")]
|
||||
assert clip_delete.mark_spans(engine.db, sid, 300, 600) == []
|
||||
dur = {"minS": 60, "maxS": 90, "backtrackS": 120}
|
||||
session = engine.db.get("SELECT * FROM sessions WHERE id = ?", sid)
|
||||
existing = clip_delete.mark_spans(engine.db, sid, 0, 600)
|
||||
assert engine.intel._insert_scan_moment(session, {"start_s": 160, "end_s": 230, "score": 8}, 0, 600, dur, existing) is False
|
||||
assert engine.intel._insert_scan_moment(session, {"start_s": 400, "end_s": 470, "score": 8}, 0, 600, dur, existing) is True
|
||||
|
||||
|
||||
def test_render_skips_a_clip_deleted_after_the_queue_listed_it(repo, monkeypatch):
|
||||
_client, engine, sid, root = repo
|
||||
add_clip(engine, sid, 1, "pending")
|
||||
stale = engine.db.get("SELECT * FROM clips WHERE id = 1") # a fila leu a lista…
|
||||
clip_delete.delete_clip(engine, 1) # …e o corte foi apagado antes de o render começar
|
||||
called = []
|
||||
monkeypatch.setattr(engine, "_render_clip", lambda clip: called.append(clip["id"]))
|
||||
engine.render_clip(stale)
|
||||
assert called == [] and engine._rendering == set()
|
||||
assert not (root / "clips" / str(sid) / "clip-1.mp4").exists()
|
||||
|
||||
|
||||
def test_session_finishes_and_learning_stays_after_delete(repo):
|
||||
client, engine, sid, _root = repo
|
||||
engine.db.run("UPDATE sessions SET status = 'processing' WHERE id = ?", sid)
|
||||
engine.db.run("INSERT INTO emotes (channel_key, name, source, uses, weight, first_seen, last_seen) VALUES ('k', 'KEKW', 'twitch', 3, 0.6, 'x', 'x')")
|
||||
add_clip(engine, sid, 1, "pending")
|
||||
engine.db.run("UPDATE clips SET learned = 1 WHERE id = 1")
|
||||
session = engine.db.get("SELECT * FROM sessions WHERE id = ?", sid)
|
||||
engine.finish_if_done(session)
|
||||
assert engine.db.get("SELECT status FROM sessions WHERE id = ?", sid)["status"] == "processing" # pendente segura
|
||||
assert client.delete("/v1/clips/1", headers=auth()).status_code == 200
|
||||
engine.finish_if_done(session)
|
||||
assert engine.db.get("SELECT status FROM sessions WHERE id = ?", sid)["status"] == "done"
|
||||
assert engine.db.get("SELECT weight FROM emotes WHERE name = 'KEKW'")["weight"] == 0.6 # o aprendizado fica
|
||||
# Apagar a sessão leva as marcas junto.
|
||||
engine.delete_session(sid)
|
||||
assert engine.db.get("SELECT COUNT(*) AS n FROM deleted_clips")["n"] == 0
|
||||
@@ -0,0 +1,281 @@
|
||||
"""Pedidos do dono de 17/11/2026: duração mínima de verdade (mínimo + 1 s em todo corte automático), gancho em tarja
|
||||
animada e fontes empacotadas para escolher."""
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from app import editor, editor_render, layout
|
||||
from app.config import REPO_ROOT
|
||||
from app.judge import _clean
|
||||
from app.scoring import ChatMessage, Params, Word, find_moments, fit_length, fit_window
|
||||
|
||||
from .test_editor import KEY, api, make_project, validate # noqa: F401 - api é fixture
|
||||
from .test_scoring import burst, calm_chat
|
||||
from .test_sources_and_api import env, seed_session # noqa: F401
|
||||
|
||||
FFMPEG, FFPROBE = shutil.which("ffmpeg"), shutil.which("ffprobe")
|
||||
CFG = layout.merge()
|
||||
TARGET = layout.min_target(CFG) # 60 + 1 + 0,1
|
||||
EPS = 1e-6 # 61,1 em ponto flutuante
|
||||
HORIZONTAL = {"format": {"aspect": "horizontal"}}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 1. duração mínima
|
||||
def test_target_is_min_plus_one_second_and_never_above_max():
|
||||
assert TARGET == 61.1
|
||||
assert layout.min_target(layout.merge({"duration": {"minS": 89.5, "maxS": 90}})) == 90
|
||||
|
||||
|
||||
def test_fit_window_grows_backwards_then_forwards_and_never_invents():
|
||||
assert fit_window(100, 140, 0, 200, TARGET, 90) == (78.9, 140.0) # contexto antes
|
||||
assert fit_window(5, 30, 0, 200, TARGET, 90) == (0.0, 61.1) # começo da gravação: cresce para a frente
|
||||
assert fit_window(5, 30, 0, 40, TARGET, 90) == (0.0, 40.0) # gravação de 40 s: não inventa
|
||||
assert fit_window(0, 200, 0, 300, TARGET, 90, keep="start") == (0.0, 90.0)
|
||||
|
||||
|
||||
def test_candidate_from_heuristic_has_the_target_even_at_the_end_of_recording():
|
||||
p = Params(min_s=TARGET, max_s=90.0)
|
||||
chat = calm_chat(600) + burst(300, 8, 25, "KKKKKKKKK")
|
||||
m = find_moments(600, chat, [], [], p)[0]
|
||||
assert m.end_s - m.start_s >= TARGET - EPS
|
||||
start, end = fit_length(580, 600, 595, p, 600) # pico no fim da gravação: recua o início
|
||||
assert end - start >= TARGET - EPS and end <= 600
|
||||
|
||||
|
||||
def test_judge_answer_capped_by_window_end_still_has_the_minimum():
|
||||
# O juiz pôs o início tarde demais: o fim bate em `hi`; antes saía curto (end − start < mínimo).
|
||||
v = _clean({"keep": True, "score": 8, "start_s": 1100, "end_s": 1200, "title": "t", "caption": "c", "reason": "r"},
|
||||
1095, 1155, "m", lo=975, hi=1170, min_s=TARGET, max_s=90)
|
||||
assert v.end_s == 1170 and v.end_s - v.start_s >= TARGET - EPS
|
||||
|
||||
|
||||
def test_scan_moment_has_the_minimum(env): # noqa: F811
|
||||
_client, engine = env
|
||||
sid = seed_session(engine)
|
||||
session = engine.db.get("SELECT * FROM sessions WHERE id = ?", sid)
|
||||
ok = engine.intel._insert_scan_moment(session, {"start_s": 470, "end_s": 495, "score": 7, "title": "t", "reason": "r"},
|
||||
300.0, 500.0, CFG["duration"], [])
|
||||
clip = engine.db.get("SELECT start_s, end_s FROM clips WHERE session_id = ?", sid)
|
||||
assert ok and clip["end_s"] - clip["start_s"] >= TARGET - EPS and clip["end_s"] <= 500
|
||||
|
||||
|
||||
def _clip55():
|
||||
"""Caso medido (corte 55 da sessão 3): juiz 7900–7960 (60 s) e analista com a ação em 7915 → saía 46,8 s."""
|
||||
clip = {"session_id": 1, "start_s": 7900.0, "end_s": 7960.7, "peak_s": 7944.0, "title": "Pajé mão leve", "source": "chat"}
|
||||
words = [Word(7880 + i * 0.9, 7880 + i * 0.9 + 0.5, f"p{i}") for i in range(100)]
|
||||
return clip, {"action_start_s": 7915.0, "reaction_end_s": 7952.0, "hook": "Pajé mão leve"}, words
|
||||
|
||||
|
||||
def test_auto_project_never_goes_below_the_minimum():
|
||||
clip, analysis, words = _clip55()
|
||||
p = editor.auto_project(clip, analysis, words, [-20.0] * 9000, 9000.0, CFG)
|
||||
assert editor.output_duration(p["cuts"]) >= TARGET - EPS
|
||||
# silêncios quietos longos: só sai o que não derruba o corte abaixo do mínimo
|
||||
quiet = [-55.0] * 9000
|
||||
sparse = [Word(7890 + i * 6, 7890 + i * 6 + 0.4, "x") for i in range(14)]
|
||||
q = editor.auto_project({**clip, "peak_s": 7899.0}, None, sparse, quiet, 9000.0, CFG)
|
||||
assert editor.output_duration(q["cuts"]) >= TARGET - EPS
|
||||
# gravação curta demais: não inventa vídeo, registra o motivo
|
||||
r = editor.auto_project({**clip, "start_s": 5.0, "end_s": 30.0, "peak_s": 20.0}, None, [], [], 40.0, CFG)
|
||||
assert editor.output_duration(r["cuts"]) == 40.0 and any(s.startswith("curto:") for s in r["meta"]["steps"])
|
||||
# "cortar agora" (manual) é livre
|
||||
m = editor.auto_project({**clip, "source": "manual", "start_s": 7900.0, "end_s": 7930.0}, None, [], [], 9000.0, CFG)
|
||||
assert editor.output_duration(m["cuts"]) == 30.0
|
||||
|
||||
|
||||
def test_suggestion_respects_minimum_and_drops_removes_that_would_shrink_it():
|
||||
s = editor.clean_suggestion({"start_s": 1100, "end_s": 1130, "remove": [{"start_s": 1110, "end_s": 1120, "why": "x"}],
|
||||
"zooms": [], "hook": "h", "title": "t", "reason": "r"}, 1000, 1200, TARGET, 90)
|
||||
assert s["end"] - s["start"] >= TARGET - EPS and s["remove"] == []
|
||||
|
||||
|
||||
@pytest.mark.skipif(not (FFMPEG and FFPROBE), reason="FFmpeg não instalado")
|
||||
def test_auto_clip_file_is_at_least_min_plus_one_second(tmp_path):
|
||||
"""Medido no arquivo (ffprobe): o projeto da IA do caso do corte 55 sai com ≥ 61 s."""
|
||||
seg = tmp_path / "seg.ts"
|
||||
subprocess.run([FFMPEG, "-v", "error", "-f", "lavfi", "-i", "testsrc2=size=320x180:rate=30:duration=100", "-f", "lavfi",
|
||||
"-i", "sine=frequency=440:duration=100", "-c:v", "libx264", "-preset", "ultrafast", "-g", "15",
|
||||
"-c:a", "aac", "-shortest", str(seg)], check=True)
|
||||
clip = {"session_id": 1, "start_s": 30.0, "end_s": 90.7, "peak_s": 74.0, "title": "Pajé mão leve", "source": "chat"}
|
||||
analysis = {"action_start_s": 45.0, "reaction_end_s": 82.0, "hook": "Pajé mão leve"}
|
||||
data = editor.auto_project(clip, analysis, [], [-20.0] * 100, 100.0, CFG)
|
||||
p = validate(data, tmp_path, duration=100.0)
|
||||
out = tmp_path / "auto.mp4"
|
||||
editor_render.render_project(FFMPEG, FFPROBE, ["-c:v", "libx264", "-preset", "ultrafast"], [(seg, 0.0, 100.0)], p, CFG,
|
||||
"twitch.tv/x", out, tmp_path)
|
||||
duration = float(subprocess.run([FFPROBE, "-v", "error", "-show_entries", "format=duration", "-of", "csv=p=0", str(out)],
|
||||
capture_output=True, text=True, check=True).stdout)
|
||||
assert duration >= CFG["duration"]["minS"] + 1
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 2. gancho em tarja
|
||||
def _banner(**over):
|
||||
o = {"id": "hook", "kind": "hook", "text": "Carregando o dilera no PvP do Rob Run!", "start": 0, "end": 3, "y": 0.2,
|
||||
"size": 76, "style": "banner", "bg": "#00FF00", "color": "#FFFFFF", "font": layout.HOOK_FONT, "anim": "slide"}
|
||||
o.update(over)
|
||||
return o
|
||||
|
||||
|
||||
def test_hook_config_validates_and_merges():
|
||||
assert layout.DEFAULTS["hook"]["style"] == "banner" and layout.DEFAULTS["hook"]["anim"] == "slide"
|
||||
assert layout.validate({"hook": {"style": "plain", "bg": "#123abc", "seconds": 2.5}})["hook"] == \
|
||||
{"style": "plain", "bg": "#123ABC", "seconds": 2.5}
|
||||
for bad in ({"style": "x"}, {"bg": "verde"}, {"font": "Comic Sans"}, {"anim": "spin"}, {"seconds": 20}):
|
||||
with pytest.raises(layout.LayoutError):
|
||||
layout.validate({"hook": bad})
|
||||
|
||||
|
||||
def test_banner_overlay_validation_and_old_projects_untouched(tmp_path):
|
||||
p = validate(make_project(overlays=[_banner()]), tmp_path)
|
||||
o = p["overlays"][0]
|
||||
assert (o["style"], o["bg"], o["font"], o["anim"]) == ("banner", "#00FF00", layout.HOOK_FONT, "slide")
|
||||
old = validate(make_project(), tmp_path)["overlays"][0]
|
||||
assert not {"style", "bg", "font"} & set(old) # projeto antigo: nenhum campo novo aparece
|
||||
for bad in ({"style": "neon"}, {"font": "Comic Sans"}, {"bg": "verde"}, {"anim": "spin"}):
|
||||
with pytest.raises(editor.EditError):
|
||||
validate(make_project(overlays=[_banner(**bad)]), tmp_path)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("settings", [{}, CAM := {"layout": {"cam": {"x": 0.02, "y": 0.45, "w": 0.2, "h": 0.25}}}, HORIZONTAL])
|
||||
def test_banner_ass_two_lines_animated_and_clear_of_captions(tmp_path, settings):
|
||||
clip = {"session_id": 1, "start_s": 10.0, "end_s": 75.0, "peak_s": 50.0, "title": "Carregando o dilera no PvP do Rob Run!",
|
||||
"source": "chat"}
|
||||
cfg = layout.merge(settings)
|
||||
data = editor.auto_project(clip, None, [Word(11, 11.4, "olha")], [], 100.0, cfg)
|
||||
hook = data["overlays"][0]
|
||||
assert hook["style"] == "banner" and hook["end"] == 3.0
|
||||
p = validate(data, tmp_path)
|
||||
ass = editor_render.build_project_ass(p, editor.effective_settings(cfg, p), "twitch.tv/x")
|
||||
band = next(line for line in ass.splitlines() if ",Bar,," in line and "\\p1" in line and "&H00FF00&" in line)
|
||||
text = next(line for line in ass.splitlines() if "CARREGANDO" in line)
|
||||
assert "\\move(" in band and "\\move(" in text and "\\blur18" in text and "\\t(90,430,\\blur0)" in text
|
||||
assert f"\\fn{layout.HOOK_FONT}" in text and text.count("\\N") <= 1 # no máximo 2 linhas, palavra inteira
|
||||
g = editor_render.banner_layout(p["overlays"][0], layout.canvas_size(cfg))
|
||||
cap_y = layout.caption_y(editor.effective_settings(cfg, p))
|
||||
size = editor.effective_settings(cfg, p)["caption"]["size"]
|
||||
assert cap_y + size < g["top"] or cap_y - size > g["top"] + g["height"] # a tarja não cobre a legenda
|
||||
assert all(len(line) <= 40 for line in g["lines"])
|
||||
|
||||
|
||||
def test_banner_shrinks_long_text_instead_of_cutting_words():
|
||||
o = _banner(text="Uma frase bem comprida que não caberia em duas linhas no tamanho cheio do gancho {\\b1}", size=120)
|
||||
g = editor_render.banner_layout(o, (1080, 1920))
|
||||
assert len(g["lines"]) <= 2 and g["size"] < 120
|
||||
assert " ".join(g["lines"]) == o["text"].upper() # nenhuma palavra cortada
|
||||
events = editor_render.banner_events(o, (1080, 1920))
|
||||
assert "{\\b1}" not in events[1][2] and "(/B1)" in events[1][2] # texto escapado
|
||||
|
||||
|
||||
def _frame(video: Path, at: float, size: tuple[int, int]) -> bytes:
|
||||
return subprocess.run([FFMPEG, "-v", "error", "-ss", f"{at:.2f}", "-i", str(video), "-frames:v", "1", "-f", "rawvideo",
|
||||
"-pix_fmt", "rgb24", "-"], capture_output=True, check=True).stdout[: size[0] * size[1] * 3]
|
||||
|
||||
|
||||
def _green_rows(frame: bytes, w: int, h: int) -> list[int]:
|
||||
rows = []
|
||||
for y in range(0, h, 4):
|
||||
px = [frame[(y * w + x) * 3: (y * w + x) * 3 + 3] for x in range(0, w, 40)]
|
||||
if sum(1 for r, g, b in px if g > 200 and r < 80 and b < 80) > len(px) * 0.6:
|
||||
rows.append(y)
|
||||
return rows
|
||||
|
||||
|
||||
@pytest.mark.skipif(not (FFMPEG and FFPROBE), reason="FFmpeg não instalado")
|
||||
@pytest.mark.parametrize("aspect", ["vertical", "horizontal"])
|
||||
def test_real_render_banner(tmp_path, aspect):
|
||||
seg = tmp_path / "dark.ts"
|
||||
subprocess.run([FFMPEG, "-v", "error", "-f", "lavfi", "-i", "color=c=0x202060:size=640x360:rate=30:duration=6",
|
||||
"-f", "lavfi", "-i", "sine=frequency=440:duration=6", "-c:v", "libx264", "-preset", "ultrafast", "-g", "15",
|
||||
"-c:a", "aac", "-shortest", str(seg)], check=True)
|
||||
words = [{"s": 1.0 + i * 0.4, "e": 1.3 + i * 0.4, "w": w} for i, w in enumerate("tá escutando tiro não é".split())]
|
||||
data = make_project(source={"sessionId": 1, "lo": 0, "hi": 6}, settings={"format": {"aspect": aspect}},
|
||||
cuts=[{"start": 0, "end": 5, "mode": None}], overlays=[_banner(end=3)],
|
||||
captions={"enabled": True, "preset": "classic", "style": {}, "emphColor": "#22E36B", "words": words},
|
||||
cover={"enabled": False, "t": 1})
|
||||
p = validate(data, tmp_path, duration=6.0)
|
||||
out = tmp_path / f"{aspect}.mp4"
|
||||
editor_render.render_project(FFMPEG, FFPROBE, ["-c:v", "libx264", "-preset", "ultrafast"], [(seg, 0.0, 6.0)], p,
|
||||
layout.merge(), "twitch.tv/x", out, tmp_path)
|
||||
w, h = layout.FRAME_SIZES[aspect]
|
||||
early, settled, after = _frame(out, 0.05, (w, h)), _frame(out, 1.5, (w, h)), _frame(out, 4.0, (w, h))
|
||||
rows = _green_rows(settled, w, h)
|
||||
assert rows and abs((min(rows) + max(rows)) / 2 / h - 0.2) < 0.05 # tarja assentada perto de 20 % da altura
|
||||
assert len(_green_rows(early, w, h)) < len(rows) # no começo ela ainda está entrando
|
||||
assert _green_rows(after, w, h) == [] # depois do gancho, some
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 3. fontes empacotadas
|
||||
def test_packaged_fonts_lock_files_and_licenses():
|
||||
lock = json.loads((REPO_ROOT / "assets" / "fonts" / "fonts.lock.json").read_text(encoding="utf-8"))
|
||||
families = [e["family"] for e in lock["files"]]
|
||||
assert {"Luckiest Guy", "Bangers", "Anton", "Bebas Neue", "Poppins ExtraBold"} == set(families)
|
||||
for e in lock["files"]:
|
||||
assert hashlib.sha256((REPO_ROOT / e["path"]).read_bytes()).hexdigest() == e["sha256"]
|
||||
assert (REPO_ROOT / e["licenseFile"]).is_file() and e["license"] in ("OFL-1.1", "Apache-2.0")
|
||||
assert re.search(r"/google/fonts/[0-9a-f]{40}/", e["url"]) # URL presa a commit
|
||||
assert Path(e["path"]).parent.as_posix() == "assets/fonts" # pasta plana (fontsdir não lê subpastas)
|
||||
assert layout.font_files() == {e["family"]: e["path"] for e in lock["files"]}
|
||||
assert set(families) <= set(layout.FONTS)
|
||||
|
||||
|
||||
def test_packaged_fonts_have_portuguese_accents_and_matching_family_name():
|
||||
ttlib = pytest.importorskip("fontTools.ttLib")
|
||||
for family, path in layout.font_files().items():
|
||||
font = ttlib.TTFont(REPO_ROOT / path)
|
||||
cmap = font.getBestCmap()
|
||||
assert all(ord(c) in cmap for c in "TÁ ESCUTANDO TIRO, NÃO É? ÇÃÕÂÊÔÍÓÚÀ".replace(" ", ""))
|
||||
names = {r.nameID: r.toUnicode() for r in font["name"].names if r.platformID == 3}
|
||||
assert family == names[1] # o nome usado no ASS é o da família (ID 1) do arquivo
|
||||
|
||||
|
||||
def test_fontsdir_only_when_a_packaged_font_is_used():
|
||||
assert layout.ass_filter("a.ass", "Style: Caption,Arial Black,84") == "ass=a.ass"
|
||||
assert "fontsdir='" in layout.ass_filter("a.ass", "Style: Caption,Bangers,84")
|
||||
assert "fontsdir='" in layout.ass_filter("a.ass", "{\\fnLuckiest Guy}OI")
|
||||
|
||||
|
||||
def test_settings_route_lists_font_files(api): # noqa: F811
|
||||
client, _engine, _root = api
|
||||
body = client.get("/v1/sessions/1/settings", headers={"X-Service-Key": KEY}).json()
|
||||
assert body["fontFiles"]["Bangers"] == "assets/fonts/Bangers-Regular.ttf" and "Bangers" in body["fonts"]
|
||||
assert body["defaults"]["hook"]["style"] == "banner" and "slide" in body["hookAnims"]
|
||||
|
||||
|
||||
@pytest.mark.skipif(not FFMPEG, reason="FFmpeg não instalado")
|
||||
def test_packaged_font_is_really_used_in_render(tmp_path):
|
||||
"""Mesmo texto acentuado com Bangers, com Arial Black e com uma família inexistente: Bangers sai diferente das
|
||||
duas (o libass achou o arquivo empacotado)."""
|
||||
words = [{"s": 0.0, "e": 0.9, "w": w} for w in ["TÁ"]] + [{"s": 0.95, "e": 1.9, "w": "ESCUTANDO"}]
|
||||
|
||||
def still(font: str) -> bytes:
|
||||
p = validate(make_project(source={"sessionId": 1, "lo": 0, "hi": 6}, cuts=[{"start": 0, "end": 3, "mode": None}],
|
||||
overlays=[], captions={"enabled": True, "preset": "classic", "style": {}, "emphColor": "#22E36B",
|
||||
"words": words}, progress={"enabled": False}, cover={"enabled": False, "t": 1}), tmp_path, duration=6.0)
|
||||
cfg = editor.effective_settings(layout.merge(), p)
|
||||
cfg["caption"]["font"] = font
|
||||
ass = editor_render.build_project_ass(p, cfg, "")
|
||||
(tmp_path / "f.ass").write_text(ass, encoding="utf-8")
|
||||
frame = tmp_path / "f.png"
|
||||
subprocess.run([FFMPEG, "-y", "-v", "error", "-f", "lavfi", "-i", "color=c=0x303030:s=1080x1920:d=1", "-filter_complex",
|
||||
f"[0:v]{layout.ass_filter('f.ass', ass)}[v]", "-map", "[v]", "-frames:v", "1", frame.name],
|
||||
cwd=tmp_path, check=True)
|
||||
return frame.read_bytes()
|
||||
|
||||
bangers, arial, missing = still("Bangers"), still("Arial Black"), still("Fonte Que Nao Existe")
|
||||
assert bangers != arial and bangers != missing
|
||||
|
||||
|
||||
def test_banner_entry_blurs_the_whole_letter_and_settles_identical():
|
||||
"""Com contorno, o blur do libass só desfoca a borda: na entrada o preenchimento vem numa camada sem contorno
|
||||
(borrada inteira, como no modelo do dono) e, do fim da entrada em diante, entra o evento assentado de sempre."""
|
||||
events = editor_render.banner_events(_banner(), (1080, 1920))
|
||||
fill, outline, settled = events[1], events[2], events[3]
|
||||
assert r"\bord0" in fill[2] and r"\blur18\t(90,430,\blur0)" in fill[2] and fill[3] == (0.0, 0.43)
|
||||
assert r"\1a&HFF&" in outline[2] and outline[0] < fill[0] # contorno sem preenchimento, por baixo
|
||||
assert settled[3] == (0.43, None) and r"\move" not in settled[2] and r"\blur" not in settled[2]
|
||||
assert r"\pos(540," in settled[2] and r"\bord8\shad4" in settled[2]
|
||||
@@ -0,0 +1,313 @@
|
||||
"""Editor de cortes: validador do projeto, contas de tempo, legenda animada (ASS), filtergraph e rotas."""
|
||||
import json
|
||||
import shutil
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from app import editor, editor_render, layout
|
||||
from app.config import Settings
|
||||
from app.db import Database
|
||||
from app.main import create_app
|
||||
from app.scoring import Word
|
||||
from app.worker import Engine
|
||||
|
||||
from .test_sources_and_api import KEY, FakeJudge
|
||||
|
||||
FFMPEG = shutil.which("ffmpeg")
|
||||
|
||||
|
||||
def make_project(**over) -> dict:
|
||||
p = {
|
||||
"schema": 1, "source": {"sessionId": 1, "lo": 0, "hi": 60}, "settings": {},
|
||||
"cuts": [{"start": 10, "end": 20, "mode": None}, {"start": 25, "end": 30, "mode": "game_only"}],
|
||||
"captions": {"enabled": True, "preset": "pop", "style": {}, "emphColor": "#22E36B",
|
||||
"words": [{"s": 11, "e": 11.4, "w": "olha"}, {"s": 11.5, "e": 12, "w": "isso", "emph": True},
|
||||
{"s": 21, "e": 22, "w": "removida"}, {"s": 26, "e": 26.5, "w": "voltou"}]},
|
||||
"overlays": [{"id": "hook", "kind": "hook", "text": "ELE NÃO ACREDITOU", "start": 0, "end": 3, "y": 0.2, "size": 70,
|
||||
"color": "#FFFFFF", "box": "#E11D48", "anim": "pop"},
|
||||
{"id": "z1", "kind": "zoom", "start": 12, "end": 15, "scale": 1.4, "x": 0.5, "y": 0.4, "ramp": 0.2}],
|
||||
"progress": {"enabled": True, "color": "#FF7A1A", "height": 12},
|
||||
"audio": {"volume": 1, "narration": [], "music": None, "sfx": []},
|
||||
"cover": {"enabled": True, "t": 12, "text": "LAG"},
|
||||
}
|
||||
p.update(over)
|
||||
return p
|
||||
|
||||
|
||||
def validate(data, tmp_path: Path, duration=100.0):
|
||||
return editor.validate_project(data, session_id=1, session_duration=duration, repo_root=tmp_path,
|
||||
tts_dir=tmp_path / "tts", assets_dir=tmp_path / "assets")
|
||||
|
||||
|
||||
def test_time_mapping():
|
||||
cuts = [{"start": 10, "end": 20}, {"start": 25, "end": 30}]
|
||||
assert editor.output_duration(cuts) == 15
|
||||
assert editor.to_output(15, cuts) == (5, True)
|
||||
assert editor.to_output(22, cuts) == (10, False) # trecho removido gruda no começo do próximo
|
||||
assert editor.to_output(26, cuts) == (11, True)
|
||||
assert editor.to_session(11, cuts) == 26
|
||||
sl = editor.slice_pieces(cuts, 8, 12)
|
||||
assert [(p.start, p.end, p.out) for p in sl] == [(18, 20, 0), (25, 27, 2)]
|
||||
assert editor.normalize_cuts([{"start": 5, "end": 8}, {"start": 1, "end": 5.01}]) == [{"start": 1, "end": 8}]
|
||||
|
||||
|
||||
def test_validate_accepts_and_normalizes(tmp_path):
|
||||
p = validate(make_project(), tmp_path)
|
||||
assert p["cuts"][1]["mode"] == "game_only" and p["captions"]["words"][1]["emph"] is True
|
||||
assert editor.output_duration(p["cuts"]) == 15
|
||||
|
||||
|
||||
@pytest.mark.parametrize("change,message", [
|
||||
({"schema": 2}, "versão"),
|
||||
({"cuts": []}, "pelo menos um trecho"),
|
||||
({"cuts": [{"start": 10, "end": 11}]}, "de 3 a 180"),
|
||||
({"cuts": [{"start": 10, "end": 70}]}, r"cuts\[0\]\.end vai de 0 a 60"), # fora da janela (hi = 60)
|
||||
({"source": {"sessionId": 9, "lo": 0, "hi": 60}}, "outra sessão"),
|
||||
({"source": {"sessionId": 1, "lo": 0, "hi": 900}}, "source.hi"), # além do fim da gravação
|
||||
({"cuts": [{"start": 10, "end": 20, "mode": "rm -rf"}]}, "mode"),
|
||||
({"overlays": [{"id": "a b", "kind": "text", "text": "x", "start": 10, "end": 12}]}, "id curto"),
|
||||
({"overlays": [{"id": "z1", "kind": "zoom", "start": 10, "end": 14, "scale": 1.3},
|
||||
{"id": "z2", "kind": "zoom", "start": 12, "end": 16, "scale": 1.3}]}, "dois zooms"),
|
||||
({"overlays": [{"id": "t", "kind": "text", "text": "x" * 200, "start": 10, "end": 12}]}, "120"),
|
||||
({"audio": {"music": {"file": "../voice/.env"}}}, "música"),
|
||||
({"audio": {"music": {"file": "C:/Windows/win.ini"}}}, "música"),
|
||||
({"audio": {"narration": [{"id": "n", "file": "output/x.wav", "at": 10}]}}, "narração"),
|
||||
])
|
||||
def test_validate_rejects(tmp_path, change, message):
|
||||
with pytest.raises(editor.EditError, match=message):
|
||||
validate(make_project(**change), tmp_path)
|
||||
|
||||
|
||||
def test_zero_length_word_is_tolerated(tmp_path):
|
||||
data = make_project()
|
||||
data["captions"]["words"].append({"s": 13.0, "e": 13.0, "w": "queria"}) # Whisper real (corte 9 do skipnho)
|
||||
words = validate(data, tmp_path)["captions"]["words"]
|
||||
assert {"s": 13.0, "e": 13.05, "w": "queria"} in words
|
||||
|
||||
|
||||
def test_window_limit(tmp_path):
|
||||
with pytest.raises(editor.EditError, match="janela"):
|
||||
validate(make_project(source={"sessionId": 1, "lo": 0, "hi": 900}), tmp_path, duration=2000)
|
||||
|
||||
|
||||
def test_audio_only_from_allowed_folders(tmp_path):
|
||||
(tmp_path / "assets").mkdir()
|
||||
(tmp_path / "assets" / "beat.mp3").write_bytes(b"x")
|
||||
(tmp_path / "tts").mkdir()
|
||||
(tmp_path / "tts" / "tts-0123456789ab.wav").write_bytes(b"x")
|
||||
p = validate(make_project(audio={"volume": 1, "music": {"file": "assets/beat.mp3", "volume": 0.2},
|
||||
"narration": [{"id": "n1", "file": "tts/tts-0123456789ab.wav", "at": 12}]}), tmp_path)
|
||||
assert p["audio"]["music"]["file"] == "assets/beat.mp3" and p["audio"]["narration"][0]["at"] == 12
|
||||
|
||||
|
||||
def test_output_words_and_ass_presets(tmp_path):
|
||||
p = validate(make_project(), tmp_path)
|
||||
words = editor.output_words(p)
|
||||
assert [w.word for w in words] == ["olha", "isso", "voltou"] # "removida" caiu no trecho cortado
|
||||
assert words[2].start == 11.0 # 26 s da sessão = 10 s + 1 s
|
||||
cfg = editor.effective_settings(layout.merge(), p)
|
||||
ass = editor_render.build_project_ass(p, cfg, "twitch.tv/x")
|
||||
assert "\\fscx118" in ass # pop na palavra falada
|
||||
assert "&H6BE322&" in ass # cor da ênfase (#22E36B em BGR) na palavra marcada
|
||||
assert "ELE NÃO ACREDITOU" in ass and "Box" in ass # gancho com caixa
|
||||
assert "\\p1" in ass and "\\fscx100.00" in ass # barra de progresso até 100%
|
||||
assert "\\C" not in ass # gotcha 58: tag nunca em maiúscula
|
||||
for preset, mark in (("karaoke", "\\kf"), ("single", "\\fscx70"), ("minimal", "OLHA")):
|
||||
q = json.loads(json.dumps(p))
|
||||
q["captions"]["preset"] = preset
|
||||
text = editor_render.build_project_ass(q, editor.effective_settings(layout.merge(), q), "")
|
||||
assert mark in text if preset != "minimal" else mark not in text # mínima não usa maiúsculas
|
||||
|
||||
|
||||
def test_ass_escapes_user_text(tmp_path):
|
||||
p = make_project(overlays=[{"id": "t", "kind": "text", "text": "{\\b1}oi\\N", "start": 11, "end": 13}])
|
||||
q = validate(p, tmp_path)
|
||||
ass = editor_render.build_project_ass(q, editor.effective_settings(layout.merge(), q), "")
|
||||
assert "{\\b1}" not in ass and "(/b1)oi/N" in ass
|
||||
|
||||
|
||||
def test_filter_has_pieces_layouts_and_zoom(tmp_path):
|
||||
p = validate(make_project(), tmp_path)
|
||||
cfg = editor.effective_settings(layout.merge({"layout": {"cam": {"x": 0, "y": 0.5, "w": 0.2, "h": 0.3}}}), p)
|
||||
graph = editor_render.build_filter(p, cfg, editor.pieces(p["cuts"]), 10.0, "e.ass", [])
|
||||
assert "trim=start=0.000:end=10.000" in graph and "trim=start=15.000:end=20.000" in graph
|
||||
assert "vstack" in graph and "[c_0]" in graph # 1º trecho câmera em cima (rótulos únicos por trecho)
|
||||
assert "concat=n=2:v=1:a=1" in graph and "zoompan=z='1+0.4000*" in graph and "ass=e.ass" in graph
|
||||
# Prévia real a partir de 8 s: o zoom continua no mesmo instante do corte (it + 8).
|
||||
assert "(it+8.000)" in editor_render.zoom_filter(p, 8.0)
|
||||
|
||||
|
||||
def test_suggestion_is_clamped():
|
||||
s = editor.clean_suggestion({"hook": "x" * 200, "title": "t", "start_s": -50, "end_s": 999,
|
||||
"remove": [{"start_s": 20, "end_s": 20.1, "why": ""}, {"start_s": 30, "end_s": 34, "why": "silêncio"}],
|
||||
"zooms": [{"t": 40, "why": "grito"}, {"t": 500, "why": "fora"}], "reason": "r"}, 10, 80)
|
||||
assert (s["start"], s["end"]) == (10, 80) and len(s["hook"]) == 80
|
||||
assert s["remove"] == [{"start": 30, "end": 34, "why": "silêncio"}] and [z["t"] for z in s["zooms"]] == [40]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- rotas e render real
|
||||
def _lavfi_segments(folder: Path, n: int = 3, seconds: int = 4) -> list[Path]:
|
||||
folder.mkdir(parents=True, exist_ok=True)
|
||||
files = []
|
||||
for i in range(n):
|
||||
f = folder / f"seg_{i:05d}.ts"
|
||||
subprocess.run([FFMPEG, "-y", "-v", "error", "-f", "lavfi", "-i", f"testsrc2=s=640x360:r=30:d={seconds}",
|
||||
"-f", "lavfi", "-i", f"sine=frequency={300 + 100 * i}:d={seconds}", "-c:v", "libx264", "-preset",
|
||||
"ultrafast", "-g", "15", "-c:a", "aac", "-shortest", "-f", "mpegts", str(f)], check=True, capture_output=True)
|
||||
files.append(f)
|
||||
return files
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def api(tmp_path, monkeypatch):
|
||||
import app.editor_api as editor_api
|
||||
import app.worker as worker
|
||||
monkeypatch.setattr(editor_api, "REPO_ROOT", tmp_path)
|
||||
monkeypatch.setattr(worker, "REPO_ROOT", tmp_path)
|
||||
settings = Settings.load(env_file=tmp_path / "none.env", service_key=KEY, data_dir=tmp_path / "data",
|
||||
clips_dir=tmp_path / "output" / "clipper", judge_provider="codex", voice_url=None, voice_key=None)
|
||||
db = Database(settings.data_dir / "clipper.db")
|
||||
engine = Engine(settings, db, judge=FakeJudge())
|
||||
client = TestClient(create_app(settings, engine, start_engine=False))
|
||||
db.run("INSERT INTO sessions (id, platform, kind, url, status, dir, duration_s, started_at) "
|
||||
"VALUES (1, 'twitch', 'live', 'https://www.twitch.tv/skipnho', 'done', 'data/s1', 12, 'x')")
|
||||
words = [[1.0, 1.4, "olha"], [1.5, 2.0, "isso"], [9.0, 9.5, "fim"]]
|
||||
for i in range(3):
|
||||
db.run("INSERT INTO segments (session_id, idx, file, start_s, end_s, wall_end, analyzed, words_json) VALUES (1, ?, ?, ?, ?, 0, 1, ?)",
|
||||
i, f"data/s1/seg_{i:05d}.ts", i * 4.0, i * 4.0 + 4, json.dumps([w for w in words if i * 4 <= w[0] < i * 4 + 4]))
|
||||
db.run("INSERT INTO clips (id, session_id, peak_s, start_s, end_s, score, source, status, title, created_at, updated_at) "
|
||||
"VALUES (7, 1, 5, 2, 10, 8, 'manual', 'ready', 'Título', 'x', 'x')")
|
||||
return client, engine, tmp_path
|
||||
|
||||
|
||||
def test_edit_routes_roundtrip(api):
|
||||
client, engine, root = api
|
||||
h = {"X-Service-Key": KEY}
|
||||
r = client.get("/v1/clips/7/edit", headers=h)
|
||||
assert r.status_code == 200, r.text
|
||||
body = r.json()
|
||||
assert body["rev"] == 0 and body["project"]["cuts"] == [{"start": 2.0, "end": 10.0, "mode": None}]
|
||||
assert [w["w"] for w in body["words"]] == ["olha", "isso", "fim"] and body["window"] == {"lo": 0.0, "hi": 12.0}
|
||||
project = body["project"]
|
||||
project["cuts"] = [{"start": 0.0, "end": 3.0, "mode": None}, {"start": 6.0, "end": 10.0, "mode": None}]
|
||||
saved = client.put("/v1/clips/7/edit", headers=h, json={"project": project, "rev": 0})
|
||||
assert saved.status_code == 200 and saved.json()["rev"] == 1 and saved.json()["durationS"] == 7
|
||||
stale = client.put("/v1/clips/7/edit", headers=h, json={"project": project, "rev": 0})
|
||||
assert stale.status_code == 409 # autosave de outra aba não atropela
|
||||
bad = client.put("/v1/clips/7/edit", headers=h, json={"project": {**project, "cuts": []}, "rev": 1})
|
||||
assert bad.status_code == 400 and "trecho" in bad.json()["error"]
|
||||
assert client.get("/v1/clips/7", headers=h).json()["edit"]["updatedAt"]
|
||||
exp = client.post("/v1/clips/7/export", headers=h)
|
||||
assert exp.status_code == 200 and exp.json()["status"] == "pending" and exp.json()["editedDurationS"] == 7
|
||||
assert (exp.json()["startS"], exp.json()["endS"]) == (0.0, 10.0)
|
||||
# Ajuste do cartão (−2 s no início não cabe: a sessão começa em 0) → as pontas do projeto acompanham.
|
||||
client.patch("/v1/clips/7", headers=h, json={"endS": 11.0})
|
||||
assert client.get("/v1/clips/7/edit", headers=h).json()["project"]["cuts"][-1]["end"] == 11.0
|
||||
assert client.delete("/v1/clips/7/edit", headers=h).status_code == 204
|
||||
assert client.get("/v1/clips/7", headers=h).json()["edit"] is None
|
||||
|
||||
|
||||
def test_tts_and_suggest_need_services(api):
|
||||
client, _engine, _root = api
|
||||
h = {"X-Service-Key": KEY}
|
||||
assert "voz" in client.post("/v1/clips/7/tts", headers=h, json={"text": "oi", "voice": "pt-br-x"}).json()["error"]
|
||||
assert client.post("/v1/clips/7/tts", headers=h, json={"text": "oi", "voice": "../x"}).status_code == 422
|
||||
|
||||
|
||||
@pytest.mark.skipif(not FFMPEG, reason="FFmpeg não instalado")
|
||||
def test_real_render_proxy_and_waveform(api):
|
||||
client, engine, root = api
|
||||
_lavfi_segments(root / "data" / "s1")
|
||||
h = {"X-Service-Key": KEY}
|
||||
project = client.get("/v1/clips/7/edit", headers=h).json()["project"]
|
||||
project["cuts"] = [{"start": 1.0, "end": 4.0, "mode": None}, {"start": 6.0, "end": 9.0, "mode": "game_only"}]
|
||||
project["overlays"].append({"id": "z", "kind": "zoom", "start": 7, "end": 8.5, "scale": 1.5, "x": 0.5, "y": 0.5, "ramp": 0.2})
|
||||
project["progress"]["enabled"] = True
|
||||
assert client.put("/v1/clips/7/edit", headers=h, json={"project": project, "rev": 0}).status_code == 200
|
||||
proxy = client.post("/v1/clips/7/proxy", headers=h, json={"lo": 0, "hi": 12})
|
||||
assert proxy.status_code == 200, proxy.text
|
||||
wave = client.get("/v1/clips/7/waveform?lo=0&hi=12", headers=h).json()
|
||||
assert 500 <= len(wave["peaks"]) <= 610 and max(wave["peaks"]) == 1.0
|
||||
prev = client.post("/v1/clips/7/preview-render", headers=h, json={"fromS": 2, "durationS": 3})
|
||||
assert prev.status_code == 200, prev.text
|
||||
client.post("/v1/clips/7/export", headers=h)
|
||||
engine.render_pending()
|
||||
clip = client.get("/v1/clips/7", headers=h).json()
|
||||
assert clip["status"] == "ready", clip["error"]
|
||||
out = root / clip["file"]
|
||||
assert clip["edit"]["cover"] and (root / clip["edit"]["cover"]).is_file() # capa (etapa 7) gerada no export
|
||||
probe = subprocess.run([shutil.which("ffprobe") or "ffprobe", "-v", "error", "-show_entries", "stream=width,height:format=duration",
|
||||
"-of", "json", str(out)], capture_output=True, text=True, check=True)
|
||||
info = json.loads(probe.stdout)
|
||||
assert {"width": 1080, "height": 1920} in [{k: s[k] for k in ("width", "height")} for s in info["streams"] if "width" in s]
|
||||
assert abs(float(info["format"]["duration"]) - 6.0) < 0.25 # 3 s + 3 s, sem o meio removido
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- projeto entregue pela IA
|
||||
def test_auto_project_uses_pipeline_knowledge():
|
||||
clip = {"session_id": 1, "start_s": 100.0, "end_s": 140.0, "peak_s": 120.0, "title": "Título do juiz"}
|
||||
analysis = {"action_start_s": 95.0, "reaction_end_s": 143.0, "hook": "Caiu a 1 m da chegada"}
|
||||
words = [Word(94.0, 95.3, "olha"), Word(96.0, 96.4, "vai"), Word(103.0, 103.5, "silêncio"),
|
||||
Word(110.0, 110.4, "depois"), Word(118.0, 118.5, "NÃO"), Word(141.0, 141.4, "kkkk")]
|
||||
loudness = [-20.0] * 200
|
||||
for t in range(103, 111):
|
||||
loudness[t] = -55.0 # quieto entre 103,5 e 110 s → a IA corta; perto do pico (120 s) não corta
|
||||
# Mínimo de 15 s (configuração do canal): sobra espaço para tirar o silêncio. Com o padrão novo (60 s) o corte de
|
||||
# 50 s já está abaixo do mínimo e nenhum silêncio sai (conferido no fim).
|
||||
cfg = layout.merge({"layout": {"cam": {"x": 0, "y": 0.5, "w": 0.2, "h": 0.3}}, "duration": {"minS": 15}})
|
||||
p = editor.auto_project(clip, analysis, words, loudness, 300.0, cfg, model="m", generated_at="agora")
|
||||
assert p["cuts"][0]["start"] == 93.9 # ação em 95 − 0,8 s caiu no meio de "olha" → recua para antes da palavra
|
||||
assert p["cuts"][-1]["end"] == 143.8 # fim da reação + 0,8 s
|
||||
assert len(p["cuts"]) == 2 and p["cuts"][0]["end"] == 103.75 and p["cuts"][1]["start"] == 109.75
|
||||
hook = next(o for o in p["overlays"] if o["kind"] == "hook")
|
||||
zoom = next(o for o in p["overlays"] if o["kind"] == "zoom")
|
||||
assert hook["text"] == "Caiu a 1 m da chegada" and zoom["start"] == 119.8 and zoom["y"] == 0.17 # rosto (câmera em cima)
|
||||
assert p["captions"]["preset"] == "pop" and p["meta"]["origin"] == "ai" and p["cover"]["t"] == 120.0
|
||||
assert any("silêncio" in s for s in p["meta"]["steps"])
|
||||
# Sem análise e sem som medido: trecho do juiz, gancho = título.
|
||||
q = editor.auto_project(clip, None, words, [], 300.0, layout.merge())
|
||||
# Mínimo de verdade (17/11/2026): o trecho de 40 s do juiz cresce PARA TRÁS até mínimo + 1 s (+0,1 de folga).
|
||||
assert (q["cuts"][0]["start"], q["cuts"][-1]["end"]) == (78.9, 140.0)
|
||||
assert editor.output_duration(q["cuts"]) >= 61.0 and any("estendido" in s for s in q["meta"]["steps"])
|
||||
assert q["overlays"][0]["text"] == "Título do juiz"
|
||||
# Gancho do analista longo (frase descritiva) → usa o título do editor.
|
||||
long_hook = {"hook": "A provocação sobre ficar moscando começa e, logo depois, ele solta vários gritos"}
|
||||
assert editor.auto_project(clip, long_hook, words, [], 300.0, layout.merge())["overlays"][0]["text"] == "Título do juiz"
|
||||
default_min = editor.auto_project(clip, analysis, words, loudness, 300.0, layout.merge())
|
||||
assert len(default_min["cuts"]) == 1 and not any("silêncio" in s for s in default_min["meta"]["steps"])
|
||||
|
||||
|
||||
def test_render_always_goes_through_project(api):
|
||||
"""Um caminho de render: corte sem projeto ganha o da IA (origem ai); salvar no editor vira origem user."""
|
||||
client, engine, root = api
|
||||
h = {"X-Service-Key": KEY}
|
||||
body = client.get("/v1/clips/7/edit", headers=h).json()
|
||||
assert body["origin"] == "ai" and body["aiProject"]["meta"]["origin"] == "ai" and not body["saved"]
|
||||
if FFMPEG:
|
||||
_lavfi_segments(root / "data" / "s1")
|
||||
engine.db.run("UPDATE clips SET status = 'pending' WHERE id = 7")
|
||||
engine.render_pending()
|
||||
clip = client.get("/v1/clips/7", headers=h).json()
|
||||
assert clip["status"] == "ready", clip["error"]
|
||||
assert clip["edit"]["origin"] == "ai"
|
||||
project = client.get("/v1/clips/7/edit", headers=h).json()
|
||||
saved = client.put("/v1/clips/7/edit", headers=h, json={"project": project["project"], "rev": project["rev"]})
|
||||
assert saved.status_code == 200
|
||||
again = client.get("/v1/clips/7/edit", headers=h).json()
|
||||
assert again["origin"] == "user" and again["aiProject"]["meta"]["origin"] == "ai"
|
||||
|
||||
|
||||
def test_pick_hook_never_shows_session_time_or_cuts_a_word():
|
||||
from app.editor import pick_hook
|
||||
# Medido no corte 25 do skipnho: o analista devolveu uma frase com o tempo da gravação e ela saía cortada.
|
||||
raw = "Aos 5085s, ele solta que não veio de família rica e imediatamente começa a se desculpar"
|
||||
text, from_analyst = pick_hook(raw, "“Não vim de família rica” — e vêm os pedidos de desculpa")
|
||||
assert not from_analyst and text == "“Não vim de família rica” — e vêm os pedidos de desculpa"
|
||||
assert pick_hook("O lag jogou ele na água", "título") == ("O lag jogou ele na água", True)
|
||||
long_title = "Ele tenta explicar o que aconteceu com o carro e acaba piorando tudo na frente do chat"
|
||||
text, _ = pick_hook("", long_title)
|
||||
assert len(text) <= 60 and long_title.startswith(text) and not text.endswith(" ")
|
||||
assert pick_hook("Aos 120s, vem o susto", None)[0] == "Vem o susto"
|
||||
@@ -0,0 +1,109 @@
|
||||
"""Camadas novas do editor (17/11/2026): câmera em tela cheia por trecho, trecho mudo, texto com posição livre,
|
||||
chat da live na tela e capa nos primeiros quadros."""
|
||||
from pathlib import Path
|
||||
|
||||
from app import editor, editor_render, layout
|
||||
from app.scoring import ChatMessage
|
||||
|
||||
from .test_editor import make_project, validate
|
||||
|
||||
CAM = {"layout": {"cam": {"x": 0.02, "y": 0.45, "w": 0.2, "h": 0.25}}}
|
||||
|
||||
|
||||
def test_old_projects_get_defaults_for_new_fields(tmp_path):
|
||||
p = validate(make_project(), tmp_path)
|
||||
assert p["chat"]["enabled"] is False and p["chat"]["lines"] == 5
|
||||
assert p["cover"]["atStart"] is False
|
||||
assert all(c["muted"] is False for c in p["cuts"])
|
||||
assert p["overlays"][0]["x"] == 0.5
|
||||
|
||||
|
||||
def test_cam_only_layout_fills_the_screen_with_the_camera():
|
||||
cfg = layout.merge(CAM)
|
||||
chain = layout.layout_chain(cfg, "in", "out", mode="cam_only")
|
||||
assert "crop=iw*0.2:ih*0.25:iw*0.02:ih*0.45" in chain and "vstack" not in chain and "boxblur" not in chain
|
||||
assert f"crop={layout.W}:{layout.H}" in chain
|
||||
# sem câmera marcada não há o que mostrar: cai no desfoque
|
||||
assert "boxblur" in layout.layout_chain(layout.merge(), "in", "out", mode="cam_only")
|
||||
|
||||
|
||||
def test_cut_mode_and_mute_survive_and_do_not_merge(tmp_path):
|
||||
cuts = [{"start": 10, "end": 15, "mode": "cam_only"}, {"start": 15, "end": 20, "mode": "cam_only", "muted": True},
|
||||
{"start": 20, "end": 24, "mode": "cam_only", "muted": True}]
|
||||
p = validate(make_project(cuts=cuts), tmp_path)
|
||||
assert [(c["start"], c["end"], c["muted"]) for c in p["cuts"]] == [(10, 15, False), (15, 24, True)]
|
||||
cfg = editor.effective_settings(layout.merge(CAM), p)
|
||||
graph = editor_render.build_filter(p, cfg, editor.pieces(p["cuts"]), 10.0, None, [])
|
||||
first, second = graph.split("[pa0]")[0], graph.split("[pa0]")[1].split("[pa1]")[0]
|
||||
assert "volume=0" not in first.split("[sa0]atrim")[1] # 1º trecho com som
|
||||
assert second.rstrip().endswith("volume=0") # 2º trecho mudo
|
||||
assert graph.count("crop=iw*0.2:ih*0.25") == 2 # câmera em tela cheia nos dois
|
||||
|
||||
|
||||
def test_text_position_and_chat_block_in_ass(tmp_path):
|
||||
data = make_project(chat={"enabled": True, "x": 0.05, "y": 0.6, "width": 0.5, "lines": 2, "size": 30})
|
||||
data["overlays"][0]["x"] = 0.25
|
||||
p = validate(data, tmp_path)
|
||||
cfg = editor.effective_settings(layout.merge(), p)
|
||||
chat = [ChatMessage(11.0, "KKKKKK", "ana"), ChatMessage(12.0, "server chinês? {\\b1}", "beto"),
|
||||
ChatMessage(13.0, "terceira mensagem bem comprida que não cabe na largura do bloco de chat", "caio"),
|
||||
ChatMessage(22.0, "fora do corte", "dani")]
|
||||
ass = editor_render.build_project_ass(p, cfg, "twitch.tv/x", chat=chat)
|
||||
assert f"\\pos({int(1080 * 0.25)},{int(1920 * 0.2)})" in ass # gancho na posição arrastada
|
||||
chat_lines = [line for line in ass.splitlines() if ",Chat," in line]
|
||||
assert len(chat_lines) == 3 and "fora do corte" not in ass
|
||||
assert f"\\an1\\pos({int(1080 * 0.05)},{int(1920 * 0.6)})" in chat_lines[0]
|
||||
assert "ana:" in chat_lines[0] and "\\N" not in chat_lines[0]
|
||||
assert chat_lines[2].count("\\N") == 1 and "ana:" not in chat_lines[2] # só as 2 últimas
|
||||
assert "{\\b1}" not in ass and "…" in chat_lines[2] # texto do chat nunca vira tag; linha longa é cortada
|
||||
# desligado (padrão): nenhum evento de chat
|
||||
off = editor_render.build_project_ass(validate(make_project(), tmp_path), cfg, "", chat=chat)
|
||||
assert ",Chat,," not in off.split("[Events]")[1]
|
||||
|
||||
|
||||
def test_cover_at_start_overlays_first_frames(tmp_path):
|
||||
p = validate(make_project(cover={"enabled": True, "t": 12, "text": "LAG", "atStart": True}), tmp_path)
|
||||
assert p["cover"]["atStart"] is True
|
||||
cfg = editor.effective_settings(layout.merge(), p)
|
||||
graph = editor_render.build_filter(p, cfg, editor.pieces(p["cuts"]), 10.0, "e.ass", [], cover_input=1)
|
||||
assert "[vbase]" in graph and "[1:v]scale=1080:1920" in graph and "overlay=enable='lt(t,0.0667)'" in graph
|
||||
assert graph.rstrip().split(";")[-1] != "" and "[v]" in graph
|
||||
plain = editor_render.build_filter(p, cfg, editor.pieces(p["cuts"]), 10.0, "e.ass", [])
|
||||
assert "[vbase]" not in plain
|
||||
|
||||
|
||||
def test_real_render_with_new_layers(tmp_path):
|
||||
"""Render de verdade (FFmpeg) com câmera inteira, trecho mudo, chat na tela e capa no início."""
|
||||
import shutil
|
||||
import subprocess
|
||||
|
||||
ffmpeg = shutil.which("ffmpeg")
|
||||
if not ffmpeg:
|
||||
import pytest
|
||||
pytest.skip("sem ffmpeg")
|
||||
seg = tmp_path / "seg0.ts"
|
||||
subprocess.run([ffmpeg, "-v", "error", "-f", "lavfi", "-i", "testsrc2=size=640x360:rate=30:duration=8", "-f", "lavfi",
|
||||
"-i", "sine=frequency=440:duration=8", "-c:v", "libx264", "-preset", "ultrafast", "-g", "15", "-c:a", "aac", "-shortest",
|
||||
str(seg)], check=True) # -g 15: quadro-chave a cada 0,5 s (senão não dá para saltar no .ts)
|
||||
cuts = [{"start": 1, "end": 4, "mode": "cam_only"}, {"start": 4, "end": 7, "mode": None, "muted": True}]
|
||||
data = make_project(source={"sessionId": 1, "lo": 0, "hi": 8}, cuts=cuts, overlays=[],
|
||||
captions={"enabled": False, "preset": "pop", "style": {}, "emphColor": "#22E36B", "words": []},
|
||||
cover={"enabled": True, "t": 2, "text": "CAPA", "atStart": True},
|
||||
chat={"enabled": True, "lines": 3})
|
||||
p = validate(data, tmp_path, duration=8.0)
|
||||
base = layout.merge(CAM)
|
||||
segments = [(seg, 0.0, 8.0)]
|
||||
cover = editor_render.render_cover(ffmpeg, segments, p, base, "twitch.tv/x", tmp_path / "cover.jpg")
|
||||
out = tmp_path / "out.mp4"
|
||||
editor_render.render_project(ffmpeg, shutil.which("ffprobe"), ["-c:v", "libx264", "-preset", "ultrafast"], segments, p, base,
|
||||
"twitch.tv/x", out, tmp_path, chat=[ChatMessage(2.0, "KKKK", "ana"), ChatMessage(5.0, "F", "beto")],
|
||||
cover_file=cover)
|
||||
probe = subprocess.run([shutil.which("ffprobe") or "ffprobe", "-v", "error", "-show_entries", "format=duration:stream=width,height",
|
||||
"-of", "csv=p=0", str(out)], capture_output=True, text=True, check=True).stdout
|
||||
assert "1080,1920" in probe and abs(float(probe.strip().splitlines()[-1]) - 6.0) < 0.2
|
||||
# Trecho mudo: o volume médio da 2ª metade é silêncio; a 1ª tem o tom de teste.
|
||||
def mean_db(start: float) -> float:
|
||||
err = subprocess.run([ffmpeg, "-v", "info", "-ss", str(start), "-t", "2", "-i", str(out), "-af", "volumedetect", "-vn",
|
||||
"-f", "null", "-"], capture_output=True, text=True).stderr
|
||||
return float(err.split("mean_volume:")[1].split("dB")[0])
|
||||
assert mean_db(0.5) > -40 and mean_db(3.6) < -70
|
||||
@@ -0,0 +1,469 @@
|
||||
"""Rastreio de reação (face.py) com backends falsos: sem rede, sem modelo, sem FFmpeg."""
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
|
||||
import pytest
|
||||
|
||||
from app import face as face_mod
|
||||
from app.db import SCHEMA, Database
|
||||
from app.face import FaceService, FaceUnavailable, ModelStore
|
||||
from app.judge import build_prompt
|
||||
from app.reaction import FaceSample
|
||||
from tests.test_sources_and_api import KEY, auth, env, seed_session # noqa: F401 - fixture reaproveitada
|
||||
|
||||
CAM = {"x": 0.014, "y": 0.4, "w": 0.2, "h": 0.5}
|
||||
|
||||
|
||||
class FakeTracker:
|
||||
"""Rosto parado no meio do recorte; sorriso alto nos segundos de `laughs`; sem rosto nos de `gone`."""
|
||||
|
||||
name = "fake"
|
||||
|
||||
def __init__(self, laughs=(), gone=()):
|
||||
self.laughs, self.gone, self.closed = set(laughs), set(gone), False
|
||||
|
||||
def process(self, t, rgb):
|
||||
if int(t) in self.gone:
|
||||
return FaceSample(t, False)
|
||||
smile = 0.9 if int(t) in self.laughs else 0.05 + 0.05 * ((int(t * 6) % 3) / 2)
|
||||
return FaceSample(t, True, 0.5, 0.4, 0.3, {"mouthSmileLeft": smile, "mouthSmileRight": smile})
|
||||
|
||||
def close(self):
|
||||
self.closed = True
|
||||
|
||||
|
||||
def fake_reader(_ffmpeg, _file, crop_px, out_size, fps=6):
|
||||
for i in range(30 * fps):
|
||||
yield i / fps, None
|
||||
|
||||
|
||||
def make_service(engine, laughs=(), gone=(), tracker_factory=None):
|
||||
service = FaceService(engine, store=object(), tracker_factory=tracker_factory or (lambda _backend=None: FakeTracker(laughs, gone)),
|
||||
detector_factory=None, reader=fake_reader, grabber=None, sizer=lambda _f: (1280, 720))
|
||||
engine.face = service
|
||||
return service
|
||||
|
||||
|
||||
def set_cam(engine, sid, cam=CAM, source="yunet"):
|
||||
engine.db.run("UPDATE sessions SET cam_json = ? WHERE id = ?",
|
||||
json.dumps({"hasWebcam": cam is not None, "cam": cam, "source": source}), sid)
|
||||
|
||||
|
||||
def session(engine, sid):
|
||||
return engine.db.get("SELECT * FROM sessions WHERE id = ?", sid)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- banco / modelos
|
||||
def test_migration_creates_face_track(tmp_path):
|
||||
db = Database(tmp_path / "c.db")
|
||||
assert db.conn.execute("PRAGMA user_version").fetchone()[0] == len(SCHEMA)
|
||||
cols = {r["name"] for r in db.all("PRAGMA table_info(face_track)")}
|
||||
assert {"session_id", "idx", "status", "data_json", "error", "updated_at"} <= cols
|
||||
|
||||
|
||||
def _lock(tmp_path, content: bytes) -> object:
|
||||
lock = tmp_path / "models.lock.json"
|
||||
lock.write_text(json.dumps({"dir": "x", "models": [
|
||||
{"id": "m", "file": "m.onnx", "url": "https://exemplo/m.onnx", "sha256": hashlib.sha256(content).hexdigest()}]}))
|
||||
return lock
|
||||
|
||||
|
||||
def test_model_store_downloads_lazily_and_checks_sha256(tmp_path):
|
||||
calls = []
|
||||
|
||||
def fetch(url, dest):
|
||||
calls.append(url)
|
||||
dest.write_bytes(b"pesos certos")
|
||||
|
||||
store = ModelStore(tmp_path / "models", _lock(tmp_path, b"pesos certos"), fetch=fetch)
|
||||
path = store.path("m")
|
||||
assert path.read_bytes() == b"pesos certos" and calls == ["https://exemplo/m.onnx"]
|
||||
assert store.path("m") == path and len(calls) == 1 # conferido uma vez; não baixa de novo
|
||||
# Arquivo já presente e certo (setup.ps1 baixou): nenhum download.
|
||||
fresh = ModelStore(tmp_path / "models", _lock(tmp_path, b"pesos certos"), fetch=lambda *_: pytest.fail("baixou"))
|
||||
assert fresh.path("m") == path
|
||||
|
||||
|
||||
def test_model_store_rejects_wrong_sha256_and_network_errors(tmp_path):
|
||||
store = ModelStore(tmp_path / "models", _lock(tmp_path, b"pesos certos"),
|
||||
fetch=lambda _url, dest: dest.write_bytes(b"adulterado"))
|
||||
with pytest.raises(FaceUnavailable, match="sha256"):
|
||||
store.path("m")
|
||||
assert not list((tmp_path / "models").iterdir()) # nem o .part fica
|
||||
|
||||
def offline(_url, _dest):
|
||||
raise OSError("sem rede")
|
||||
with pytest.raises(FaceUnavailable, match="baixar"):
|
||||
ModelStore(tmp_path / "models", _lock(tmp_path, b"x"), fetch=offline).path("m")
|
||||
with pytest.raises(FaceUnavailable):
|
||||
store.path("nao-existe")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- laço por bloco
|
||||
def test_block_is_tracked_in_full_frame_coords(env): # noqa: F811
|
||||
_client, engine = env
|
||||
service = make_service(engine, laughs=range(40, 45))
|
||||
sid = seed_session(engine, duration=120)
|
||||
assert service.step() is False # câmera ainda não decidida: espera a detecção
|
||||
set_cam(engine, sid)
|
||||
for _ in range(4):
|
||||
assert service.step() is True
|
||||
assert service.step() is False
|
||||
rows = engine.db.all("SELECT * FROM face_track WHERE session_id = ? ORDER BY idx", sid)
|
||||
assert [r["status"] for r in rows] == ["done"] * 4
|
||||
data = json.loads(rows[1]["data_json"])
|
||||
assert data["cam"] == CAM and data["backend"] == "fake" and data["frames"] == 180
|
||||
seconds = data["seconds"]
|
||||
assert [s["t"] for s in seconds] == list(range(30, 60)) # bloco 30–60 s, sem repetir segundos do vizinho
|
||||
crop = face_mod.expand(CAM)
|
||||
assert seconds[0]["cx"] == pytest.approx(crop["x"] + 0.5 * crop["w"], abs=1e-3) # quadro inteiro, não recorte
|
||||
assert seconds[0]["size"] == pytest.approx(0.3 * crop["h"], abs=1e-3)
|
||||
assert service.tracked_until(sid) == 120
|
||||
dense = service.dense(sid, 0, 120)
|
||||
assert len(dense) == 120 and dense[42].smile == pytest.approx(0.9)
|
||||
|
||||
|
||||
def test_no_cam_and_backend_unavailable(env): # noqa: F811
|
||||
_client, engine = env
|
||||
service = make_service(engine)
|
||||
sid = seed_session(engine, duration=60)
|
||||
set_cam(engine, sid, cam=None) # detecção rodou e não achou câmera
|
||||
assert service.step() and service.step()
|
||||
assert {r["status"] for r in engine.db.all("SELECT status FROM face_track WHERE session_id = ?", sid)} == {"no_cam"}
|
||||
assert service.for_scoring(session(engine, sid), 0, 60) == (None, 0.0) # pontuação segue como antes
|
||||
# Backend sem modelo/biblioteca: não marca o bloco (tenta de novo depois).
|
||||
sid2 = seed_session(engine, duration=60)
|
||||
set_cam(engine, sid2)
|
||||
|
||||
def broken(_backend=None):
|
||||
raise FaceUnavailable("sem modelo")
|
||||
service._tracker_factory = broken
|
||||
with pytest.raises(FaceUnavailable):
|
||||
service.step()
|
||||
assert engine.db.get("SELECT COUNT(*) AS n FROM face_track WHERE session_id = ?", sid2)["n"] == 0
|
||||
|
||||
|
||||
def test_block_error_is_recorded(env): # noqa: F811
|
||||
_client, engine = env
|
||||
service = make_service(engine)
|
||||
sid = seed_session(engine, duration=30)
|
||||
set_cam(engine, sid)
|
||||
|
||||
def failing(*_a, **_k):
|
||||
raise face_mod.FaceError("bloco apagado")
|
||||
yield # pragma: no cover
|
||||
service._reader = failing
|
||||
assert service.step()
|
||||
row = engine.db.get("SELECT * FROM face_track WHERE session_id = ?", sid)
|
||||
assert row["status"] == "error" and "apagado" in row["error"]
|
||||
|
||||
|
||||
def test_camera_change_resets_the_track(env): # noqa: F811
|
||||
_client, engine = env
|
||||
service = make_service(engine)
|
||||
sid = seed_session(engine, duration=60)
|
||||
set_cam(engine, sid)
|
||||
service.step()
|
||||
service.step()
|
||||
assert engine.db.get("SELECT COUNT(*) AS n FROM face_track")["n"] == 2
|
||||
# Você corrige a câmera no layout da sessão: a série é apagada e refeita com o retângulo novo.
|
||||
new_cam = {"x": 0.7, "y": 0.6, "w": 0.25, "h": 0.35}
|
||||
engine.db.run("UPDATE sessions SET settings_json = ? WHERE id = ?", json.dumps({"layout": {"cam": new_cam}}), sid)
|
||||
assert service.cam_for(session(engine, sid)) == (new_cam, "manual", True)
|
||||
service.step()
|
||||
rows = engine.db.all("SELECT data_json FROM face_track WHERE session_id = ?", sid)
|
||||
assert len(rows) == 1 and json.loads(rows[0]["data_json"])["cam"] == new_cam
|
||||
|
||||
|
||||
def test_find_new_clips_waits_for_face_at_most_two_blocks(env): # noqa: F811
|
||||
_client, engine = env
|
||||
service = make_service(engine, laughs=range(300, 306))
|
||||
sid = seed_session(engine) # pico do chat em 300 s, 600 s gravados, transcrição toda pronta
|
||||
set_cam(engine, sid)
|
||||
for _ in range(9): # rosto até 270 s: 11 blocos atrás da transcrição → não segura o corte
|
||||
service.step()
|
||||
assert service.must_wait(330, 270, 600) is False
|
||||
assert service.must_wait(330, 270, 320) is True # rosto 1–2 blocos atrás: espera
|
||||
while service.step():
|
||||
pass
|
||||
assert engine.find_new_clips(session(engine, sid)) == 1
|
||||
clip = engine.db.get("SELECT * FROM clips WHERE session_id = ?", sid)
|
||||
reasons = json.loads(clip["reasons_json"])
|
||||
assert clip["source"] == "chat" and reasons["face"]["label"] == "risada" and 300 <= reasons["face"]["peakS"] <= 306
|
||||
|
||||
|
||||
def test_live_clip_waits_while_face_is_one_block_behind(env): # noqa: F811
|
||||
_client, engine = env
|
||||
service = make_service(engine, laughs=range(300, 306))
|
||||
sid = seed_session(engine)
|
||||
set_cam(engine, sid)
|
||||
for _ in range(10): # rosto até 300 s; o corte (≈ 286–306 s + folga) precisa até ~318 s
|
||||
service.step()
|
||||
engine.db.run("UPDATE segments SET analyzed = 0 WHERE session_id = ? AND idx >= 12", sid) # transcrição até 360 s
|
||||
assert engine.find_new_clips(session(engine, sid)) == 0
|
||||
service.step()
|
||||
assert engine.find_new_clips(session(engine, sid)) == 1
|
||||
|
||||
|
||||
def test_judge_prompt_gets_face_line(env): # noqa: F811
|
||||
_client, engine = env
|
||||
service = make_service(engine, laughs=range(300, 306))
|
||||
sid = seed_session(engine)
|
||||
set_cam(engine, sid)
|
||||
while service.step():
|
||||
pass
|
||||
text = service.summary(session(engine, sid), 280, 330)
|
||||
assert text.startswith("risada forte em 30")
|
||||
prompt = build_prompt("x", "twitch", 290, 320, 305, [], [], {}, face=text)
|
||||
assert "Rosto do streamer" in prompt and "risada forte em 30" in prompt
|
||||
assert "Rosto do streamer" not in build_prompt("x", "twitch", 290, 320, 305, [], [], {})
|
||||
engine.intel.opts["faceTrack"] = False
|
||||
assert service.summary(session(engine, sid), 280, 330) == ""
|
||||
|
||||
|
||||
class FakeOsfTracker(FakeTracker):
|
||||
"""Plano B: rosto e posição, sem blendshapes (como o OpenSeeFace de verdade)."""
|
||||
|
||||
name = "openseeface"
|
||||
|
||||
def process(self, t, rgb):
|
||||
return FaceSample(t, True, 0.5, 0.4, 0.3, {})
|
||||
|
||||
|
||||
def test_openseeface_series_does_not_break_signal_nor_lie_to_the_judge(env): # noqa: F811
|
||||
_client, engine = env
|
||||
service = make_service(engine, tracker_factory=lambda _backend=None: FakeOsfTracker())
|
||||
sid = seed_session(engine)
|
||||
set_cam(engine, sid)
|
||||
while service.step():
|
||||
pass
|
||||
view = service.view(session(engine, sid), 0, None)
|
||||
assert view["blocks"]["done"] > 0 and view["moments"] == []
|
||||
assert all(r.get("signal", 0) == 0 for r in view["seconds"])
|
||||
face, _until = service.for_scoring(session(engine, sid), 0, 300)
|
||||
from app.scoring import find_moments
|
||||
assert find_moments(300, [], [None] * 300, [], face=face) == []
|
||||
# Sem expressões, "sem reação marcante" seria mentira para o analista: a linha não vai.
|
||||
assert service.summary(session(engine, sid), 100, 200) == ""
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- câmera local
|
||||
class FakeDetector:
|
||||
def detect(self, bgr):
|
||||
return [(18.0, 363.0, 85.0, 109.0, 0.92)]
|
||||
|
||||
|
||||
class FakeFrame:
|
||||
shape = (720, 1280, 3)
|
||||
|
||||
|
||||
def test_detect_cam_local_first_without_ai(env): # noqa: F811
|
||||
_client, engine = env
|
||||
service = make_service(engine)
|
||||
service._detector_factory = FakeDetector
|
||||
service._grabber = lambda *_a, **_k: FakeFrame()
|
||||
engine.judge.provider = "off" # sem IA nenhuma
|
||||
sid = seed_session(engine)
|
||||
result = engine.intel.detect_cam(sid, apply=True)
|
||||
assert result["hasWebcam"] and result["source"] == "yunet" and result["frames"] == 12
|
||||
cam = result["cam"]
|
||||
assert cam["y"] < 363 / 720 - 0.5 * 109 / 720 # folga acima da testa
|
||||
saved = json.loads(session(engine, sid)["settings_json"])
|
||||
assert saved["layout"]["cam"] == cam # sem canal: vale para a sessão
|
||||
assert json.loads(session(engine, sid)["cam_json"])["source"] == "yunet"
|
||||
|
||||
|
||||
def test_detect_cam_no_face_falls_back_to_ai_or_records_retry(env): # noqa: F811
|
||||
_client, engine = env
|
||||
service = make_service(engine)
|
||||
service._detector_factory = lambda: type("D", (), {"detect": lambda self, bgr: []})()
|
||||
service._grabber = lambda *_a, **_k: FakeFrame()
|
||||
sid = seed_session(engine)
|
||||
engine.db.run("UPDATE sessions SET status = 'recording' WHERE id = ?", sid)
|
||||
calls = []
|
||||
|
||||
def ai_cam(images):
|
||||
calls.append(len(images))
|
||||
return {"has_webcam": True, "x": 0.01, "y": 0.5, "w": 0.2, "h": 0.4, "game_on_screen": ""}
|
||||
engine.judge.detect_cam = ai_cam
|
||||
engine.intel.frames = lambda _s, times, _tag: [(t, f"f{int(t)}.jpg") for t in times]
|
||||
engine.intel.e.rel = lambda p: str(p)
|
||||
result = engine.intel.detect_cam(sid)
|
||||
assert result["source"] == "ai" and calls == [3] # local sem rosto → IA (ligada, com visão)
|
||||
# Sem IA: fica registrado "sem câmera" e tenta de novo daqui a 5 min de gravação.
|
||||
engine.judge.provider = "off"
|
||||
engine.db.run("UPDATE sessions SET cam_json = NULL WHERE id = ?", sid)
|
||||
engine.intel.maybe_detect_cam(session(engine, sid))
|
||||
saved = json.loads(session(engine, sid)["cam_json"])
|
||||
assert saved["hasWebcam"] is False and saved["source"] == "yunet" and saved["retryAfterS"] == 900
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- API
|
||||
def test_face_api_and_reset(env): # noqa: F811
|
||||
client, engine = env
|
||||
service = make_service(engine, laughs=range(300, 306))
|
||||
sid = seed_session(engine)
|
||||
set_cam(engine, sid)
|
||||
while service.step():
|
||||
pass
|
||||
r = client.get(f"/v1/sessions/{sid}/face?from=290&to=320", headers=auth())
|
||||
assert r.status_code == 200
|
||||
body = r.json()
|
||||
assert body["cam"] == CAM and body["camSource"] == "yunet" and body["coords"] == "frame"
|
||||
assert body["blocks"]["done"] == 20 and body["trackedUntilS"] == 600
|
||||
assert [s["t"] for s in body["seconds"]][:2] == [290, 291] and body["seconds"][-1]["t"] == 319
|
||||
assert 0 < body["seconds"][0]["cx"] < CAM["x"] + CAM["w"] and "signal" in body["seconds"][0]
|
||||
assert [m["label"] for m in body["moments"]] == ["risada"]
|
||||
assert client.get(f"/v1/sessions/{sid}/face?from=50&to=10", headers=auth()).status_code == 400
|
||||
assert client.get("/v1/sessions/999/face", headers=auth()).status_code == 404
|
||||
r = client.post(f"/v1/sessions/{sid}/face/reset", headers=auth())
|
||||
assert r.status_code == 200 and r.json() == {"ok": True, "deleted": 20, "scheduled": False}
|
||||
assert client.get(f"/v1/sessions/{sid}/face", headers=auth()).json()["blocks"]["done"] == 0
|
||||
|
||||
|
||||
def test_face_track_option_persists(env): # noqa: F811
|
||||
client, engine = env
|
||||
r = client.put("/v1/judge", json={"provider": "codex", "model": "", "minScore": 6, "faceTrack": False}, headers=auth())
|
||||
assert r.status_code == 200 and r.json()["options"]["faceTrack"] is False
|
||||
assert engine.face.enabled is False
|
||||
saved = {r["key"]: r["value"] for r in engine.db.all("SELECT * FROM settings")}
|
||||
assert saved["opt_faceTrack"] == "false"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- correções da revisão (médios)
|
||||
import sys # noqa: E402
|
||||
import time # noqa: E402
|
||||
|
||||
|
||||
def _fake_ffmpeg(code: str) -> list[str]:
|
||||
"""Processo falso no lugar do FFmpeg (Python sem shell): `code` escreve quadros/stderr e sai."""
|
||||
return [sys.executable, "-c", code]
|
||||
|
||||
|
||||
def test_read_frames_ok_and_nonzero_exit_after_some_frames():
|
||||
frame = 4 * 2 * 3
|
||||
ok = face_mod._read_frames(_fake_ffmpeg(f"import sys; sys.stdout.buffer.write(b'x' * {frame * 3})"), (4, 2), 6, 30, "b")
|
||||
assert len(list(ok)) == 3
|
||||
# FFmpeg que cai no meio (2 quadros e código 1): erro, não bloco truncado gravado como completo.
|
||||
code = f"import sys; sys.stdout.buffer.write(b'x' * {frame * 2}); sys.stdout.flush(); sys.exit(1)"
|
||||
with pytest.raises(face_mod.FaceError, match="código 1 depois de 2 quadros"):
|
||||
list(face_mod._read_frames(_fake_ffmpeg(code), (4, 2), 6, 30, "b"))
|
||||
|
||||
|
||||
def test_read_frames_drains_big_stderr_and_has_a_deadline():
|
||||
# ~360 KB no stderr (mais que o buffer do pipe) não trava; o erro traz a última linha.
|
||||
code = "import sys; sys.stderr.write('ruido\\n' * 60000 + 'fim do erro\\n'); sys.exit(2)"
|
||||
started = time.perf_counter()
|
||||
with pytest.raises(face_mod.FaceError, match="fim do erro"):
|
||||
list(face_mod._read_frames(_fake_ffmpeg(code), (4, 2), 6, 30, "b"))
|
||||
# Processo que não entrega nada nem sai: morto pelo prazo.
|
||||
with pytest.raises(face_mod.FaceError, match="passou de 1 s"):
|
||||
list(face_mod._read_frames(_fake_ffmpeg("import time; time.sleep(60)"), (4, 2), 6, 1, "b"))
|
||||
assert time.perf_counter() - started < 20
|
||||
|
||||
|
||||
def test_truncated_block_is_error_not_done(env): # noqa: F811
|
||||
_client, engine = env
|
||||
service = make_service(engine)
|
||||
sid = seed_session(engine, duration=30)
|
||||
set_cam(engine, sid)
|
||||
|
||||
def short(*_a, **_k):
|
||||
for i in range(60): # 10 s de 30
|
||||
yield i / 6, None
|
||||
service._reader = short
|
||||
assert service.step()
|
||||
row = engine.db.get("SELECT * FROM face_track WHERE session_id = ?", sid)
|
||||
assert row["status"] == "error" and "truncado" in row["error"]
|
||||
|
||||
|
||||
def test_reset_does_not_block_while_a_block_is_running(env): # noqa: F811
|
||||
client, engine = env
|
||||
service = make_service(engine)
|
||||
sid = seed_session(engine, duration=60)
|
||||
set_cam(engine, sid)
|
||||
service.step()
|
||||
service._busy.acquire() # um bloco "em andamento"
|
||||
try:
|
||||
started = time.perf_counter()
|
||||
r = client.post(f"/v1/sessions/{sid}/face/reset", headers=auth())
|
||||
assert time.perf_counter() - started < 3
|
||||
assert r.status_code == 202 and r.json()["scheduled"] is True
|
||||
finally:
|
||||
service._busy.release()
|
||||
assert engine.db.get("SELECT COUNT(*) AS n FROM face_track WHERE session_id = ?", sid)["n"] == 1
|
||||
service.step() # o laço aplica o reset agendado antes do próximo bloco
|
||||
rows = engine.db.all("SELECT idx FROM face_track WHERE session_id = ?", sid)
|
||||
assert [r["idx"] for r in rows] == [0] # apagou e refez só o primeiro
|
||||
|
||||
|
||||
def test_backend_is_fixed_per_session():
|
||||
seen = []
|
||||
|
||||
class Store:
|
||||
def path(self, model_id):
|
||||
if model_id == "face_landmarker":
|
||||
raise FaceUnavailable("sem mediapipe")
|
||||
seen.append(model_id)
|
||||
raise FaceUnavailable("sem pesos do plano B")
|
||||
|
||||
service = FaceService.__new__(FaceService)
|
||||
service.store = Store()
|
||||
# Sessão que começou no MediaPipe: espera ele voltar, não troca para o OpenSeeFace no meio.
|
||||
with pytest.raises(FaceUnavailable, match="sem mediapipe"):
|
||||
service._default_tracker("mediapipe")
|
||||
assert seen == []
|
||||
# Sessão nova: o plano B só entra aqui.
|
||||
with pytest.raises(FaceUnavailable, match="plano B"):
|
||||
service._default_tracker(None)
|
||||
assert seen == ["osf_landmarks"]
|
||||
|
||||
|
||||
def test_session_backend_comes_from_the_series(env): # noqa: F811
|
||||
_client, engine = env
|
||||
asked = []
|
||||
|
||||
def factory(backend=None):
|
||||
asked.append(backend)
|
||||
return FakeTracker()
|
||||
service = make_service(engine, tracker_factory=factory)
|
||||
sid = seed_session(engine, duration=60)
|
||||
set_cam(engine, sid)
|
||||
service.step()
|
||||
service.step()
|
||||
assert asked == [None, "fake"]
|
||||
|
||||
|
||||
def test_crop_geometry_never_leaves_the_frame():
|
||||
for crop in ({"x": 0.95, "y": 0.9, "w": 0.3, "h": 0.4}, {"x": -0.1, "y": -0.2, "w": 1.5, "h": 1.5},
|
||||
{"x": 0.999, "y": 0.999, "w": 0.01, "h": 0.01}):
|
||||
(x, y, w, h), (ow, oh) = face_mod.crop_geometry(crop, (1280, 720))
|
||||
assert 0 <= x and 0 <= y and x + w <= 1280 and y + h <= 720 and w >= 2 and h >= 2
|
||||
assert x % 2 == y % 2 == w % 2 == h % 2 == 0 and ow >= 2 and oh >= 2
|
||||
|
||||
|
||||
def test_transient_detector_failure_is_not_saved_as_no_cam(env): # noqa: F811
|
||||
_client, engine = env
|
||||
service = make_service(engine)
|
||||
|
||||
def unavailable():
|
||||
raise FaceUnavailable("download do YuNet falhou")
|
||||
service._detector_factory = unavailable
|
||||
engine.judge.provider = "off"
|
||||
sid = seed_session(engine) # sessão 'processing' (não grava)
|
||||
engine.intel.maybe_detect_cam(session(engine, sid))
|
||||
assert session(engine, sid)["cam_json"] is None # nada permanente
|
||||
assert engine.intel._cam_retry_at[sid] > time.time()
|
||||
engine.intel.maybe_detect_cam(session(engine, sid)) # dentro da espera: nem tenta
|
||||
# Falha não passageira (poucos quadros) em sessão parada: grava com nova tentativa pelo relógio.
|
||||
engine.intel._cam_retry_at.clear()
|
||||
service._detector_factory = FakeDetector
|
||||
service._grabber = lambda *_a, **_k: None
|
||||
engine.intel.maybe_detect_cam(session(engine, sid))
|
||||
saved = json.loads(session(engine, sid)["cam_json"])
|
||||
assert saved["hasWebcam"] is False and saved["retryAt"] > time.time() and saved["attempts"] == 1
|
||||
engine.db.run("UPDATE sessions SET cam_json = ? WHERE id = ?", json.dumps(saved | {"retryAt": 0}), sid)
|
||||
service._grabber = lambda *_a, **_k: FakeFrame()
|
||||
engine.intel.maybe_detect_cam(session(engine, sid))
|
||||
assert json.loads(session(engine, sid)["cam_json"])["hasWebcam"] is True
|
||||
@@ -0,0 +1,318 @@
|
||||
"""Formato do corte (vertical 9:16 / horizontal 16:9), durações padrão novas (60–90 s, volta até 2 min) e tempo da
|
||||
legenda com fala rápida (pedidos do dono, 16/11/2026)."""
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
import shutil
|
||||
import sqlite3
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from app import db as db_module
|
||||
from app import editor, editor_render, layout, subtitles
|
||||
from app.scoring import ChatMessage, Word
|
||||
|
||||
from .test_editor import KEY, _lavfi_segments, api, make_project, validate # noqa: F401 - api é fixture
|
||||
|
||||
FFMPEG = shutil.which("ffmpeg")
|
||||
FFPROBE = shutil.which("ffprobe")
|
||||
HORIZONTAL = {"format": {"aspect": "horizontal"}}
|
||||
CAM = {"layout": {"cam": {"x": 0.02, "y": 0.45, "w": 0.2, "h": 0.25}}}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- configuração: format e duration
|
||||
def test_format_validate_and_merge():
|
||||
assert layout.DEFAULTS["format"] == {"aspect": "vertical"}
|
||||
assert layout.merge()["format"]["aspect"] == "vertical"
|
||||
assert layout.validate({"format": {"aspect": "horizontal"}}) == {"format": {"aspect": "horizontal"}}
|
||||
assert layout.validate({"format": {}}) == {"format": {}}
|
||||
for bad in ({"format": {"aspect": "quadrado"}}, {"format": "horizontal"}):
|
||||
with pytest.raises(layout.LayoutError):
|
||||
layout.validate(bad)
|
||||
# padrão ← canal ← sessão ← projeto: a camada de cima vence; sem `format` (config antiga) = vertical.
|
||||
cfg = layout.merge({"format": {"aspect": "horizontal"}}, {"caption": {"size": 90}})
|
||||
assert layout.aspect(cfg) == "horizontal" and layout.frame_size(cfg) == (1920, 1080)
|
||||
assert layout.aspect(layout.merge(cfg, {"format": {"aspect": "vertical"}})) == "vertical"
|
||||
assert layout.aspect({"layout": {}}) == "vertical" and layout.frame_size(layout.merge()) == (1080, 1920)
|
||||
|
||||
|
||||
def test_duration_defaults_and_limits():
|
||||
assert layout.DEFAULTS["duration"] == {"minS": 60, "maxS": 90, "backtrackS": 120}
|
||||
assert layout.validate({"duration": {"minS": 120, "maxS": 180, "backtrackS": 120}})["duration"]["minS"] == 120
|
||||
for bad in ({"minS": 121}, {"minS": 4}, {"maxS": 181}, {"maxS": 14}, {"backtrackS": 121}, {"minS": 90, "maxS": 90},
|
||||
{"minS": 100, "maxS": 90}):
|
||||
with pytest.raises(layout.LayoutError):
|
||||
layout.validate({"duration": bad})
|
||||
|
||||
|
||||
def test_settings_routes_carry_format(api): # noqa: F811
|
||||
client, engine, _root = api
|
||||
h = {"X-Service-Key": KEY}
|
||||
r = client.put("/v1/sessions/1/settings", headers=h, json={"format": {"aspect": "horizontal"}})
|
||||
assert r.status_code == 200, r.text
|
||||
body = r.json()
|
||||
assert body["own"] == {"format": {"aspect": "horizontal"}} and body["effective"]["format"]["aspect"] == "horizontal"
|
||||
assert body["defaults"]["format"]["aspect"] == "vertical" and body["defaults"]["duration"]["maxS"] == 90
|
||||
assert body["aspects"] == ["vertical", "horizontal"] and body["frames"]["horizontal"]["width"] == 1920
|
||||
assert client.put("/v1/sessions/1/settings", headers=h, json={"format": {"aspect": "x"}}).status_code == 400
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- layout horizontal
|
||||
def test_horizontal_layout_modes():
|
||||
plain = layout.merge(HORIZONTAL)
|
||||
for mode in ("auto", "blur", "cam_top", "game_only"):
|
||||
cfg = layout.merge(HORIZONTAL, CAM, {"layout": {"mode": mode}})
|
||||
assert layout.resolved_mode(cfg) == "full"
|
||||
chain = layout.layout_chain(cfg, "in", "out")
|
||||
assert "vstack" not in chain and "boxblur" not in chain and "pad=1920:1080" in chain # quadro inteiro
|
||||
cam_only = layout.merge(HORIZONTAL, CAM, {"layout": {"mode": "cam_only"}})
|
||||
chain = layout.layout_chain(cam_only, "in", "out")
|
||||
assert layout.resolved_mode(cam_only) == "cam_only" and "crop=iw*0.2:ih*0.25:iw*0.02:ih*0.45" in chain
|
||||
assert "crop=1920:1080" in chain # câmera preenche 1920×1080 sem distorcer
|
||||
# cam_only sem câmera marcada: quadro inteiro; região do jogo marcada: recorta e preenche.
|
||||
assert layout.resolved_mode(layout.merge(HORIZONTAL, {"layout": {"mode": "cam_only"}})) == "full"
|
||||
game = layout.merge(HORIZONTAL, {"layout": {"game": {"x": 0.1, "y": 0.1, "w": 0.8, "h": 0.8}}})
|
||||
assert "crop=iw*0.8:ih*0.8:iw*0.1:ih*0.1,scale=1920:1080:force_original_aspect_ratio=increase,crop=1920:1080" in \
|
||||
layout.layout_chain(game, "in", "out")
|
||||
# troca de layout por trecho (editor) também respeita o formato
|
||||
assert "crop=iw*0.2" in layout.layout_chain(layout.merge(HORIZONTAL, CAM), "in", "out", mode="cam_only")
|
||||
assert layout.layout_chain(plain, "in", "out").startswith("[in]scale=1920:1080:force_original_aspect_ratio=decrease")
|
||||
|
||||
|
||||
def test_horizontal_ass_positions_and_sizes(tmp_path):
|
||||
data = make_project(settings=HORIZONTAL, chat={"enabled": True, "x": 0.02, "y": 0.9, "width": 0.3, "lines": 3})
|
||||
p = validate(data, tmp_path)
|
||||
cfg = editor.effective_settings(layout.merge(), p)
|
||||
assert layout.aspect(cfg) == "horizontal"
|
||||
ass = editor_render.build_project_ass(p, cfg, "twitch.tv/x", chat=[ChatMessage(11.0, "KKKK", "ana")])
|
||||
assert "PlayResX: 2560" in ass and "PlayResY: 1440" in ass # quadro lógico (textos a 75 % no 1920×1080)
|
||||
assert "\\pos(1280,1224)" in ass # legenda automática: centro, 85 % da altura
|
||||
assert f"\\pos(1280,{int(1440 * 0.2)})" in ass # gancho (y relativo)
|
||||
assert f"\\an1\\pos({int(2560 * 0.02)},{int(1440 * 0.9)})" in ass # chat (x/y relativos)
|
||||
assert "m 0 0 l 2560 0 2560 12 0 12" in ass # barra de progresso na largura toda
|
||||
credit = next(line for line in ass.splitlines() if line.startswith("Style: Credit"))
|
||||
assert credit.endswith(",9,48,48,36,1") # crédito no canto superior direito
|
||||
graph = editor_render.build_filter(p, cfg, editor.pieces(p["cuts"]), 10.0, "e.ass", [], cover_input=1)
|
||||
assert "s=1920x1080" in graph and "[1:v]scale=1920:1080" in graph # zoom e capa no tamanho do formato
|
||||
# legenda com y escolhido: fração da altura do quadro lógico
|
||||
q = validate(make_project(settings={**HORIZONTAL, "caption": {"y": 0.5}}), tmp_path)
|
||||
assert "\\pos(1280,720)" in editor_render.build_project_ass(q, editor.effective_settings(layout.merge(), q), "")
|
||||
|
||||
|
||||
def _golden_values() -> dict:
|
||||
"""Mesmas entradas usadas para gravar tests/data/vertical_golden_sha256.json com o código de ANTES do formato."""
|
||||
cam = {"layout": {"cam": {"x": 0.02, "y": 0.45, "w": 0.2, "h": 0.25}, "game": {"x": 0.3, "y": 0.1, "w": 0.6, "h": 0.8}}}
|
||||
g = {}
|
||||
for base_name, base in (("nocam", {}), ("cam", cam)):
|
||||
for mode in layout.MODES:
|
||||
cfg = layout.merge(base, {"layout": {"mode": mode}})
|
||||
g[f"chain-{base_name}-{mode}"] = layout.layout_chain(cfg, "in", "out", ",setsar=1", "_0")
|
||||
g[f"vf-{base_name}-{mode}"] = layout.video_filter(cfg, "a.ass")
|
||||
g[f"capy-{base_name}-{mode}"] = layout.caption_y(cfg)
|
||||
return g, cam
|
||||
|
||||
|
||||
def test_vertical_output_is_unchanged(tmp_path):
|
||||
"""O vertical continua idêntico ao de antes do formato (filtergraph, legenda, textos, chat, capa)."""
|
||||
expected = json.loads((Path(__file__).parent / "data" / "vertical_golden_sha256.json").read_text(encoding="utf-8"))
|
||||
g, cam = _golden_values()
|
||||
p = validate(make_project(chat={"enabled": True, "lines": 3}), tmp_path)
|
||||
chat = [ChatMessage(11.0, "KKKKKK", "ana"), ChatMessage(13.0, "server chinês", "beto")]
|
||||
for base_name, base in (("nocam", {}), ("cam", cam)):
|
||||
for preset in editor.CAPTION_PRESETS:
|
||||
q = json.loads(json.dumps(p))
|
||||
q["captions"]["preset"] = preset
|
||||
g[f"ass-{base_name}-{preset}"] = editor_render.build_project_ass(
|
||||
q, editor.effective_settings(layout.merge(base), q), "twitch.tv/x", chat=chat)
|
||||
cfg = editor.effective_settings(layout.merge(base), p)
|
||||
g[f"filter-{base_name}"] = editor_render.build_filter(p, cfg, editor.pieces(p["cuts"]), 10.0, "e.ass", [], cover_input=1)
|
||||
words = [Word(1.0, 1.3, "olha"), Word(1.4, 1.8, "isso"), Word(1.9, 2.3, "aqui"), Word(3.5, 3.9, "caiu"), Word(4.0, 4.6, "mano")]
|
||||
g[f"subs-{base_name}"] = subtitles.build_ass(words, 0.5, 6.0, "twitch.tv/x", layout.merge(base))
|
||||
got = {k: hashlib.sha256(str(v).encode("utf-8")).hexdigest() for k, v in g.items()}
|
||||
assert set(got) == set(expected)
|
||||
assert [k for k in expected if got[k] != expected[k]] == []
|
||||
|
||||
|
||||
def test_old_project_without_format_stays_vertical(tmp_path):
|
||||
p = validate(make_project(settings={"caption": {"size": 90}}), tmp_path)
|
||||
assert "format" not in p["settings"]
|
||||
cfg = editor.effective_settings(layout.merge(), p)
|
||||
assert layout.aspect(cfg) == "vertical" and "PlayResY: 1920" in editor_render.build_project_ass(p, cfg, "")
|
||||
# o projeto escolhe o formato por corte, por cima do canal/sessão
|
||||
q = validate(make_project(settings={"format": {"aspect": "vertical"}}), tmp_path)
|
||||
assert layout.aspect(editor.effective_settings(layout.merge(HORIZONTAL), q)) == "vertical"
|
||||
with pytest.raises(editor.EditError):
|
||||
validate(make_project(settings={"format": {"aspect": "4:3"}}), tmp_path)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- render real
|
||||
def _dark_segment(folder: Path, seconds: int = 8) -> Path:
|
||||
"""Bloco de vídeo escuro (texto claro aparece com clareza) com tom de teste."""
|
||||
seg = folder / "dark.ts"
|
||||
subprocess.run([FFMPEG, "-v", "error", "-f", "lavfi", "-i", f"color=c=0x202020:size=640x360:rate=30:duration={seconds}",
|
||||
"-f", "lavfi", "-i", f"sine=frequency=440:duration={seconds}", "-c:v", "libx264", "-preset", "ultrafast",
|
||||
"-g", "15", "-c:a", "aac", "-shortest", str(seg)], check=True)
|
||||
return seg
|
||||
|
||||
|
||||
def _gray_frame(video: Path, at: float, w: int, h: int) -> bytes:
|
||||
return subprocess.run([FFMPEG, "-v", "error", "-ss", f"{at:.2f}", "-i", str(video), "-frames:v", "1", "-f", "rawvideo",
|
||||
"-pix_fmt", "gray", "-"], capture_output=True, check=True).stdout[: w * h]
|
||||
|
||||
|
||||
def _bright(frame: bytes, w: int, x0: float, x1: float, y0: float, y1: float, h: int) -> int:
|
||||
return sum(1 for y in range(int(y0 * h), int(y1 * h)) for x in range(int(x0 * w), int(x1 * w), 2)
|
||||
if frame[y * w + x] > 200)
|
||||
|
||||
|
||||
@pytest.mark.skipif(not (FFMPEG and FFPROBE), reason="FFmpeg não instalado")
|
||||
def test_real_horizontal_render(tmp_path):
|
||||
"""Render de verdade em 1920×1080: legenda, gancho, chat, zoom, barra, crédito e capa no início."""
|
||||
seg = _dark_segment(tmp_path)
|
||||
words = [{"s": 1.2 + i * 0.3, "e": 1.45 + i * 0.3, "w": w} for i, w in enumerate("olha isso aqui caiu mano".split())]
|
||||
data = make_project(source={"sessionId": 1, "lo": 0, "hi": 8}, settings=HORIZONTAL,
|
||||
cuts=[{"start": 1, "end": 4, "mode": None}, {"start": 4, "end": 7, "mode": "cam_only"}],
|
||||
overlays=[{"id": "hook", "kind": "hook", "text": "ELE NÃO ACREDITOU", "start": 0, "end": 2, "y": 0.2,
|
||||
"size": 70, "color": "#FFFFFF", "box": "#E11D48", "anim": "none"},
|
||||
{"id": "z", "kind": "zoom", "start": 5, "end": 6.5, "scale": 1.3, "x": 0.5, "y": 0.5, "ramp": 0.2}],
|
||||
captions={"enabled": True, "preset": "classic", "style": {}, "emphColor": "#22E36B", "words": words},
|
||||
cover={"enabled": True, "t": 2, "text": "CAPA", "atStart": True},
|
||||
chat={"enabled": True, "x": 0.02, "y": 0.6, "width": 0.3, "lines": 3, "size": 40})
|
||||
p = validate(data, tmp_path, duration=8.0)
|
||||
base = layout.merge(CAM)
|
||||
segments = [(seg, 0.0, 8.0)]
|
||||
cover = editor_render.render_cover(FFMPEG, segments, p, base, "twitch.tv/x", tmp_path / "cover.jpg")
|
||||
out = tmp_path / "out.mp4"
|
||||
editor_render.render_project(FFMPEG, FFPROBE, ["-c:v", "libx264", "-preset", "ultrafast"], segments, p, base, "twitch.tv/x",
|
||||
out, tmp_path, chat=[ChatMessage(1.5, "KKKK", "ana"), ChatMessage(5.0, "F", "beto")],
|
||||
cover_file=cover)
|
||||
probe = subprocess.run([FFPROBE, "-v", "error", "-show_entries", "format=duration:stream=width,height", "-of", "csv=p=0",
|
||||
str(out)], capture_output=True, text=True, check=True).stdout
|
||||
assert "1920,1080" in probe and abs(float(probe.strip().splitlines()[-1]) - 6.0) < 0.2
|
||||
cover_probe = subprocess.run([FFPROBE, "-v", "error", "-show_entries", "stream=width,height", "-of", "csv=p=0", str(cover)],
|
||||
capture_output=True, text=True, check=True).stdout
|
||||
assert cover_probe.strip() == "1920,1080"
|
||||
w, h = 1920, 1080
|
||||
frame = _gray_frame(out, 1.0, w, h) # 1 s de saída = 2 s da sessão: gancho, legenda e chat na tela
|
||||
assert _bright(frame, w, 0.25, 0.75, 0.15, 0.25, h) > 200 # gancho em cima
|
||||
assert _bright(frame, w, 0.25, 0.75, 0.80, 0.90, h) > 200 # legenda no terço de baixo
|
||||
assert _bright(frame, w, 0.0, 0.3, 0.50, 0.60, h) > 50 # chat à esquerda
|
||||
assert _bright(frame, w, 0.7, 1.0, 0.0, 0.08, h) > 50 # crédito no canto de cima à direita
|
||||
assert _bright(frame, w, 0.0, 1.0, 0.30, 0.45, h) < 50 # o meio do jogo fica limpo
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- aspect no corte + migração v8
|
||||
def test_migration_v8_marks_old_clips_vertical(tmp_path):
|
||||
path = tmp_path / "old.db"
|
||||
conn = sqlite3.connect(path)
|
||||
for script in db_module.SCHEMA[:7]:
|
||||
for statement in db_module._split(script):
|
||||
conn.execute(statement)
|
||||
conn.execute("PRAGMA user_version = 7")
|
||||
conn.execute("INSERT INTO sessions (id, platform, kind, url, status, dir, started_at) VALUES (1, 'twitch', 'live', 'u', 'done', 'd', 'x')")
|
||||
conn.execute("INSERT INTO clips (session_id, peak_s, start_s, end_s, score, source, status, created_at, updated_at) "
|
||||
"VALUES (1, 5, 0, 10, 1, 'chat', 'ready', 'x', 'x')")
|
||||
conn.commit()
|
||||
conn.close()
|
||||
database = db_module.Database(path)
|
||||
assert database.get("PRAGMA user_version")["user_version"] == len(db_module.SCHEMA) >= 8 # v9 (capture_json) em cima
|
||||
assert database.get("SELECT aspect FROM clips")["aspect"] == "vertical"
|
||||
with pytest.raises(sqlite3.IntegrityError):
|
||||
database.run("UPDATE clips SET aspect = 'quadrado'")
|
||||
database.close()
|
||||
|
||||
|
||||
@pytest.mark.skipif(not FFMPEG, reason="FFmpeg não instalado")
|
||||
def test_clip_reports_rendered_aspect(api): # noqa: F811
|
||||
client, engine, root = api
|
||||
h = {"X-Service-Key": KEY}
|
||||
assert client.get("/v1/clips/7", headers=h).json()["aspect"] == "vertical" # antes do render: padrão
|
||||
_lavfi_segments(root / "data" / "s1")
|
||||
client.put("/v1/sessions/1/settings", headers=h, json={"format": {"aspect": "horizontal"}})
|
||||
engine.db.run("UPDATE clips SET status = 'pending' WHERE id = 7")
|
||||
engine.render_pending()
|
||||
clip = client.get("/v1/clips/7", headers=h).json()
|
||||
assert clip["status"] == "ready", clip["error"]
|
||||
assert clip["aspect"] == "horizontal"
|
||||
assert any(c["aspect"] == "horizontal" for c in client.get("/v1/clips", headers=h).json()["clips"])
|
||||
probe = subprocess.run([FFPROBE or "ffprobe", "-v", "error", "-select_streams", "v", "-show_entries", "stream=width,height",
|
||||
"-of", "csv=p=0", str(root / clip["file"])], capture_output=True, text=True, check=True).stdout
|
||||
assert probe.strip() == "1920,1080"
|
||||
# Prévia real do começo com capa no início: a capa é gerada também para a prévia.
|
||||
project = client.get("/v1/clips/7/edit", headers=h).json()
|
||||
project["project"]["cover"]["atStart"] = True
|
||||
assert client.put("/v1/clips/7/edit", headers=h, json=project).status_code == 200
|
||||
prev = client.post("/v1/clips/7/preview-render", headers=h, json={"fromS": 0, "durationS": 2})
|
||||
assert prev.status_code == 200, prev.text
|
||||
assert (root / "output" / "clipper" / "1" / "edit-7" / "preview-cover.jpg").is_file()
|
||||
# O projeto escolhe o formato por corte: vertical por cima da sessão horizontal.
|
||||
project = client.get("/v1/clips/7/edit", headers=h).json()
|
||||
project["project"]["settings"] = {"format": {"aspect": "vertical"}}
|
||||
assert client.put("/v1/clips/7/edit", headers=h, json=project).status_code == 200
|
||||
client.post("/v1/clips/7/export", headers=h)
|
||||
engine.render_pending()
|
||||
assert client.get("/v1/clips/7", headers=h).json()["aspect"] == "vertical"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- legenda com fala rápida
|
||||
def _fast_words() -> list[Word]:
|
||||
"""~7 palavras/s, com sobreposição (fim depois do início da seguinte), duração zero e duas no mesmo instante."""
|
||||
out, t = [], 0.3
|
||||
for i, text in enumerate("e aí mano olha isso que ele fez cara não acredito vai vai vai pega ele agora sim kkkk".split()):
|
||||
dur = 0.0 if i % 5 == 3 else 0.22 # algumas de 0 s (Whisper)
|
||||
out.append(Word(round(t, 3), round(t + dur, 3), text))
|
||||
t += 0.14
|
||||
out.append(Word(out[-1].start, out[-1].start + 0.2, "boa")) # mesmo instante da anterior
|
||||
return out
|
||||
|
||||
|
||||
def _caption_events(ass: str) -> list[tuple[float, float]]:
|
||||
def ts(s: str) -> float:
|
||||
hh, mm, ss = s.split(":")
|
||||
return int(hh) * 3600 + int(mm) * 60 + float(ss)
|
||||
rows = [line.split(",") for line in ass.splitlines() if re.match(r"Dialogue: 0,.*,(Caption|Karaoke),", line)]
|
||||
return sorted((ts(r[1]), ts(r[2])) for r in rows)
|
||||
|
||||
|
||||
def test_fast_speech_captions_never_overlap_and_stay_in_sync(tmp_path):
|
||||
raw = _fast_words()
|
||||
clean = subtitles.clean_words(raw)
|
||||
assert all(b.start > a.start and a.end <= b.start + 1e-9 for a, b in zip(clean, clean[1:])) # ordem, sem sobreposição
|
||||
assert all(w.end - w.start > 0 for w in clean)
|
||||
assert subtitles.clean_words(clean) == clean # idempotente
|
||||
# só a palavra que começava junto com a anterior foi empurrada (e no máximo 40 ms)
|
||||
shifts = [round(c.start - r.start, 3) for r, c in zip(sorted(raw, key=lambda w: (w.start, w.end)), clean)]
|
||||
assert [s for s in shifts if s] == [0.04]
|
||||
blocks = subtitles.caption_blocks(raw, 3)
|
||||
assert all(len(g) <= 4 for g, _ in blocks) and any(len(g) == 4 for g, _ in blocks) # fala rápida: +1 palavra
|
||||
for (g1, end1), (g2, _) in zip(blocks, blocks[1:]):
|
||||
assert end1 <= g2[0].start # um bloco sai antes do próximo entrar
|
||||
|
||||
# Render do editor (todos os presets, nos dois formatos) e do worker: nenhum par de eventos ao mesmo tempo, e
|
||||
# cada bloco entra no início da sua 1ª palavra (no centésimo do ASS).
|
||||
words = [{"s": w.start + 10, "e": w.end + 10, "w": w.word} for w in raw]
|
||||
starts = {round(w.start, 2) for w in clean}
|
||||
for settings in ({}, HORIZONTAL):
|
||||
for preset in editor.CAPTION_PRESETS:
|
||||
p = validate(make_project(settings=settings, cuts=[{"start": 10, "end": 20, "mode": None}], overlays=[],
|
||||
captions={"enabled": True, "preset": preset, "style": {}, "emphColor": "#22E36B",
|
||||
"words": words}), tmp_path)
|
||||
events = _caption_events(editor_render.build_project_ass(p, editor.effective_settings(layout.merge(), p), ""))
|
||||
assert len(events) >= 5, preset
|
||||
assert all(b[0] >= a[1] - 1e-6 for a, b in zip(events, events[1:])), preset
|
||||
assert all(round(s, 2) in starts or any(abs(s - x) <= 0.011 for x in starts) for s, _ in events), preset
|
||||
events = _caption_events(subtitles.build_ass(raw, 0.0, 10.0, "", layout.merge(settings)))
|
||||
assert all(b[0] >= a[1] - 1e-6 for a, b in zip(events, events[1:]))
|
||||
|
||||
|
||||
def test_emphasis_and_highlight_survive_word_cleaning(tmp_path):
|
||||
words = [{"s": 11.0, "e": 11.3, "w": "olha"}, {"s": 11.0, "e": 11.2, "w": "isso", "emph": True},
|
||||
{"s": 11.25, "e": 11.25, "w": "aqui"}]
|
||||
p = validate(make_project(cuts=[{"start": 10, "end": 15, "mode": None}], overlays=[],
|
||||
captions={"enabled": True, "preset": "classic", "style": {}, "emphColor": "#22E36B", "words": words}),
|
||||
tmp_path)
|
||||
ass = editor_render.build_project_ass(p, editor.effective_settings(layout.merge(), p), "")
|
||||
assert "&H6BE322&" in ass # ênfase ainda casada com a palavra certa depois do saneamento
|
||||
assert len(_caption_events(ass)) == 3
|
||||
@@ -0,0 +1,54 @@
|
||||
"""Hashtags da legenda: canal e jogo fixos (perfil), momento da IA, sem repetidas, até 8."""
|
||||
|
||||
from app.hashtags import build_caption, compose, fold, split_hashtags, to_tag
|
||||
from app.intel import clean_profile
|
||||
from app.judge import _clean
|
||||
|
||||
|
||||
def test_to_tag_normalizes_names_and_phrases():
|
||||
assert to_tag("ROB RUN") == "#ROBRUN"
|
||||
assert to_tag("#Lamborghini") == "#Lamborghini"
|
||||
assert to_tag("perseguição policial") == "#PerseguiçãoPolicial"
|
||||
assert to_tag("Call of Duty: Warzone") == "#CallOfDutyWarzone"
|
||||
assert to_tag(" ") is None and to_tag("#123") is None and to_tag("!!!") is None
|
||||
|
||||
|
||||
def test_compose_puts_channel_then_game_then_moment_without_duplicates():
|
||||
profile = {"hashtags": ["#ROBRUN", "#RobRunGame", "#jogodeassalto", "#quarta"]}
|
||||
tags = compose("skipnho", "ROB RUN", profile, ["assalto ao banco", "RobRun", "Clã", "cla", "sorteio", "extra", "mais"])
|
||||
# Jogo: até 3 do perfil; momento: até 4; "RobRun"/"cla" repetem (sem maiúscula/acento) e saem.
|
||||
assert tags == ["#skipnho", "#ROBRUN", "#RobRunGame", "#jogodeassalto", "#AssaltoAoBanco", "#Clã"]
|
||||
assert fold("#Clã") == fold("#CLA")
|
||||
|
||||
|
||||
def test_compose_without_profile_uses_game_name_and_caps_at_eight():
|
||||
assert compose("skipnho", "ROB RUN", None, []) == ["#skipnho", "#ROBRUN"]
|
||||
many = compose("canal", "Jogo", {"hashtags": ["#a1", "#b2", "#c3"]}, [f"tag{i}" for i in range(10)])
|
||||
assert len(many) == 8
|
||||
|
||||
|
||||
def test_caption_layout_text_tags_credit():
|
||||
text, inline = split_hashtags("O clã vai ao banco #skipnho e o plano dá errado. #assalto")
|
||||
assert text == "O clã vai ao banco e o plano dá errado." and inline == ["#skipnho", "#assalto"]
|
||||
caption = build_caption(text, ["#skipnho", "#ROBRUN"], "🎥 Créditos: https://twitch.tv/skipnho")
|
||||
assert caption == "O clã vai ao banco e o plano dá errado.\n\n#skipnho #ROBRUN\n\n🎥 Créditos: https://twitch.tv/skipnho"
|
||||
assert build_caption("", [], "🎥 Créditos: x") == "🎥 Créditos: x"
|
||||
|
||||
|
||||
def test_profile_hashtags_are_cleaned():
|
||||
profile = clean_profile({"name": "ROB RUN", "hashtags": ["rob run", "#ROBRUN", "#robrun", "#123", "GTA RP"]})
|
||||
# "rob run" vira "#RobRun"; "#ROBRUN" e "#robrun" são a mesma tag (sem maiúscula) e saem.
|
||||
assert profile["hashtags"] == ["#RobRun", "#GTARP"]
|
||||
|
||||
|
||||
def test_api_accepts_hashtags_in_profile_edit_and_section_chat():
|
||||
from app.main import GameProfileIn, GameRefineIn
|
||||
|
||||
assert GameProfileIn(hashtags=["#ROBRUN"]).hashtags == ["#ROBRUN"]
|
||||
assert GameRefineIn(instruction="pesquise as hashtags", section="hashtags").section == "hashtags"
|
||||
|
||||
|
||||
def test_verdict_reads_moment_hashtags_and_tolerates_old_answers():
|
||||
base = {"keep": True, "score": 8, "start_s": 10, "end_s": 80, "title": "t", "caption": "c", "reason": "r"}
|
||||
assert _clean({**base, "hashtags": ["assalto", " ", "Lamborghini"]}, 10, 80, "m", 0, 200, 30, 90).hashtags == ("assalto", "Lamborghini")
|
||||
assert _clean(base, 10, 80, "m", 0, 200, 30, 90).hashtags == ()
|
||||
@@ -0,0 +1,225 @@
|
||||
import json
|
||||
|
||||
import pytest
|
||||
|
||||
from app import layout
|
||||
from app.emotes import EmoteCatalog, extract, message_bonus, parse_twitch_tag
|
||||
from app.judge import Judge
|
||||
from app.scoring import ChatMessage, find_moments
|
||||
from tests.test_sources_and_api import KEY, auth, env, seed_session # noqa: F401 - fixture reaproveitada
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- emotes
|
||||
def test_parse_twitch_emote_tag_uses_codepoints():
|
||||
text = "😂 Kappa oi LUL"
|
||||
assert parse_twitch_tag("25:2-6/425618:11-13", text) == ["Kappa", "LUL"]
|
||||
assert parse_twitch_tag("", text) == []
|
||||
assert parse_twitch_tag("25:90-99", text) == [] # posição fora do texto não quebra
|
||||
|
||||
|
||||
def test_extract_third_party_and_emoji():
|
||||
found = extract("PepeLaugh mano 😂 Kappa", ["Kappa"], {"PepeLaugh": "bttv", "mano": "7tv"})
|
||||
assert ("Kappa", "twitch") in found and ("PepeLaugh", "bttv") in found and ("😂", "emoji") in found
|
||||
|
||||
|
||||
def test_message_bonus_learned_and_clamped():
|
||||
assert message_bonus([], {}) == 0
|
||||
assert message_bonus(["skpPog"], {}) == pytest.approx(0.4)
|
||||
assert message_bonus(["skpPog"], {"skpPog": 2.0}) == pytest.approx(2.4)
|
||||
assert message_bonus(["a", "b"], {"a": 3, "b": 3}) == 3.0
|
||||
|
||||
|
||||
def test_catalog_tolerates_failing_sources():
|
||||
def fetch(url):
|
||||
if "7tv" in url:
|
||||
raise TimeoutError
|
||||
if "betterttv" in url and "users" in url:
|
||||
return {"channelEmotes": [{"code": "skpPog"}], "sharedEmotes": [{"code": "PepeLaugh"}]}
|
||||
if "betterttv" in url:
|
||||
return [{"code": "FeelsGoodMan"}]
|
||||
return None
|
||||
catalog = EmoteCatalog(fetch)
|
||||
names = catalog.names("123")
|
||||
assert names["skpPog"] == "bttv" and "FeelsGoodMan" in names
|
||||
assert catalog.cached("123")["PepeLaugh"] == "bttv"
|
||||
assert catalog.cached("999").get("skpPog") is None
|
||||
|
||||
|
||||
def test_emote_only_reactions_make_a_peak_in_small_chat():
|
||||
# Live pequena: ninguém escreve "kkkk", só manda emote do canal.
|
||||
calm = [ChatMessage(t * 7.0, "salve") for t in range(130)]
|
||||
burst = [ChatMessage(500 + i, "skpPog", emotes=("skpPog",), bonus=0.4) for i in range(5)]
|
||||
moments = [m for m in find_moments(900, calm + burst, [], []) if m.source == "chat"]
|
||||
assert len(moments) == 1 and moments[0].reasons["emotes"] == {"skpPog": 5}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- layout
|
||||
def test_layout_validate_and_merge():
|
||||
own = layout.validate({"layout": {"mode": "cam_top", "cam": {"x": 0.01, "y": 0.46, "w": 0.2, "h": 0.3}},
|
||||
"caption": {"color": "#ffffff", "highlight": "#00ff88", "size": 90}})
|
||||
cfg = layout.merge({"caption": {"size": 70}}, own)
|
||||
assert cfg["caption"]["size"] == 90 and cfg["caption"]["highlight"] == "#00FF88"
|
||||
assert layout.resolved_mode(cfg) == "cam_top"
|
||||
for bad in ({"layout": {"mode": "x"}}, {"layout": {"cam": {"x": 0.9, "y": 0, "w": 0.5, "h": 0.3}}},
|
||||
{"caption": {"color": "red"}}, {"duration": {"minS": 60, "maxS": 30}}):
|
||||
with pytest.raises(layout.LayoutError):
|
||||
layout.validate(bad)
|
||||
|
||||
|
||||
def test_layout_filters():
|
||||
cam = layout.merge({"layout": {"cam": {"x": 0, "y": 0.5, "w": 0.2, "h": 0.3}}})
|
||||
f = layout.video_filter(cam, "c.ass")
|
||||
assert "vstack" in f and "ass=c.ass" in f and "crop=iw*0.2:ih*0.3:iw*0:ih*0.5" in f
|
||||
assert layout.caption_y(cam) == layout.cam_panel_height(cam) + 40 # legenda na emenda câmera/jogo
|
||||
assert "boxblur" in layout.video_filter(layout.merge(), None) # sem câmera: layout desfocado
|
||||
assert layout.ass_color("#FFE500") == "&H0000E5FF&" and layout.ass_inline_color("#FFE500") == "&H00E5FF&"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- API + motor
|
||||
def test_settings_api_channel_and_session(env): # noqa: F811
|
||||
client, engine = env
|
||||
client.post("/v1/channels", json={"url": "https://www.twitch.tv/alanzoka"}, headers=auth())
|
||||
r = client.put("/v1/channels/twitch-alanzoka/settings",
|
||||
json={"layout": {"cam": {"x": 0.7, "y": 0.0, "w": 0.3, "h": 0.3}}}, headers=auth())
|
||||
assert r.status_code == 200 and r.json()["effective"]["layout"]["cam"]["x"] == 0.7
|
||||
assert client.put("/v1/channels/twitch-alanzoka/settings", json={"caption": {"size": 999}}, headers=auth()).status_code == 400
|
||||
sid = seed_session(engine)
|
||||
engine.db.run("UPDATE sessions SET channel_id = 'twitch-alanzoka' WHERE id = ?", sid)
|
||||
r = client.put(f"/v1/sessions/{sid}/settings", json={"caption": {"highlight": "#FF0000"}}, headers=auth())
|
||||
eff = r.json()["effective"]
|
||||
assert eff["caption"]["highlight"] == "#FF0000" and eff["layout"]["cam"]["x"] == 0.7 # sessão sobre o canal
|
||||
|
||||
|
||||
def test_user_approval_teaches_emote_weights(env): # noqa: F811
|
||||
client, engine = env
|
||||
sid = seed_session(engine)
|
||||
wall = engine.db.get("SELECT wall_end FROM segments WHERE session_id = ? AND idx = 10", sid)["wall_end"]
|
||||
engine.db.many("INSERT INTO chat (session_id, wall, user, text, emotes) VALUES (?, ?, 'u', 'skpPog', ?)",
|
||||
[(sid, wall - 28 + i, json.dumps(["skpPog"])) for i in range(4)])
|
||||
engine.db.run("INSERT INTO emotes (channel_key, name, source, uses, weight, first_seen, last_seen)"
|
||||
" VALUES ('twitch-alanzoka', 'skpPog', 'bttv', 4, 0, 'x', 'x')")
|
||||
engine.db.run("INSERT INTO clips (session_id, peak_s, start_s, end_s, score, source, status, created_at, updated_at)"
|
||||
" VALUES (?, 304, 290, 320, 5, 'chat', 'ready', 'x', 'x')", sid)
|
||||
clip_id = engine.db.get("SELECT id FROM clips WHERE session_id = ?", sid)["id"]
|
||||
client.patch(f"/v1/clips/{clip_id}", json={"status": "approved"}, headers=auth())
|
||||
client.patch(f"/v1/clips/{clip_id}", json={"status": "approved"}, headers=auth()) # repetir não soma de novo
|
||||
weight = engine.db.get("SELECT weight FROM emotes WHERE name = 'skpPog'")["weight"]
|
||||
assert weight == pytest.approx(0.3)
|
||||
emotes = client.get("/v1/emotes?channel=twitch-alanzoka", headers=auth()).json()["emotes"]
|
||||
assert emotes[0]["name"] == "skpPog" and emotes[0]["weight"] == 0.3
|
||||
|
||||
|
||||
class ScanJudge(Judge):
|
||||
def __init__(self):
|
||||
super().__init__("codex", "fake", __import__("pathlib").Path("."))
|
||||
self.prompts = []
|
||||
|
||||
def scan(self, prompt, images):
|
||||
self.prompts.append(prompt)
|
||||
return {"screen_game": "ROB RUN", "has_webcam": True, "summary": "tiroteio na base",
|
||||
"moments": [{"score": 8, "start_s": 100, "end_s": 140, "title": "Emboscada", "caption": "c #robrun",
|
||||
"reason": "virada"},
|
||||
{"score": 3, "start_s": 150, "end_s": 175, "title": "fraco", "caption": "", "reason": "morno"}]}
|
||||
|
||||
|
||||
def test_scan_creates_clips_without_chat_peak(env): # noqa: F811
|
||||
client, engine = env
|
||||
engine.judge = ScanJudge()
|
||||
engine.intel.opts["vision"] = False # sem ffmpeg nos testes
|
||||
sid = seed_session(engine)
|
||||
engine.db.run("UPDATE sessions SET status = 'recording', game = 'ROB RUN' WHERE id = ?", sid)
|
||||
session = engine.db.get("SELECT * FROM sessions WHERE id = ?", sid)
|
||||
assert engine.intel.scan_session(session) == 1 # a proposta nota 3 nem vai aos juízes
|
||||
clips = client.get(f"/v1/clips?session={sid}", headers=auth()).json()["clips"]
|
||||
assert len(clips) == 1 and clips[0]["status"] == "candidate" and clips[0]["source"] == "ai"
|
||||
assert clips[0]["reasons"]["proposalTitle"] == "Emboscada"
|
||||
s2 = client.get(f"/v1/sessions/{sid}", headers=auth()).json()
|
||||
assert s2["scannedUntilS"] == 180 and s2["screenGame"] == "ROB RUN" and s2["memory"][0]["summary"] == "tiroteio na base"
|
||||
# janela seguinte também é varrida; a anterior não é repetida
|
||||
session = engine.db.get("SELECT * FROM sessions WHERE id = ?", sid)
|
||||
engine.intel.scan_session(session)
|
||||
assert "Janela nova: 180s a 360s" in engine.judge.prompts[-1]
|
||||
|
||||
|
||||
def test_game_override_and_chat_ingest(env): # noqa: F811
|
||||
client, engine = env
|
||||
sid = seed_session(engine)
|
||||
r = client.put(f"/v1/sessions/{sid}/game", json={"name": "GTA VI"}, headers=auth())
|
||||
assert r.json()["game"] == "GTA VI" and r.json()["gameSource"] == "user"
|
||||
assert client.get("/v1/games", headers=auth()).json()["games"][0]["status"] == "pending"
|
||||
engine.intel.ingest_chat(sid, "twitch-alanzoka", None, [(20000.0, "u", "Kappa kkk 😂", ["Kappa"])])
|
||||
row = engine.db.get("SELECT emotes FROM chat WHERE wall = 20000.0")
|
||||
assert json.loads(row["emotes"]) == ["Kappa", "😂"]
|
||||
uses = {r["name"]: r["uses"] for r in engine.db.all("SELECT name, uses FROM emotes")}
|
||||
assert uses == {"Kappa": 1, "😂": 1}
|
||||
|
||||
|
||||
def test_resume_and_finish_interrupted_session(env): # noqa: F811
|
||||
client, engine = env
|
||||
sid = seed_session(engine)
|
||||
engine.db.run("UPDATE sessions SET status = 'interrupted' WHERE id = ?", sid)
|
||||
engine.check_live = lambda url: (False, "") # canal offline: não dá para retomar
|
||||
r = client.post(f"/v1/sessions/{sid}/resume", headers=auth())
|
||||
assert r.status_code == 400 and "não está ao vivo" in r.json()["error"]
|
||||
started = []
|
||||
engine.check_live = lambda url: (True, "título")
|
||||
|
||||
class FakeCapture:
|
||||
def __init__(self, eng, session_id, source, workdir, start_idx=0):
|
||||
started.append(start_idx)
|
||||
self.chat = None
|
||||
|
||||
def start(self):
|
||||
pass
|
||||
|
||||
import app.worker as worker_module
|
||||
original = worker_module.Capture
|
||||
worker_module.Capture = FakeCapture
|
||||
try:
|
||||
r = client.post(f"/v1/sessions/{sid}/resume", headers=auth())
|
||||
finally:
|
||||
worker_module.Capture = original
|
||||
assert r.status_code == 200 and r.json()["status"] == "starting"
|
||||
assert started == [20] # 20 blocos já existiam (0–19): continua a numeração
|
||||
engine.captures.clear()
|
||||
engine.db.run("UPDATE sessions SET status = 'interrupted' WHERE id = ?", sid)
|
||||
r = client.post(f"/v1/sessions/{sid}/finish", headers=auth())
|
||||
assert r.json()["status"] == "processing"
|
||||
|
||||
|
||||
def test_startup_marks_recording_as_interrupted_and_remembers(tmp_path):
|
||||
from app.db import Database
|
||||
db = Database(tmp_path / "c.db")
|
||||
db.run("INSERT INTO sessions (platform, kind, url, status, chat_status, dir, started_at) VALUES"
|
||||
" ('twitch', 'live', 'https://www.twitch.tv/x', 'recording', 'connected', '', 'x')")
|
||||
db.run("INSERT INTO sessions (platform, kind, url, status, chat_status, dir, started_at) VALUES"
|
||||
" ('twitch', 'live', 'https://www.twitch.tv/y', 'interrupted', 'connected', '', 'x')")
|
||||
db.close()
|
||||
db = Database(tmp_path / "c.db")
|
||||
rows = db.all("SELECT status, chat_status FROM sessions ORDER BY id")
|
||||
assert db.interrupted_on_start == [1]
|
||||
assert rows == [{"status": "interrupted", "chat_status": "off"}, {"status": "interrupted", "chat_status": "off"}]
|
||||
|
||||
|
||||
def test_confirmed_game_silences_screen_doubt(env): # noqa: F811
|
||||
client, engine = env
|
||||
sid = seed_session(engine)
|
||||
engine.db.run("UPDATE sessions SET game = 'ROB RUN', game_source = 'platform', screen_game = 'Call of Duty: Warzone' WHERE id = ?", sid)
|
||||
session = engine.db.get("SELECT * FROM sessions WHERE id = ?", sid)
|
||||
assert "Warzone" in engine.intel.context(session) # sem confirmação: a dúvida vai para os juízes
|
||||
client.put(f"/v1/sessions/{sid}/game", json={"name": "ROB RUN"}, headers=auth())
|
||||
session = engine.db.get("SELECT * FROM sessions WHERE id = ?", sid)
|
||||
ctx = engine.intel.context(session)
|
||||
assert "CONFIRMADO" in ctx and "visto na tela" not in ctx and "Call of Duty" not in ctx
|
||||
engine.check_meta = lambda url: {"title": "", "category": "Grand Theft Auto V", "author": ""}
|
||||
engine.intel.check_game(session, force=True) # checagem automática não troca jogo confirmado
|
||||
assert engine.db.get("SELECT game_source FROM sessions WHERE id = ?", sid)["game_source"] == "user"
|
||||
|
||||
|
||||
def test_research_pending_is_quiet_with_ai_off(env): # noqa: F811
|
||||
"""IA desligada: o jogo fica 'pending' sem erro (antes o laço de contexto logava um WARNING a cada 30 s)."""
|
||||
_client, engine = env
|
||||
engine.judge = Judge("off", "", engine.settings.data_dir / "judge")
|
||||
engine.db.run("INSERT INTO games (id, name, status) VALUES ('rob-run', 'ROB RUN', 'pending')")
|
||||
engine.intel.research_pending()
|
||||
assert engine.db.get("SELECT status FROM games WHERE id = 'rob-run'")["status"] == "pending"
|
||||
@@ -0,0 +1,353 @@
|
||||
import json
|
||||
import random
|
||||
|
||||
import pytest
|
||||
|
||||
from app.reaction import (
|
||||
FaceSample, FaceSecond, ReactionParams, label, locate_cam, per_second, reaction_moments, reaction_signal,
|
||||
seconds_from_json, seconds_to_json, summarize,
|
||||
)
|
||||
|
||||
FPS = 6
|
||||
|
||||
|
||||
def neutral_blend(rng: random.Random, smile: float = 0.05) -> dict[str, float]:
|
||||
"""Rosto parado: blendshapes baixos com ruído (fala/tique), sorriso no nível pedido."""
|
||||
n = lambda base: max(0.0, min(1.0, base + rng.uniform(-0.03, 0.03))) # noqa: E731
|
||||
return {
|
||||
"mouthSmileLeft": n(smile), "mouthSmileRight": n(smile), "jawOpen": n(0.08),
|
||||
"eyeWideLeft": n(0.05), "eyeWideRight": n(0.05), "browInnerUp": n(0.05),
|
||||
"browOuterUpLeft": n(0.04), "browOuterUpRight": n(0.04), "browDownLeft": n(0.05), "browDownRight": n(0.05),
|
||||
"eyeBlinkLeft": n(0.1), "eyeBlinkRight": n(0.1),
|
||||
}
|
||||
|
||||
|
||||
def track(duration: int, seed: int = 1, smile: float = 0.05, events: dict | None = None,
|
||||
absent: range | None = None) -> list[FaceSample]:
|
||||
"""Quadros a 6 qps. `events`: {segundo: função(blend, rng) → (blend, dx, dy)} para injetar reações."""
|
||||
rng = random.Random(seed)
|
||||
events = events or {}
|
||||
out = []
|
||||
for i in range(duration * FPS):
|
||||
t = i / FPS
|
||||
if absent is not None and int(t) in absent:
|
||||
out.append(FaceSample(t, False))
|
||||
continue
|
||||
blend, dx, dy = neutral_blend(rng, smile), 0.0, 0.0
|
||||
if int(t) in events:
|
||||
blend, dx, dy = events[int(t)](blend, rng)
|
||||
cx = 0.5 + rng.uniform(-0.005, 0.005) + dx
|
||||
cy = 0.4 + rng.uniform(-0.005, 0.005) + dy
|
||||
out.append(FaceSample(t, True, cx, cy, 0.3, blend))
|
||||
return out
|
||||
|
||||
|
||||
def laugh(blend, rng):
|
||||
blend |= {"mouthSmileLeft": 0.9, "mouthSmileRight": 0.85, "jawOpen": 0.7}
|
||||
return blend, 0.0, rng.uniform(-0.02, 0.02)
|
||||
|
||||
|
||||
def scream(blend, rng):
|
||||
blend |= {"mouthSmileLeft": 0.02, "mouthSmileRight": 0.02, "jawOpen": 0.85}
|
||||
return blend, 0.0, 0.0
|
||||
|
||||
|
||||
def startle(blend, rng):
|
||||
blend |= {"eyeWideLeft": 0.8, "eyeWideRight": 0.8, "browInnerUp": 0.7, "browOuterUpLeft": 0.6,
|
||||
"browOuterUpRight": 0.6}
|
||||
return blend, rng.choice([-1, 1]) * 0.1, rng.uniform(-0.08, 0.08)
|
||||
|
||||
|
||||
# --- série e sinal ------------------------------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_per_second_shapes_and_none_without_face():
|
||||
seconds = per_second(track(10, absent=range(4, 6)), 10)
|
||||
assert [s.t for s in seconds] == list(range(10))
|
||||
assert seconds[0].present == 1.0 and 0.0 <= seconds[0].smile <= 0.1 and seconds[0].size == 0.3
|
||||
assert seconds[4].present == 0.0 and seconds[4].smile is None and seconds[4].cx is None
|
||||
assert seconds[0].motion is not None and seconds[0].motion < 0.5
|
||||
|
||||
|
||||
def test_json_roundtrip_is_compact_and_rounded():
|
||||
seconds = per_second(track(5, absent=range(2, 3)), 5)
|
||||
data = seconds_to_json(seconds)
|
||||
assert "smile" not in data[2] and data[2]["present"] == 0.0
|
||||
assert all(len(str(v).split(".")[-1]) <= 3 for d in data for v in d.values() if isinstance(v, float))
|
||||
back = seconds_from_json(json.loads(json.dumps(data)))
|
||||
assert back[2].smile is None and abs(back[0].cx - seconds[0].cx) < 1e-3
|
||||
|
||||
|
||||
def test_neutral_with_noise_has_no_peak():
|
||||
seconds = per_second(track(300, seed=3), 300)
|
||||
assert reaction_moments(seconds) == []
|
||||
signal = reaction_signal(seconds)
|
||||
assert max(v for v in signal if v is not None) < ReactionParams().threshold
|
||||
|
||||
|
||||
def test_laugh_is_a_peak_with_right_label_and_onset():
|
||||
events = {t: laugh for t in range(200, 205)}
|
||||
seconds = per_second(track(300, events=events), 300)
|
||||
moments = reaction_moments(seconds)
|
||||
assert len(moments) == 1
|
||||
m = moments[0]
|
||||
assert m.label == "risada" and 200 <= m.peak_s <= 204
|
||||
assert m.onset_s == 200 # a reação começa exatamente onde o evento começou
|
||||
assert m.end_s >= 204 and m.strong
|
||||
|
||||
|
||||
def test_constant_smiling_streamer_is_not_a_false_positive():
|
||||
# Streamer de "neutro sorridente": o sorriso alto é o normal dele, não reação.
|
||||
seconds = per_second(track(300, seed=5, smile=0.65), 300)
|
||||
assert reaction_moments(seconds) == []
|
||||
# E uma risada de verdade nesse mesmo streamer ainda aparece (pela boca).
|
||||
events = {t: (lambda b, r: (b | {"jawOpen": 0.7, "mouthSmileLeft": 0.8, "mouthSmileRight": 0.8}, 0.0, 0.0))
|
||||
for t in range(150, 154)}
|
||||
moments = reaction_moments(per_second(track(300, seed=5, smile=0.65, events=events), 300))
|
||||
assert [m.label for m in moments] == ["risada"]
|
||||
|
||||
|
||||
def test_scream_versus_laugh():
|
||||
events = {t: scream for t in range(100, 103)} | {t: laugh for t in range(200, 203)}
|
||||
moments = reaction_moments(per_second(track(300, events=events), 300))
|
||||
assert [(m.label, 100 <= m.peak_s <= 102 or 200 <= m.peak_s <= 202) for m in moments] == [
|
||||
("grito", True), ("risada", True)]
|
||||
|
||||
|
||||
def test_startle_versus_shock():
|
||||
still = lambda b, r: (startle(b, r)[0], 0.0, 0.0) # noqa: E731 — olhos/sobrancelha sem pulo da cabeça
|
||||
events = {t: startle for t in range(100, 102)} | {t: still for t in range(200, 202)}
|
||||
labels = [m.label for m in reaction_moments(per_second(track(300, events=events), 300))]
|
||||
assert labels == ["susto", "choque"]
|
||||
|
||||
|
||||
def test_seconds_without_face_are_none_and_never_peak():
|
||||
# Rosto some exatamente na hora em que haveria uma "risada": não pode virar pico.
|
||||
events = {t: laugh for t in range(150, 155)}
|
||||
seconds = per_second(track(300, events=events, absent=range(148, 158)), 300)
|
||||
signal = reaction_signal(seconds)
|
||||
assert all(signal[t] is None for t in range(148, 158))
|
||||
assert reaction_moments(seconds) == []
|
||||
|
||||
|
||||
def test_label_without_z_uses_absolute_thresholds():
|
||||
s = FaceSecond(0, 1.0, 0.5, 0.4, 0.3, smile=0.8, jaw=0.7, surprise=0.1, frown=0.0, blink=0.1, motion=0.1)
|
||||
assert label(s) == "risada"
|
||||
s.smile = 0.0
|
||||
assert label(s) == "grito"
|
||||
assert label(FaceSecond(1, 0.0)) == "neutro"
|
||||
assert label(FaceSecond(2, 1.0, smile=0.0, jaw=0.0, surprise=0.0, frown=0.6, motion=0.0)) == "raiva"
|
||||
|
||||
|
||||
def test_summarize_text_for_the_judge():
|
||||
events = {t: laugh for t in range(200, 204)} | {t: startle for t in range(215, 217)}
|
||||
seconds = per_second(track(300, events=events), 300)
|
||||
text = summarize(seconds, 190, 230)
|
||||
assert text.startswith("risada forte em 1") and "susto" in text and "; " in text
|
||||
assert summarize(seconds, 20, 60) == "sem reação marcante no rosto"
|
||||
gone = per_second(track(100, absent=range(0, 100)), 100)
|
||||
assert summarize(gone, 0, 50) == "rosto do streamer não aparece no trecho"
|
||||
|
||||
|
||||
# --- câmera -------------------------------------------------------------------------------------------------------
|
||||
|
||||
W, H = 1920, 1080
|
||||
|
||||
|
||||
def cam_face(rng: random.Random) -> tuple[float, float, float, float, float]:
|
||||
"""Rosto da câmera no canto inferior esquerdo, com tremida de poucos pixels."""
|
||||
return (120 + rng.uniform(-4, 4), 700 + rng.uniform(-4, 4), 110, 130, 0.9)
|
||||
|
||||
|
||||
def inside_unit(rect: dict) -> bool:
|
||||
return (0 <= rect["x"] <= 1 and 0 <= rect["y"] <= 1 and rect["w"] > 0 and rect["h"] > 0
|
||||
and rect["x"] + rect["w"] <= 1 + 1e-9 and rect["y"] + rect["h"] <= 1 + 1e-9)
|
||||
|
||||
|
||||
def test_locate_cam_stable_corner():
|
||||
rng = random.Random(1)
|
||||
frames = [[cam_face(rng)] for _ in range(12)]
|
||||
result = locate_cam(frames, W, H)
|
||||
assert result["hasWebcam"] and not result["fullFrame"] and result["confidence"] > 0.7
|
||||
cam, face = result["cam"], result["faceRect"]
|
||||
assert inside_unit(cam) and inside_unit(face)
|
||||
# O rosto fica dentro do retângulo da câmera, que está no canto inferior esquerdo.
|
||||
assert cam["x"] <= face["x"] and cam["y"] <= face["y"]
|
||||
assert face["x"] + face["w"] <= cam["x"] + cam["w"] and face["y"] + face["h"] <= cam["y"] + cam["h"]
|
||||
assert cam["x"] < 0.1 and cam["y"] > 0.4 and cam["w"] < 0.3
|
||||
|
||||
|
||||
def test_locate_cam_ignores_cutscene_face():
|
||||
rng = random.Random(2)
|
||||
frames = [[cam_face(rng)] for _ in range(12)]
|
||||
frames[3].append((900, 300, 200, 240, 0.95)) # rosto do personagem na cutscene, só em 2 de 12 quadros
|
||||
frames[4].append((905, 302, 198, 238, 0.95))
|
||||
result = locate_cam(frames, W, H)
|
||||
assert result["hasWebcam"] and result["faceRect"]["x"] < 0.1
|
||||
# Só a cutscene (sem câmera): nada.
|
||||
only = [[] for _ in range(12)]
|
||||
only[3], only[4] = [(900, 300, 200, 240, 0.95)], [(905, 302, 198, 238, 0.95)]
|
||||
assert locate_cam(only, W, H)["hasWebcam"] is False
|
||||
|
||||
|
||||
def test_locate_cam_full_frame():
|
||||
rng = random.Random(3)
|
||||
frames = [[(760 + rng.uniform(-10, 10), 250, 420, 520, 0.95)] for _ in range(10)]
|
||||
result = locate_cam(frames, W, H)
|
||||
assert result["hasWebcam"] and result["fullFrame"] and result["cam"] == {"x": 0, "y": 0, "w": 1, "h": 1}
|
||||
|
||||
|
||||
def test_locate_cam_no_face():
|
||||
result = locate_cam([[] for _ in range(12)], W, H)
|
||||
assert result == {"hasWebcam": False, "cam": None, "faceRect": None, "confidence": 0.0, "fullFrame": False}
|
||||
assert locate_cam([], W, H)["hasWebcam"] is False
|
||||
# Detecções fracas (score baixo) não contam.
|
||||
assert locate_cam([[(120, 700, 110, 130, 0.3)] for _ in range(12)], W, H)["hasWebcam"] is False
|
||||
|
||||
|
||||
def test_locate_cam_rect_clipped_and_snapped_to_frame_edges():
|
||||
# Rosto colado no canto: a expansão passaria da borda do quadro e precisa ser recortada em 0..1.
|
||||
frames = [[(10, 950, 110, 120, 0.9)] for _ in range(8)]
|
||||
result = locate_cam(frames, W, H)
|
||||
assert inside_unit(result["cam"]) and result["cam"]["x"] == 0
|
||||
# Com bordas persistentes da moldura, o retângulo encaixa nelas.
|
||||
rng = random.Random(4)
|
||||
frames = [[cam_face(rng)] for _ in range(12)]
|
||||
edges = {"xs": [0.02, 0.2, 0.7], "ys": [0.55, 0.95, 0.1]}
|
||||
cam = locate_cam(frames, W, H, edges=edges)["cam"]
|
||||
assert cam == {"x": 0.02, "y": 0.55, "w": 0.18, "h": 0.4}
|
||||
|
||||
|
||||
# --- ajustes da bancada (números reais da sessão 3, doc/FACE_BAKEOFF.md) ------------------------------------------
|
||||
|
||||
|
||||
def real_calm(n: int, seed: int = 7) -> list[FaceSecond]:
|
||||
"""Neutro como o da live real: sorriso por segundo 0,02–0,25 (mediana ~0,1), boca ~0, olho arregalado ~0."""
|
||||
rng = random.Random(seed)
|
||||
return [FaceSecond(t, 1.0, 0.5, 0.4, 0.3, smile=rng.uniform(0.02, 0.22), jaw=rng.uniform(0.0, 0.01),
|
||||
surprise=rng.uniform(0.0, 0.004), frown=rng.uniform(0.01, 0.07), brow=rng.uniform(0.01, 0.05),
|
||||
blink=0.1, motion=rng.uniform(0.02, 0.15)) for t in range(n)]
|
||||
|
||||
|
||||
def test_real_calm_with_isolated_spikes_has_no_peak():
|
||||
# No calmo real houve um segundo com sorriso 0,38 e outro com browInnerUp 0,38: não é reação.
|
||||
seconds = real_calm(300)
|
||||
seconds[200].smile = 0.38
|
||||
seconds[250].brow = 0.38
|
||||
assert reaction_moments(seconds) == []
|
||||
|
||||
|
||||
def test_laugh_without_open_mouth_is_risada():
|
||||
# Corte 10/12: sorriso 0,84–0,95 por vários segundos com jawOpen ≤ 0,11.
|
||||
seconds = real_calm(300)
|
||||
for t in range(200, 210):
|
||||
seconds[t].smile, seconds[t].jaw = 0.9, 0.05
|
||||
moments = reaction_moments(seconds)
|
||||
assert [m.label for m in moments] == ["risada"] and moments[0].onset_s == 200 and moments[0].strong
|
||||
|
||||
|
||||
def test_shout_is_jaw_and_brow_down_without_smile():
|
||||
# Corte 10, 1628 s: jawOpen 0,42 + browDown forte, sorriso 0,06 naquele segundo.
|
||||
seconds = real_calm(300)
|
||||
seconds[200].smile, seconds[200].jaw, seconds[200].frown = 0.06, 0.42, 0.5
|
||||
seconds[250].frown = 0.6 # franziu de boca fechada
|
||||
labels = [(m.peak_s, m.label) for m in reaction_moments(seconds)]
|
||||
assert labels == [(200, "grito"), (250, "raiva")]
|
||||
|
||||
|
||||
def test_confused_brow_inner_up_without_smile():
|
||||
# Corte 9 (lag): browInnerUp 0,7–0,8 por ~6 s, sorriso baixo, eyeWide ~0.
|
||||
seconds = real_calm(300)
|
||||
for t in range(200, 206):
|
||||
seconds[t].brow = 0.78
|
||||
moments = reaction_moments(seconds)
|
||||
assert [m.label for m in moments] == ["confuso"] and moments[0].onset_s == 200
|
||||
|
||||
|
||||
def test_surprise_does_not_need_eye_wide():
|
||||
# Na live real eyeWide fica ~0: sobrancelha (interna OU externa) levantada é o canal `brow`; parada = confuso,
|
||||
# com a cabeça se mexendo = susto. Olho arregalado parado continua sendo choque.
|
||||
blend = {"browOuterUpLeft": 0.7, "browOuterUpRight": 0.7, "eyeWideLeft": 0.0, "eyeWideRight": 0.0}
|
||||
second = per_second([FaceSample(0.1, True, 0.5, 0.4, 0.3, blend)], 1)[0]
|
||||
assert second.brow == pytest.approx(0.7) and second.surprise == 0.0
|
||||
assert label(second) == "confuso"
|
||||
second.motion = 0.9
|
||||
assert label(second) == "susto"
|
||||
eyes = per_second([FaceSample(0.1, True, 0.5, 0.4, 0.3, {"eyeWideLeft": 0.8, "eyeWideRight": 0.8})], 1)[0]
|
||||
assert label(eyes) == "choque"
|
||||
|
||||
|
||||
def test_motion_alone_or_with_flickering_face_is_not_a_peak():
|
||||
# Rastreio pulando (rosto em 1/3 do segundo) dava "susto" de intensidade 13 na live real.
|
||||
seconds = real_calm(300)
|
||||
seconds[200].present, seconds[200].motion, seconds[200].brow = 0.33, 3.0, 0.2
|
||||
seconds[250].motion = 3.0 # só movimento, rosto inteiro: ajeitou a cadeira
|
||||
assert reaction_moments(seconds) == []
|
||||
|
||||
|
||||
def test_old_series_without_brow_still_works():
|
||||
# Série gravada antes do canal `brow`: o canal fica parado, sem quebrar.
|
||||
data = seconds_to_json(real_calm(60))
|
||||
for d in data:
|
||||
d.pop("brow", None)
|
||||
assert all(v is not None for v in reaction_signal(seconds_from_json(data)))
|
||||
|
||||
|
||||
def test_summarize_absolute_times_for_the_prompt():
|
||||
seconds = real_calm(300)
|
||||
for t in range(200, 205):
|
||||
seconds[t].smile = 0.9
|
||||
assert summarize(seconds, 190, 230, relative=False).startswith("risada forte em 20")
|
||||
|
||||
|
||||
def test_locate_cam_leaning_streamer_stays_one_group():
|
||||
# Câmera grande (rosto ~0,16 do quadro): ele se inclina 0,8 largura de rosto em metade dos quadros.
|
||||
# Com distância fixa em fração do quadro (ou comparando com o 1º membro) o grupo se partia em dois.
|
||||
rng = random.Random(9)
|
||||
frames = []
|
||||
for i in range(12):
|
||||
lean = 0.8 * 300 if i % 2 else 0
|
||||
frames.append([(200 + lean + rng.uniform(-4, 4), 600 + rng.uniform(-4, 4), 300, 340, 0.9)])
|
||||
result = locate_cam(frames, W, H)
|
||||
assert result["hasWebcam"] and result["confidence"] > 0.5 # partido em dois daria presença 0,5 → ≤ 0,45
|
||||
face = result["faceRect"]
|
||||
center = (face["x"] + face["w"] / 2) * W
|
||||
assert 200 + 150 + 80 < center < 200 + 150 + 160 # média das duas posições (~350 + 120)
|
||||
|
||||
|
||||
def test_locate_cam_frameless_keeps_forehead():
|
||||
# Câmera sem moldura (streamer recortado sobre o jogo, banner logo abaixo): o retângulo vem do rosto e deixa
|
||||
# folga acima da testa — a IA cortava a testa (topo em y 0,532 com o rosto começando em 0,504).
|
||||
fw, fh = 1280, 720
|
||||
frames = [[(80 + i % 3, 363, 85, 109, 0.92)] for i in range(12)] # rosto da bancada: x 0,066 y 0,504 h 0,152
|
||||
result = locate_cam(frames, fw, fh)
|
||||
cam, face = result["cam"], result["faceRect"]
|
||||
assert face["y"] - cam["y"] >= 0.5 * face["h"] # testa e cabelo dentro
|
||||
assert cam["y"] + cam["h"] >= face["y"] + face["h"] + face["h"] # ombros/peito abaixo do queixo
|
||||
# Borda "falsa" logo acima da testa (ex.: banner) não corta a cabeça.
|
||||
edges = {"xs": [], "ys": [face["y"] - 0.01]}
|
||||
assert locate_cam(frames, fw, fh, edges=edges)["cam"]["y"] < face["y"] - 0.3 * face["h"]
|
||||
|
||||
|
||||
def test_two_hours_of_series_is_fast():
|
||||
# channel_z era O(n²): a API e a pontuação recalculam a live inteira. 2 h sintéticas precisam de < 1 s.
|
||||
import time
|
||||
|
||||
seconds = real_calm(7200, seed=3)
|
||||
for t in range(4000, 4006):
|
||||
seconds[t].smile = 0.9
|
||||
started = time.perf_counter()
|
||||
moments = reaction_moments(seconds)
|
||||
assert time.perf_counter() - started < 1.0
|
||||
assert [m.label for m in moments] == ["risada"] and moments[0].onset_s == 4000
|
||||
|
||||
|
||||
def test_locate_cam_ignores_static_low_score_object():
|
||||
"""Teste ao vivo de 17/11 (lofigirl, sem webcam): a tela de um notebook desenhado na borda esquerda saiu como
|
||||
rosto de 24×34 px com score 0,61–0,66 em 8 de 12 quadros e virou câmera. Webcam real: 0,92–0,94."""
|
||||
fake = (0.0, 415.0, 24.0, 34.0, 0.63)
|
||||
frames = [[fake], [fake], [fake, (726.0, 253.0, 73.0, 98.0, 0.604)], [], [fake], [], [fake], [fake],
|
||||
[(606.0, 254.0, 155.0, 197.0, 0.615)], [fake], [], [fake, (605.0, 257.0, 154.0, 193.0, 0.61)]]
|
||||
assert locate_cam(frames, 1280, 720)["hasWebcam"] is False
|
||||
real = [[(109.0 + i % 3, 359.0, 82.0, 112.0, 0.93)] for i in range(12)]
|
||||
assert locate_cam(real, 1280, 720)["hasWebcam"] is True
|
||||
@@ -0,0 +1,252 @@
|
||||
"""Reenquadramento do jogo no tempo (keyframes) e camadas inseridas (pedido do dono, 17/11/2026, corte 61)."""
|
||||
import shutil
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from app import editor, editor_render, layout, reframe
|
||||
|
||||
from .test_editor import make_project, validate
|
||||
|
||||
FFMPEG, FFPROBE = shutil.which("ffmpeg"), shutil.which("ffprobe")
|
||||
needs_ffmpeg = pytest.mark.skipif(not (FFMPEG and FFPROBE), reason="FFmpeg não instalado")
|
||||
SRC_W, SRC_H = 1280, 720
|
||||
DOT = (808.0, 308.0) # centro do quadrado branco de 16 px no vídeo de teste
|
||||
|
||||
|
||||
def _project(**over):
|
||||
base = make_project(source={"sessionId": 1, "lo": 0, "hi": 8}, cuts=[{"start": 0, "end": 4, "mode": None}],
|
||||
overlays=[], captions={"enabled": False, "preset": "pop", "style": {}, "emphColor": "#22E36B",
|
||||
"words": []},
|
||||
progress={"enabled": False}, cover={"enabled": False, "t": 1})
|
||||
base.update(over)
|
||||
return base
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- interpolação e validação
|
||||
def test_interpolation_semantics():
|
||||
keys = [{"t": 1.0, "cx": 0.2, "ease": "linear"}, {"t": 3.0, "cx": 0.6, "ease": "hold"},
|
||||
{"t": 5.0, "cx": 0.9, "ease": "smooth"}, {"t": 7.0, "cx": 0.1, "ease": "smooth"}]
|
||||
assert reframe.interp(keys, 0.0, "cx") == 0.2 # antes do 1º: segura
|
||||
assert reframe.interp(keys, 2.0, "cx") == pytest.approx(0.4) # linear
|
||||
assert reframe.interp(keys, 4.99, "cx") == 0.6 and reframe.interp(keys, 5.0, "cx") == 0.9 # hold salta no key seguinte
|
||||
assert reframe.interp(keys, 6.0, "cx") == pytest.approx(0.5) # smooth: meio exato no meio
|
||||
assert reframe.interp(keys, 6.5, "cx") < 0.9 - 0.8 * 0.75 + 0.05 # smooth acelera no meio (mais que linear)
|
||||
assert reframe.interp(keys, 9.0, "cx") == 0.1 # depois do último: segura
|
||||
|
||||
|
||||
def test_window_keeps_aspect_and_stays_inside():
|
||||
keys = [{"t": 0, "cx": 0.98, "cy": 0.02, "w": 0.4, "ease": "smooth"}]
|
||||
x, y, w, h = reframe.window(keys, 0, SRC_W, SRC_H, 1080 / 1268)
|
||||
assert w / h == pytest.approx(1080 / 1268) and x + w <= SRC_W + 1e-6 and y >= 0 and x >= 0
|
||||
big = [{"t": 0, "cx": 0.5, "cy": 0.5, "w": 1.0, "ease": "smooth"}]
|
||||
x, y, w, h = reframe.window(big, 0, SRC_W, SRC_H, 1080 / 1920) # zoom que não cabe: encolhe, não deforma
|
||||
assert h == pytest.approx(SRC_H) and w == pytest.approx(SRC_H * 1080 / 1920)
|
||||
|
||||
|
||||
def test_validation(tmp_path):
|
||||
keys = [{"t": 3, "cx": 0.5, "cy": 0.5, "w": 0.5}, {"t": 1, "cx": 0.2, "cy": 0.3, "w": 1, "ease": "hold"}]
|
||||
p = validate(_project(reframe={"keys": keys}), tmp_path)
|
||||
assert [k["t"] for k in p["reframe"]["keys"]] == [1, 3] and p["reframe"]["keys"][1]["ease"] == "smooth"
|
||||
assert "reframe" not in validate(_project(), tmp_path) and "reframe" not in validate(_project(reframe={"keys": []}), tmp_path)
|
||||
inset = {"id": "i", "kind": "inset", "start": 1, "end": 3, "src": {"x": 0.7, "y": 0.0, "w": 0.3, "h": 0.25},
|
||||
"x": 0.5, "y": 0.3, "size": 0.5, "border": "#ffffff"}
|
||||
q = validate(_project(overlays=[inset]), tmp_path)["overlays"][0]
|
||||
assert q["border"] == "#FFFFFF" and q["borderW"] == 6 and q["radius"] == 18 and q["shadow"] is True and q["keys"] == []
|
||||
bad = [
|
||||
{"reframe": {"keys": [{"t": 1, "cx": 0.5, "cy": 0.5, "w": 0.01}]}},
|
||||
{"reframe": {"keys": [{"t": 1, "cx": 0.5, "cy": 0.5, "w": 0.5, "ease": "bounce"}]}},
|
||||
{"reframe": {"keys": [{"t": 1, "cx": 0.5, "cy": 0.5, "w": 0.5}, {"t": 1.01, "cx": 0.5, "cy": 0.5, "w": 0.5}]}},
|
||||
{"reframe": {"keys": [{"t": 1 + i * 0.05, "cx": 0.5, "cy": 0.5, "w": 0.5} for i in range(61)]}},
|
||||
{"overlays": [{**inset, "src": {"x": 0.9, "y": 0, "w": 0.3, "h": 0.2}}]}, # fora do quadro
|
||||
{"overlays": [{**inset, "size": 0.05}]},
|
||||
{"overlays": [{**inset, "anim": "spin"}]},
|
||||
{"overlays": [{**inset, "src": None}]},
|
||||
{"overlays": [{**inset, "id": f"i{n}"} for n in range(13)]}, # mais de 12 camadas
|
||||
]
|
||||
for change in bad:
|
||||
with pytest.raises(editor.EditError):
|
||||
validate(_project(**change), tmp_path)
|
||||
|
||||
|
||||
def test_old_project_graph_unchanged_and_inset_not_in_ass(tmp_path):
|
||||
p = validate(make_project(), tmp_path)
|
||||
cfg = editor.effective_settings(layout.merge(), p)
|
||||
graph = editor_render.build_filter(p, cfg, editor.pieces(p["cuts"]), 10.0, "e.ass", [])
|
||||
assert "perspective" not in graph and "[vraw]" not in graph and "split=2[tl" not in graph
|
||||
inset = {"id": "i", "kind": "inset", "start": 11, "end": 13, "src": {"x": 0, "y": 0, "w": 0.3, "h": 0.3}}
|
||||
q = validate(make_project(overlays=[inset]), tmp_path)
|
||||
assert "Dialogue: 2" not in editor_render.build_project_ass(q, cfg, "")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- render real
|
||||
@pytest.fixture(scope="module")
|
||||
def dot_video(tmp_path_factory):
|
||||
if not FFMPEG:
|
||||
pytest.skip("FFmpeg não instalado")
|
||||
folder = tmp_path_factory.mktemp("reframe")
|
||||
seg = folder / "dot.ts"
|
||||
subprocess.run([FFMPEG, "-v", "error", "-f", "lavfi", "-i", f"color=c=0x101010:s={SRC_W}x{SRC_H}:r=30:d=8",
|
||||
"-f", "lavfi", "-i", "sine=frequency=440:duration=8",
|
||||
"-vf", "drawbox=x=800:y=300:w=16:h=16:color=white:t=fill", "-c:v", "libx264", "-preset", "ultrafast",
|
||||
"-crf", "8", "-g", "15", "-c:a", "aac", "-shortest", str(seg)], check=True)
|
||||
return seg
|
||||
|
||||
|
||||
def _frames(video: Path, size: tuple[int, int]):
|
||||
import numpy as np
|
||||
raw = subprocess.run([FFMPEG, "-v", "error", "-i", str(video), "-f", "rawvideo", "-pix_fmt", "gray", "-"],
|
||||
capture_output=True, check=True).stdout
|
||||
return np.frombuffer(raw, np.uint8).reshape(-1, size[1], size[0]).astype(float)
|
||||
|
||||
|
||||
def _centroid(frame):
|
||||
import numpy as np
|
||||
m = np.where(frame > 128, frame, 0)
|
||||
s = m.sum()
|
||||
if not s:
|
||||
return None
|
||||
ys, xs = np.mgrid[0:frame.shape[0], 0:frame.shape[1]]
|
||||
return (m * xs).sum() / s, (m * ys).sum() / s
|
||||
|
||||
|
||||
def _expected(keys, t, dest):
|
||||
x, y, w, h = reframe.window(keys, t, SRC_W, SRC_H, dest[0] / dest[1])
|
||||
return (DOT[0] - x) / w * dest[0], (DOT[1] - y) / h * dest[1]
|
||||
|
||||
|
||||
def _render(tmp_path, video, project, settings=None, name="out.mp4"):
|
||||
p = validate(project, tmp_path, duration=8.0)
|
||||
out = tmp_path / name
|
||||
editor_render.render_project(FFMPEG, FFPROBE, ["-c:v", "libx264", "-preset", "ultrafast", "-crf", "12"],
|
||||
[(video, 0.0, 8.0)], p, layout.merge(settings or {}), "", out, tmp_path)
|
||||
return p, out
|
||||
|
||||
|
||||
@needs_ffmpeg
|
||||
@pytest.mark.parametrize("aspect", ["vertical", "horizontal"])
|
||||
def test_reframe_window_follows_keys_smoothly(tmp_path, dot_video, aspect):
|
||||
keys = [{"t": 0.0, "cx": 0.5, "cy": 0.5, "w": 1.0, "ease": "smooth"},
|
||||
{"t": 2.0, "cx": 0.62, "cy": 0.42, "w": 0.3, "ease": "hold"},
|
||||
{"t": 3.0, "cx": 0.66, "cy": 0.45, "w": 0.45, "ease": "linear"}]
|
||||
settings = {"format": {"aspect": aspect}, "layout": {"mode": "game_only"}}
|
||||
_, out = _render(tmp_path, dot_video, _project(reframe={"keys": keys}, settings=settings))
|
||||
size = layout.FRAME_SIZES[aspect]
|
||||
frames = _frames(out, size)
|
||||
for n in (0, 15, 30, 45, 60, 75, 89, 91, 105): # quadro n = sessão n/30 (um trecho só)
|
||||
got = _centroid(frames[n])
|
||||
want = _expected(keys, n / 30, size)
|
||||
assert got and abs(got[0] - want[0]) < 4 and abs(got[1] - want[1]) < 4, (n, got, want)
|
||||
xs = [_centroid(f)[0] for f in frames[1:60]]
|
||||
steps = [b - a for a, b in zip(xs, xs[1:])]
|
||||
assert all(s <= 0.05 for s in steps) or all(s >= -0.05 for s in steps) # sempre no mesmo sentido: sem tremida
|
||||
jump_before, jump_after = _centroid(frames[89]), _centroid(frames[91]) # hold: salta no key de 3,0 s
|
||||
assert abs(jump_after[0] - jump_before[0]) > 20
|
||||
|
||||
|
||||
@needs_ffmpeg
|
||||
def test_reframe_uses_session_time_across_cuts(tmp_path, dot_video):
|
||||
keys = [{"t": 0.0, "cx": 0.5, "cy": 0.5, "w": 1.0, "ease": "linear"}, {"t": 6.0, "cx": 0.66, "cy": 0.45, "w": 0.35}]
|
||||
cuts = [{"start": 0.0, "end": 1.5, "mode": None}, {"start": 3.0, "end": 5.0, "mode": None}]
|
||||
settings = {"layout": {"mode": "game_only"}}
|
||||
_, out = _render(tmp_path, dot_video, _project(reframe={"keys": keys}, cuts=cuts, settings=settings))
|
||||
frames = _frames(out, (1080, 1920))
|
||||
for out_t, session_t in ((0.5, 0.5), (2.0, 3.5), (3.0, 4.5)):
|
||||
got, want = _centroid(frames[int(out_t * 30)]), _expected(keys, session_t, (1080, 1920))
|
||||
assert abs(got[0] - want[0]) < 4 and abs(got[1] - want[1]) < 4, (out_t, got, want)
|
||||
|
||||
|
||||
@needs_ffmpeg
|
||||
def test_reframe_in_cam_top_uses_game_area_and_cover(tmp_path, dot_video):
|
||||
keys = [{"t": 0.0, "cx": 0.62, "cy": 0.42, "w": 0.3}]
|
||||
settings = {"layout": {"mode": "cam_top", "cam": {"x": 0.0, "y": 0.0, "w": 0.2, "h": 0.25}}}
|
||||
p, out = _render(tmp_path, dot_video, _project(reframe={"keys": keys}, settings=settings))
|
||||
top = layout.cam_panel_height(layout.merge(settings))
|
||||
got = _centroid(_frames(out, (1080, 1920))[10][top:])
|
||||
want = _expected(keys, 0, (1080, 1920 - top))
|
||||
assert abs(got[0] - want[0]) < 4 and abs(got[1] - want[1]) < 4
|
||||
cover = editor_render.render_cover(FFMPEG, [(dot_video, 0.0, 8.0)], {**p, "cover": {**p["cover"], "t": 1.0}},
|
||||
layout.merge(settings), "", tmp_path / "cover.jpg")
|
||||
assert cover.is_file()
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def color_video(tmp_path_factory):
|
||||
if not FFMPEG:
|
||||
pytest.skip("FFmpeg não instalado")
|
||||
folder = tmp_path_factory.mktemp("insets")
|
||||
seg = folder / "colors.ts"
|
||||
boxes = ("drawbox=x=0:y=0:w=300:h=200:color=0x00FF00:t=fill,"
|
||||
"drawbox=x=900:y=500:w=380:h=220:color=0x0000FF:t=fill")
|
||||
subprocess.run([FFMPEG, "-v", "error", "-f", "lavfi", "-i", f"color=c=0xFF0000:s={SRC_W}x{SRC_H}:r=30:d=8",
|
||||
"-f", "lavfi", "-i", "sine=frequency=440:duration=8", "-vf", boxes, "-c:v", "libx264",
|
||||
"-preset", "ultrafast", "-crf", "8", "-g", "15", "-c:a", "aac", "-shortest", str(seg)], check=True)
|
||||
return seg
|
||||
|
||||
|
||||
def _rgb(video: Path, t: float, size: tuple[int, int]):
|
||||
import numpy as np
|
||||
raw = subprocess.run([FFMPEG, "-v", "error", "-ss", f"{t:.3f}", "-i", str(video), "-frames:v", "1", "-f", "rawvideo",
|
||||
"-pix_fmt", "rgb24", "-"], capture_output=True, check=True).stdout
|
||||
return np.frombuffer(raw, np.uint8).reshape(size[1], size[0], 3).astype(int)
|
||||
|
||||
|
||||
def _is(px, color, tol=60):
|
||||
return all(abs(int(a) - b) < tol for a, b in zip(px, color))
|
||||
|
||||
|
||||
@needs_ffmpeg
|
||||
@pytest.mark.parametrize("aspect", ["vertical", "horizontal"])
|
||||
def test_two_overlapping_insets_with_border_and_anim(tmp_path, color_video, aspect):
|
||||
green = {"id": "g", "kind": "inset", "start": 0.5, "end": 3.5, "src": {"x": 0.0, "y": 0.0, "w": 0.2344, "h": 0.2778},
|
||||
"x": 0.25, "y": 0.25, "size": 0.4, "border": "#FFFFFF", "borderW": 8, "radius": 20, "shadow": True, "anim": "fade"}
|
||||
blue = {"id": "b", "kind": "inset", "start": 1.0, "end": 3.5, "src": {"x": 0.7031, "y": 0.6944, "w": 0.2969, "h": 0.3056},
|
||||
"x": 0.45, "y": 0.35, "size": 0.4, "border": "#FFFF00", "borderW": 8, "radius": 0, "shadow": False, "anim": "pop"}
|
||||
settings = {"format": {"aspect": aspect}, "layout": {"mode": "game_only", "game": {"x": 0.35, "y": 0.3, "w": 0.3, "h": 0.4}}}
|
||||
_, out = _render(tmp_path, color_video, _project(overlays=[green, blue], settings=settings))
|
||||
w, h = size = layout.FRAME_SIZES[aspect]
|
||||
frame = _rgb(out, 2.0, size)
|
||||
gx, gy = int(0.25 * w), int(0.25 * h)
|
||||
gw = 0.4 * w
|
||||
gh = gw * (0.2778 * SRC_H) / (0.2344 * SRC_W)
|
||||
bw = 0.4 * w
|
||||
bh = bw * (0.3056 * SRC_H) / (0.2969 * SRC_W)
|
||||
bx0, by0 = 0.45 * w - bw / 2, 0.35 * h - bh / 2
|
||||
assert _is(frame[gy, int(gx - gw / 2 + 12)], (0, 255, 0)) # camada verde (dentro, longe da azul)
|
||||
assert _is(frame[gy, int(gx - gw / 2 - 3)], (255, 255, 255)) # borda branca do lado de fora
|
||||
assert _is(frame[int(by0 + bh / 2), int(0.45 * w)], (0, 0, 255)) # camada azul
|
||||
ox, oy = int(bx0 + 15), int(by0 + 15) # canto da azul que cai em cima da verde: a azul (última) fica por cima
|
||||
assert gx - gw / 2 < ox < gx + gw / 2 and gy - gh / 2 < oy < gy + gh / 2
|
||||
assert _is(frame[oy, ox], (0, 0, 255))
|
||||
assert _is(frame[int(0.9 * h), int(0.9 * w)], (255, 0, 0)) # fora das camadas: o jogo (vermelho)
|
||||
early = _rgb(out, 0.56, size)[gy, int(gx - gw / 2 + 12)] # fade: no começo a verde ainda está entrando
|
||||
assert not _is(early, (0, 255, 0), tol=30)
|
||||
assert _is(_rgb(out, 3.8, size)[gy, gx], (255, 0, 0)) # depois do fim: some
|
||||
|
||||
|
||||
@needs_ffmpeg
|
||||
def test_inset_keys_move_it_in_session_time(tmp_path, color_video):
|
||||
blue = {"id": "b", "kind": "inset", "start": 0.0, "end": 6.0, "src": {"x": 0.7031, "y": 0.6944, "w": 0.2969, "h": 0.3056},
|
||||
"x": 0.3, "y": 0.5, "size": 0.3, "border": None, "shadow": False, "anim": "none",
|
||||
"keys": [{"t": 1.0, "x": 0.3, "y": 0.5, "size": 0.3, "ease": "linear"}, {"t": 5.0, "x": 0.7, "y": 0.5, "size": 0.3}]}
|
||||
cuts = [{"start": 0.0, "end": 2.0, "mode": None}, {"start": 3.0, "end": 6.0, "mode": None}]
|
||||
settings = {"layout": {"mode": "game_only", "game": {"x": 0.35, "y": 0.3, "w": 0.3, "h": 0.4}}}
|
||||
_, out = _render(tmp_path, color_video, _project(overlays=[blue], cuts=cuts, settings=settings))
|
||||
frame = _rgb(out, 2.0, (1080, 1920)) # saída 2,0 s = sessão 3,0 s → x = 0,3 + 0,4 × (2/4) = 0,5
|
||||
assert _is(frame[960, 540], (0, 0, 255)) and _is(frame[960, int(0.3 * 1080) - 120], (255, 0, 0))
|
||||
|
||||
|
||||
@needs_ffmpeg
|
||||
def test_sixty_keys_render_through_graph_file(tmp_path, dot_video):
|
||||
"""60 keyframes num trecho: o grafo passa do limite da linha de comando e vai por arquivo (-/filter_complex)."""
|
||||
keys = [{"t": i * 0.06, "cx": 0.5 + 0.1 * (i % 2), "cy": 0.5, "w": 0.4 + 0.3 * (i % 3) / 2, "ease": "linear"}
|
||||
for i in range(60)]
|
||||
p = validate(_project(reframe={"keys": keys}, settings={"layout": {"mode": "game_only"}}), tmp_path, duration=8.0)
|
||||
graph = editor_render.build_filter(p, editor.effective_settings(layout.merge(), p), editor.pieces(p["cuts"]), 0.0,
|
||||
None, [])
|
||||
assert len(graph) > 20000
|
||||
_, out = _render(tmp_path, dot_video, _project(reframe={"keys": keys}, settings={"layout": {"mode": "game_only"}}))
|
||||
got, want = _centroid(_frames(out, (1080, 1920))[100]), _expected(keys, 100 / 30, (1080, 1920))
|
||||
assert abs(got[0] - want[0]) < 4 and abs(got[1] - want[1]) < 4
|
||||
assert not list(tmp_path.glob("*.graph.txt")) # arquivo temporário apagado
|
||||
@@ -0,0 +1,190 @@
|
||||
"""Bugs de produção de 16–17/11/2026 (sessão 3 do skipnho):
|
||||
1. corte preso em 'rendering' quando o render levantava uma exceção não prevista (KeyError da legenda);
|
||||
2. o mesmo momento virando vários cortes (pico 1149 → cortes 42, 47, 49, 51, 52 em cima do 9, já pronto)."""
|
||||
import json
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from pathlib import Path
|
||||
|
||||
import app.editor_api as editor_api
|
||||
import app.worker as worker_module
|
||||
from app.judge import Judge, Verdict
|
||||
from app.scoring import Moment
|
||||
|
||||
from .test_sources_and_api import env, seed_session # noqa: F401 - fixture reaproveitada
|
||||
|
||||
|
||||
class RecuoJudge(Judge):
|
||||
"""Juiz falso (nunca chama a CLI): mantém e recua o início para `back_to`, como o juiz real fez no corte 42."""
|
||||
|
||||
def __init__(self, back_to: float | None = None):
|
||||
super().__init__("codex", "fake", Path("."))
|
||||
self.back_to = back_to
|
||||
|
||||
def analyze(self, prompt, images):
|
||||
return {"situation": "lag_ou_bug", "confidence": 0.9, "action_start_s": 0, "reaction_end_s": 0, "hook": ""}
|
||||
|
||||
def judge(self, prompt, start_s, end_s, images=None, **_limits):
|
||||
start = self.back_to if self.back_to is not None else start_s
|
||||
return Verdict(True, 8.0, start, end_s, "O lag colocou ele em três lugares", "legenda", "motivo", "fake")
|
||||
|
||||
|
||||
def add_clip(engine, sid, cid, status, peak, start, end, source="chat", reasons=None):
|
||||
engine.db.run("INSERT INTO clips (id, session_id, peak_s, start_s, end_s, score, source, reasons_json, status, title, "
|
||||
"created_at, updated_at) VALUES (?, ?, ?, ?, ?, 5, ?, ?, ?, 't', 'x', ?)",
|
||||
cid, sid, peak, start, end, source, json.dumps(reasons or {}), status, worker_module.now())
|
||||
|
||||
|
||||
def status(engine, cid):
|
||||
return engine.db.get("SELECT status FROM clips WHERE id = ?", cid)["status"]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- bug 1: render
|
||||
def test_render_that_explodes_becomes_error_and_next_clip_runs(env, monkeypatch): # noqa: F811
|
||||
_client, engine = env
|
||||
monkeypatch.setattr(worker_module, "REPO_ROOT", engine.settings.data_dir.parent)
|
||||
sid = seed_session(engine)
|
||||
add_clip(engine, sid, 1, "pending", 100, 90, 120)
|
||||
add_clip(engine, sid, 2, "pending", 300, 290, 320)
|
||||
|
||||
def ensure_edit(eng, clip, session):
|
||||
if clip["id"] == 1:
|
||||
raise KeyError(2413111138480) # o erro medido na versão intermediária da legenda
|
||||
return {"project": {}}
|
||||
monkeypatch.setattr(editor_api, "ensure_edit", ensure_edit)
|
||||
monkeypatch.setattr(editor_api, "render_clip_edit", lambda *a, **k: None)
|
||||
engine.render_pending()
|
||||
first = engine.db.get("SELECT status, error FROM clips WHERE id = 1")
|
||||
assert first["status"] == "error" and "KeyError" in first["error"]
|
||||
assert status(engine, 2) == "ready" and engine._rendering == set()
|
||||
|
||||
|
||||
def test_orphan_rendering_goes_back_to_queue_then_error(env, monkeypatch): # noqa: F811
|
||||
_client, engine = env
|
||||
sid = seed_session(engine)
|
||||
old = (datetime.now(timezone.utc) - timedelta(minutes=10)).isoformat(timespec="seconds")
|
||||
add_clip(engine, sid, 1, "rendering", 100, 90, 120)
|
||||
add_clip(engine, sid, 2, "rendering", 300, 290, 320) # recente: pode estar renderizando ainda
|
||||
add_clip(engine, sid, 3, "rendering", 500, 490, 520)
|
||||
engine.db.run("UPDATE clips SET updated_at = ? WHERE id IN (1, 3)", old)
|
||||
engine._rendering.add(3) # este processo está renderizando o 3 agora
|
||||
engine.recover_orphan_renders()
|
||||
assert [status(engine, c) for c in (1, 2, 3)] == ["pending", "rendering", "rendering"]
|
||||
for _ in range(worker_module.MAX_RENDER_ATTEMPTS - 1):
|
||||
engine.db.run("UPDATE clips SET status = 'rendering', updated_at = ? WHERE id = 1", old)
|
||||
engine.recover_orphan_renders()
|
||||
assert status(engine, 1) == "error"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- bug 2: duplicados
|
||||
def test_judge_backtrack_onto_ready_clip_is_discarded_as_duplicate(env): # noqa: F811
|
||||
_client, engine = env
|
||||
sid = seed_session(engine, duration=1300)
|
||||
add_clip(engine, sid, 9, "ready", 1084, 1045, 1100)
|
||||
engine.judge = RecuoJudge(back_to=1012)
|
||||
add_clip(engine, sid, 42, "candidate", 1149, 1095, 1155)
|
||||
engine.judge_clip(engine.db.get("SELECT * FROM clips WHERE id = 42"))
|
||||
row = engine.db.get("SELECT status, start_s, judge_json FROM clips WHERE id = 42")
|
||||
judge = json.loads(row["judge_json"])
|
||||
assert row["status"] == "discarded" and judge["duplicateOf"] == 9 and "Duplicado do corte 9" in judge["reason"]
|
||||
# "cortar agora" nunca é bloqueado: só avisa
|
||||
add_clip(engine, sid, 43, "candidate", 1080, 1040, 1100, source="manual")
|
||||
engine.judge_clip(engine.db.get("SELECT * FROM clips WHERE id = 43"))
|
||||
manual = engine.db.get("SELECT status, judge_json FROM clips WHERE id = 43")
|
||||
assert manual["status"] == "pending" and json.loads(manual["judge_json"])["warning"] == "mesmo momento do corte 9"
|
||||
|
||||
|
||||
def test_repeated_passes_never_recreate_the_same_peak(env, monkeypatch): # noqa: F811
|
||||
_client, engine = env
|
||||
sid = seed_session(engine, duration=1300)
|
||||
engine.db.run("UPDATE sessions SET status = 'stopped' WHERE id = ?", sid)
|
||||
moment = Moment(peak_s=1149.0, start_s=1095.0, end_s=1155.0, score=5.0, source="chat", reasons={"onsetS": 1142})
|
||||
monkeypatch.setattr(worker_module, "find_moments", lambda *a, **k: [moment])
|
||||
assert engine.find_new_clips(engine.db.get("SELECT * FROM sessions WHERE id = ?", sid)) == 1
|
||||
clip = engine.db.get("SELECT * FROM clips WHERE session_id = ?", sid)
|
||||
assert json.loads(clip["reasons_json"])["candidateStartS"] == 1095.0 # janela original guardada
|
||||
# O juiz recuou o corte para 1012–1100: o candidato do mesmo pico já não sobrepõe o trecho final…
|
||||
engine.db.run("UPDATE clips SET start_s = 1012, end_s = 1100, status = 'discarded' WHERE id = ?", clip["id"])
|
||||
for _ in range(3): # …mas passadas seguidas não recriam (nem com o corte descartado)
|
||||
assert engine.find_new_clips(engine.db.get("SELECT * FROM sessions WHERE id = ?", sid)) == 0
|
||||
assert engine.db.get("SELECT COUNT(*) AS n FROM clips WHERE session_id = ?", sid)["n"] == 1
|
||||
# Corte antigo sem janela guardada: o pico igual também bloqueia.
|
||||
engine.db.run("UPDATE clips SET reasons_json = '{}' WHERE id = ?", clip["id"])
|
||||
assert engine.find_new_clips(engine.db.get("SELECT * FROM sessions WHERE id = ?", sid)) == 0
|
||||
|
||||
|
||||
def test_startup_queue_drops_pending_duplicates(env): # noqa: F811
|
||||
"""Caso real da sessão 3: 42, 47, 51 e 52 (pico 1149, recuados para 1012–1100) em cima do 9, pronto."""
|
||||
_client, engine = env
|
||||
sid = seed_session(engine, duration=9000)
|
||||
add_clip(engine, sid, 9, "ready", 1084, 1045, 1100)
|
||||
for cid, start, end in ((42, 1012.2, 1099.68), (47, 1012.2, 1099.68), (51, 1012.86, 1099.68), (52, 1012.86, 1102.86)):
|
||||
add_clip(engine, sid, cid, "pending", 1149, start, end)
|
||||
add_clip(engine, sid, 53, "pending", 7850, 7793.484, 7860.114) # momento próprio (o 54 parecido foi descartado)
|
||||
add_clip(engine, sid, 54, "discarded", 7928, 7792.57, 7852.57)
|
||||
add_clip(engine, sid, 70, "pending", 1150, 1012, 1100, source="manual") # seu: nunca sai da fila
|
||||
dropped = engine.discard_pending_duplicates()
|
||||
assert sorted(dropped) == [(42, 9), (47, 9), (51, 9), (52, 9)]
|
||||
assert status(engine, 53) == "pending" and status(engine, 70) == "pending"
|
||||
assert json.loads(engine.db.get("SELECT judge_json FROM clips WHERE id = 47")["judge_json"])["duplicateOf"] == 9
|
||||
|
||||
|
||||
def test_same_moment_rule():
|
||||
a = {"peak_s": 1084, "start_s": 1045, "end_s": 1100}
|
||||
assert worker_module.same_moment(a, {"peak_s": 1149, "start_s": 1012, "end_s": 1100}) # cobre 100 % do 9
|
||||
assert worker_module.same_moment(a, {"peak_s": 1090, "start_s": 1200, "end_s": 1260}) # mesmo pico
|
||||
# momentos vizinhos de 60–90 s que só encostam não são duplicados
|
||||
assert not worker_module.same_moment({"peak_s": 1221, "start_s": 1184, "end_s": 1239},
|
||||
{"peak_s": 1287, "start_s": 1253, "end_s": 1308})
|
||||
assert not worker_module.same_moment({"peak_s": 100, "start_s": 40, "end_s": 130},
|
||||
{"peak_s": 170, "start_s": 100, "end_s": 190}) # 30 s de 90 s = 33 %
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 17/11/2026: "não está gerando os clipes"
|
||||
def test_rejected_moment_vetoes_judge_backtrack(env): # noqa: F811
|
||||
"""Caso 61/64 da sessão 3: o juiz recua o candidato (pico 8909) para a cena de um corte que você rejeitou."""
|
||||
_client, engine = env
|
||||
sid = seed_session(engine, duration=9000)
|
||||
add_clip(engine, sid, 61, "rejected", 8816, 8794.2, 8838.0)
|
||||
add_clip(engine, sid, 64, "candidate", 8909, 8878.0, 8939.1)
|
||||
engine.judge = RecuoJudge(back_to=8790)
|
||||
engine.judge_clip(engine.db.get("SELECT * FROM clips WHERE id = 64"))
|
||||
row = engine.db.get("SELECT status, judge_json FROM clips WHERE id = 64")
|
||||
judge = json.loads(row["judge_json"])
|
||||
assert row["status"] == "discarded" and judge["duplicateOf"] == 61 and "que você rejeitou" in judge["reason"]
|
||||
# descartado pela IA NÃO veta o trecho final de outro momento (só o candidato do mesmo pico)
|
||||
engine.db.run("UPDATE clips SET status = 'discarded' WHERE id = 61")
|
||||
add_clip(engine, sid, 65, "candidate", 8909, 8878.0, 8939.1)
|
||||
engine.judge_clip(engine.db.get("SELECT * FROM clips WHERE id = 65"))
|
||||
assert status(engine, 65) == "pending"
|
||||
|
||||
|
||||
def test_scan_memory_records_proposals_and_created(env): # noqa: F811
|
||||
from .test_intel import ScanJudge
|
||||
_client, engine = env
|
||||
engine.judge = ScanJudge() # 2 propostas: nota 8 (vira candidato) e nota 3 (barrada)
|
||||
engine.intel.opts["vision"] = False
|
||||
sid = seed_session(engine)
|
||||
engine.db.run("UPDATE sessions SET status = 'recording' WHERE id = ?", sid)
|
||||
assert engine.intel.scan_session(engine.db.get("SELECT * FROM sessions WHERE id = ?", sid)) == 1
|
||||
memory = json.loads(engine.db.get("SELECT memory_json FROM sessions WHERE id = ?", sid)["memory_json"])
|
||||
assert memory[-1]["proposals"] == 2 and memory[-1]["created"] == 1 and memory[-1]["summary"] == "tiroteio na base"
|
||||
|
||||
|
||||
def test_queue_cleanup_uses_the_same_veto_as_the_judge(env): # noqa: F811
|
||||
"""Fila antes do render: pendente igual a rejeitado ou a apagado-que-estava-pronto sai; igual a descartado pela IA
|
||||
fica; manual nunca sai."""
|
||||
_client, engine = env
|
||||
sid = seed_session(engine, duration=9000)
|
||||
add_clip(engine, sid, 61, "rejected", 8816, 8794.2, 8838.0)
|
||||
add_clip(engine, sid, 70, "pending", 8820, 8790.0, 8858.0) # = rejeitado
|
||||
add_clip(engine, sid, 71, "discarded", 5000, 4970.0, 5030.0)
|
||||
add_clip(engine, sid, 72, "pending", 5004, 4968.0, 5032.0) # = descartado pela IA: fica
|
||||
engine.db.run("INSERT INTO deleted_clips (clip_id, session_id, peak_s, start_s, end_s, status, source, deleted_at)"
|
||||
" VALUES (80, ?, 3000, 2970, 3040, 'ready', 'chat', 'x')", sid)
|
||||
add_clip(engine, sid, 73, "pending", 3002, 2968.0, 3038.0) # = apagado que estava pronto
|
||||
add_clip(engine, sid, 74, "pending", 8818, 8790.0, 8850.0, source="manual") # manual: nunca sai
|
||||
assert sorted(engine.discard_pending_duplicates()) == [(70, 61), (73, 80)]
|
||||
reasons = {cid: json.loads(engine.db.get("SELECT judge_json FROM clips WHERE id = ?", cid)["judge_json"])["reason"]
|
||||
for cid in (70, 73)}
|
||||
assert "que você rejeitou" in reasons[70] and "que você apagou" in reasons[73]
|
||||
assert status(engine, 72) == "pending" and status(engine, 74) == "pending"
|
||||
@@ -0,0 +1,166 @@
|
||||
"""Retomada de live depois de reinício ou de queda da captura (bug de 16/11/2026, sessão 3 do skipnho): a 1ª
|
||||
checagem logo depois do reinício falhou e a live, que estava no ar, foi direto para o processamento."""
|
||||
import subprocess
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
import app.worker as worker_module
|
||||
from app.worker import LiveCheck
|
||||
|
||||
from .test_sources_and_api import env, seed_session # noqa: F401 - fixture reaproveitada
|
||||
|
||||
|
||||
class FakeCapture:
|
||||
started: list[int] = []
|
||||
|
||||
def __init__(self, eng, session_id, source, workdir, start_idx=0):
|
||||
FakeCapture.started.append(start_idx)
|
||||
self.chat = None
|
||||
|
||||
def start(self):
|
||||
pass
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def live(env, monkeypatch): # noqa: F811
|
||||
client, engine = env
|
||||
sid = seed_session(engine)
|
||||
engine.db.run("UPDATE sessions SET status = 'interrupted' WHERE id = ?", sid)
|
||||
engine.resume_delays = (0.0,) * 7
|
||||
FakeCapture.started = []
|
||||
monkeypatch.setattr(worker_module, "Capture", FakeCapture)
|
||||
return engine, sid
|
||||
|
||||
|
||||
def scripted(engine, results):
|
||||
calls = []
|
||||
|
||||
def check(url):
|
||||
calls.append(url)
|
||||
return results[min(len(calls), len(results)) - 1]
|
||||
engine.live_check = check
|
||||
return calls
|
||||
|
||||
|
||||
def status(engine, sid):
|
||||
return engine.db.get("SELECT status FROM sessions WHERE id = ?", sid)["status"]
|
||||
|
||||
|
||||
def test_startup_resume_retries_until_the_check_works(live):
|
||||
engine, sid = live
|
||||
unknown = LiveCheck("unknown", reason="streamlink --json passou de 60 s")
|
||||
calls = scripted(engine, [unknown, unknown, unknown, LiveCheck("live", {"title": "t"})])
|
||||
engine.resume_interrupted([sid])
|
||||
assert len(calls) == 4 and FakeCapture.started == [20] # retomou na mesma sessão, continuando a numeração
|
||||
assert status(engine, sid) == "starting" # gravando de novo, não processando
|
||||
|
||||
|
||||
def test_startup_resume_gives_up_only_after_all_attempts(live):
|
||||
engine, sid = live
|
||||
calls = scripted(engine, [LiveCheck("unknown", reason="erro")])
|
||||
seen = []
|
||||
original = engine.live_check
|
||||
|
||||
def check(url):
|
||||
seen.append(status(engine, sid)) # enquanto tenta, a sessão continua 'interrupted'
|
||||
return original(url)
|
||||
engine.live_check = check
|
||||
engine.resume_interrupted([sid])
|
||||
assert len(calls) == len(engine.resume_delays) and set(seen) == {"interrupted"}
|
||||
assert FakeCapture.started == [] and status(engine, sid) == "processing"
|
||||
|
||||
|
||||
def test_offline_confirmed_twice_finishes_early(live):
|
||||
engine, sid = live
|
||||
calls = scripted(engine, [LiveCheck("offline", reason="No playable streams")])
|
||||
engine.resume_interrupted([sid])
|
||||
assert len(calls) == 2 and status(engine, sid) == "processing"
|
||||
# "offline" isolado entre falhas de checagem não conta como confirmação
|
||||
engine.db.run("UPDATE sessions SET status = 'interrupted' WHERE id = ?", sid)
|
||||
off, unk = LiveCheck("offline"), LiveCheck("unknown")
|
||||
calls = scripted(engine, [off, unk, off, unk, off, unk, off])
|
||||
engine.resume_interrupted([sid])
|
||||
assert len(calls) == 7
|
||||
|
||||
|
||||
def test_owner_action_in_the_middle_wins(live):
|
||||
engine, sid = live
|
||||
|
||||
def check(url):
|
||||
engine.db.run("UPDATE sessions SET status = 'processing' WHERE id = ?", sid) # você clicou "Processar"
|
||||
return LiveCheck("live", {"title": "t"})
|
||||
engine.live_check = check
|
||||
assert engine.keep_live(sid, "teste") is False
|
||||
assert FakeCapture.started == [] and status(engine, sid) == "processing"
|
||||
|
||||
|
||||
def test_capture_drop_mid_live_reconnects(live):
|
||||
engine, sid = live
|
||||
engine.db.run("UPDATE sessions SET status = 'recording' WHERE id = ?", sid)
|
||||
scripted(engine, [LiveCheck("unknown"), LiveCheck("live", {"title": "t"})])
|
||||
started = []
|
||||
engine.keep_live = lambda session_id, why: started.append(why) # a thread chamaria keep_live
|
||||
engine.capture_dropped(sid, got_video=True)
|
||||
import time
|
||||
for _ in range(50):
|
||||
if started:
|
||||
break
|
||||
time.sleep(0.02)
|
||||
assert status(engine, sid) == "interrupted" and started == ["captura caiu"]
|
||||
# Retomadas seguidas sem nenhum bloco novo: desiste depois de MAX_EMPTY_RESUMES e processa.
|
||||
for _ in range(worker_module.MAX_EMPTY_RESUMES):
|
||||
engine.db.run("UPDATE sessions SET status = 'recording' WHERE id = ?", sid)
|
||||
engine.capture_dropped(sid, got_video=False)
|
||||
assert status(engine, sid) == "processing"
|
||||
|
||||
|
||||
def _fake_run(monkeypatch, stdout=b"", stderr=b"", code=0, exc=None):
|
||||
def run(*_args, **_kwargs):
|
||||
if exc:
|
||||
raise exc
|
||||
return SimpleNamespace(stdout=stdout, stderr=stderr, returncode=code)
|
||||
monkeypatch.setattr(worker_module.subprocess, "run", run)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("kwargs,state", [
|
||||
({"stdout": b'{"streams": {"best": {}}, "metadata": {"title": "oi", "category": "GTA"}}'}, "live"),
|
||||
({"stdout": b'{"error": "No playable streams found on this URL: https://www.twitch.tv/x"}', "code": 1}, "offline"),
|
||||
({"exc": subprocess.TimeoutExpired("streamlink", 60)}, "unknown"),
|
||||
({"exc": OSError("não achou")}, "unknown"),
|
||||
({"stdout": b"<html>erro</html>", "stderr": b"error: rede", "code": 1}, "unknown"),
|
||||
({"stdout": b'{"error": "Unable to open URL: https://gql.twitch.tv (503 Server Error)"}', "code": 1}, "unknown"),
|
||||
])
|
||||
def test_live_check_tells_offline_from_check_failure(env, monkeypatch, caplog, kwargs, state): # noqa: F811
|
||||
_client, engine = env
|
||||
from dataclasses import replace
|
||||
engine.settings = replace(engine.settings, streamlink="streamlink")
|
||||
_fake_run(monkeypatch, **kwargs)
|
||||
result = engine.live_check("https://www.twitch.tv/x")
|
||||
assert result.state == state
|
||||
if state == "live":
|
||||
assert result.meta["category"] == "GTA" and engine.check_live("u") == (True, "oi")
|
||||
else:
|
||||
assert engine.check_meta("u") is None # quem só quer saber "está ao vivo?" continua recebendo None
|
||||
if state == "unknown":
|
||||
assert "checagem da live" in caplog.text and result.reason # motivo registrado no log
|
||||
|
||||
|
||||
@pytest.mark.skipif(not __import__("shutil").which("ffmpeg"), reason="FFmpeg não instalado")
|
||||
def test_capture_that_stops_by_itself_goes_to_reconnect(env, tmp_path, monkeypatch): # noqa: F811
|
||||
"""Captura de live que para sem stop() (aqui o "streamlink" sai na hora) não processa direto: vai para a
|
||||
retomada com novas tentativas."""
|
||||
import shutil
|
||||
import sys
|
||||
from dataclasses import replace
|
||||
|
||||
from app.sources import parse_source
|
||||
_client, engine = env
|
||||
sid = seed_session(engine)
|
||||
engine.settings = replace(engine.settings, streamlink=sys.executable, ffmpeg=shutil.which("ffmpeg"))
|
||||
dropped = []
|
||||
monkeypatch.setattr(engine, "capture_dropped", lambda session_id, got_video: dropped.append((session_id, got_video)))
|
||||
capture = worker_module.Capture(engine, sid, parse_source("https://www.twitch.tv/alanzoka"), tmp_path / "cap", start_idx=20)
|
||||
capture.thread.start() # sem o chat (não abre conexão)
|
||||
capture.thread.join(timeout=60)
|
||||
assert dropped == [(sid, False)]
|
||||
@@ -0,0 +1,196 @@
|
||||
import random
|
||||
|
||||
from app.scoring import ChatMessage, Params, Word, find_moments, message_weight, overlaps, snap_to_words
|
||||
from app.subtitles import build_ass, group_words
|
||||
|
||||
|
||||
def calm_chat(duration: int, rate: float = 3.0, seed: int = 1) -> list[ChatMessage]:
|
||||
rng = random.Random(seed)
|
||||
out = []
|
||||
for t in range(duration):
|
||||
for _ in range(int(rate) + (1 if rng.random() < rate % 1 else 0)):
|
||||
out.append(ChatMessage(t + rng.random(), rng.choice(["oi", "salve", "boa noite", "eae", "kappa"])))
|
||||
return out
|
||||
|
||||
|
||||
def burst(at: int, seconds: int, per_s: int, text: str) -> list[ChatMessage]:
|
||||
return [ChatMessage(at + s + i / per_s, text) for s in range(seconds) for i in range(per_s)]
|
||||
|
||||
|
||||
def test_message_weight_counts_reactions():
|
||||
assert message_weight("oi")[0] == 1.0
|
||||
weight, tags = message_weight("KKKKKKK clipa isso")
|
||||
assert "risada" in tags and "clip" in tags and weight == 5.0
|
||||
|
||||
|
||||
def test_finds_peak_after_the_event_and_cuts_before_it():
|
||||
chat = calm_chat(600) + burst(300, 8, 25, "KKKKKKKKK")
|
||||
moments = find_moments(600, chat, [], [])
|
||||
assert len(moments) == 1
|
||||
m = moments[0]
|
||||
assert 300 <= m.peak_s <= 310
|
||||
assert m.start_s < 300 - 5 # o corte começa ANTES da reação (é ali que aconteceu)
|
||||
assert m.end_s >= m.peak_s
|
||||
assert Params().min_s <= m.end_s - m.start_s <= Params().max_s
|
||||
assert m.source == "chat" and m.reasons["tags"].get("risada")
|
||||
|
||||
|
||||
def test_big_chat_needs_relative_peak():
|
||||
# Chat enorme o tempo todo (canal grande) não vira corte sem um pico relativo.
|
||||
assert find_moments(600, calm_chat(600, rate=40), [], []) == []
|
||||
|
||||
|
||||
def test_two_peaks_far_apart_both_found_and_close_ones_merged():
|
||||
chat = calm_chat(900) + burst(200, 6, 25, "caralho") + burst(215, 4, 25, "kkkkk") + burst(600, 6, 25, "POGGERS")
|
||||
peaks = [m.peak_s for m in find_moments(900, chat, [], [])]
|
||||
assert len(peaks) == 2
|
||||
assert 195 <= peaks[0] <= 225 and 595 <= peaks[1] <= 610
|
||||
|
||||
|
||||
def test_live_mode_waits_for_settle():
|
||||
chat = calm_chat(316) + burst(300, 8, 25, "KKKK")
|
||||
assert find_moments(316, chat, [], [], live=True) == [] # pico perto demais do fim da gravação
|
||||
chat = calm_chat(400) + burst(300, 8, 25, "KKKK")
|
||||
assert len(find_moments(400, chat, [], [], live=True)) == 1
|
||||
|
||||
|
||||
def test_live_mode_does_not_cut_a_burst_that_is_still_growing():
|
||||
# Explosão começa em 300 e só atinge o máximo em 312; com 326 s gravados o máximo ainda não assentou,
|
||||
# e o começo da explosão (já "assentado") não pode virar corte sozinho.
|
||||
chat = calm_chat(326) + burst(300, 6, 10, "kkk") + burst(306, 8, 40, "KKKKKKK")
|
||||
assert find_moments(326, chat, [], [], live=True) == []
|
||||
|
||||
|
||||
def test_audio_mode_without_chat():
|
||||
loud = [-40.0] * 600
|
||||
for t in range(400, 406):
|
||||
loud[t] = -8.0
|
||||
moments = find_moments(600, [], loud, [])
|
||||
assert len(moments) == 1 and moments[0].source == "audio" and 395 <= moments[0].peak_s <= 410
|
||||
|
||||
|
||||
def test_snap_to_words_avoids_cutting_mid_sentence():
|
||||
words = [Word(10.0, 10.4, "olha"), Word(10.5, 10.9, "isso"), Word(12.0, 12.3, "não"), Word(12.35, 12.8, "acredito"),
|
||||
Word(20.0, 20.5, "mano")]
|
||||
start, end = snap_to_words(12.2, 12.5, words)
|
||||
assert start <= 12.0 and end >= 12.8
|
||||
|
||||
|
||||
def test_overlaps():
|
||||
assert overlaps(0, 30, 20, 50)
|
||||
assert not overlaps(0, 30, 27, 60) # tolerância de 5 s
|
||||
|
||||
|
||||
def test_ass_groups_words_and_escapes_tags():
|
||||
words = [Word(1.0, 1.3, "olha"), Word(1.35, 1.6, "{isso}"), Word(1.7, 2.0, "aqui"), Word(5.0, 5.4, "gente")]
|
||||
groups = group_words(words)
|
||||
assert [len(g) for g in groups] == [3, 1]
|
||||
ass = build_ass(words, 0.5, 6.0, "twitch.tv/alanzoka")
|
||||
assert "Credit" in ass and "twitch.tv/alanzoka" in ass
|
||||
assert "{isso}" not in ass and "(ISSO)" in ass # chave do texto falado não vira tag ASS
|
||||
assert "0:00:00.50" in ass # "olha" em 1.0 s da sessão = 0.5 s do corte
|
||||
|
||||
|
||||
def test_params_default_follows_cut_settings_defaults():
|
||||
# Pedido do dono (16/11/2026): cortes de 60 a 90 s por padrão — a heurística segue a configuração do corte.
|
||||
from app.layout import DEFAULTS
|
||||
assert (Params().min_s, Params().max_s) == (DEFAULTS["duration"]["minS"], DEFAULTS["duration"]["maxS"]) == (60, 90)
|
||||
|
||||
|
||||
def test_regression_calm_chat_has_no_false_positives():
|
||||
# Medido na live real (16/11/2026): ~0,6 msg/s, 3 mensagens com um emote "clip5k1hmm" viravam corte,
|
||||
# e o começo da gravação também.
|
||||
chat = calm_chat(180, rate=0.6)
|
||||
chat += [ChatMessage(100.2, "l i b e r t e s é!"), ChatMessage(100.5, "clip5k1hmm"), ChatMessage(101.0, "ff")]
|
||||
chat += [ChatMessage(3 + i * 0.3, "130") for i in range(5)]
|
||||
assert message_weight("clip5k1hmm")[0] == 1.0
|
||||
assert message_weight("CLIP IT")[1] == ["clip"]
|
||||
assert find_moments(180, chat, [], []) == []
|
||||
|
||||
|
||||
def test_ass_keeps_tags_lowercase_when_uppercasing_text():
|
||||
ass = build_ass([Word(1.0, 1.3, "olha"), Word(1.35, 1.6, "isso")], 0.0, 5.0, "")
|
||||
assert r"{\c&H00E5FF&}OLHA{\c&HFFFFFF&} ISSO" in ass and r"\C&" not in ass
|
||||
|
||||
|
||||
def test_regression_sparse_chat_still_finds_reactions():
|
||||
# Medido em 17/11/2026 (skipnho): 0,15 msg/s; reação de 6 mensagens em 8 s nunca passava do mínimo fixo de 12.
|
||||
chat = calm_chat(900, rate=0.15, seed=3)
|
||||
chat += [ChatMessage(500 + i, t) for i, t in enumerate(["KKKKKK", "kkkkkkk", "caralho", "KKKKK", "que isso", "kkkk"])]
|
||||
moments = [m for m in find_moments(900, chat, [], []) if m.source == "chat"]
|
||||
assert len(moments) == 1 and 495 <= moments[0].peak_s <= 510
|
||||
|
||||
|
||||
def test_sparse_chat_also_uses_audio():
|
||||
chat = calm_chat(600, rate=0.15, seed=4)
|
||||
loud = [-40.0] * 600
|
||||
for t in range(300, 306):
|
||||
loud[t] = -6.0
|
||||
moments = find_moments(600, chat, loud, [])
|
||||
assert any(m.source == "audio" and 295 <= m.peak_s <= 312 for m in moments)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- rosto do streamer (reaction.py)
|
||||
from app.reaction import FaceSecond # noqa: E402
|
||||
|
||||
|
||||
def calm_face(n: int, seed: int = 11) -> list[FaceSecond]:
|
||||
rng = random.Random(seed)
|
||||
return [FaceSecond(t, 1.0, 0.1, 0.5, 0.15, smile=rng.uniform(0.02, 0.22), jaw=rng.uniform(0.0, 0.01),
|
||||
surprise=0.002, frown=rng.uniform(0.01, 0.07), brow=rng.uniform(0.01, 0.05), blink=0.1,
|
||||
motion=rng.uniform(0.02, 0.15)) for t in range(n)]
|
||||
|
||||
|
||||
def laugh_at(face: list[FaceSecond], start: int, seconds: int = 6) -> list[FaceSecond]:
|
||||
for t in range(start, start + seconds):
|
||||
face[t].smile = 0.9
|
||||
return face
|
||||
|
||||
|
||||
def noisy_loudness(n: int, seed: int = 2) -> list[float]:
|
||||
rng = random.Random(seed)
|
||||
return [-30.0 + rng.uniform(-1.5, 1.5) for _ in range(n)]
|
||||
|
||||
|
||||
def test_face_none_or_empty_keeps_old_behavior():
|
||||
chat = calm_chat(600) + burst(300, 8, 25, "KKKKKKKKK")
|
||||
loud = noisy_loudness(600)
|
||||
base = find_moments(600, chat, loud, [])
|
||||
for face in (None, [], [FaceSecond(t) for t in range(600)]): # sem rosto em nenhum segundo
|
||||
again = find_moments(600, chat, loud, [], face=face)
|
||||
assert [(m.peak_s, m.start_s, m.end_s, m.score, m.source, m.reasons) for m in again] == \
|
||||
[(m.peak_s, m.start_s, m.end_s, m.score, m.source, m.reasons) for m in base]
|
||||
|
||||
|
||||
def test_face_reinforces_chat_moment_with_limited_bonus():
|
||||
chat = calm_chat(600) + burst(300, 8, 25, "KKKKKKKKK")
|
||||
base = find_moments(600, chat, [], [])[0]
|
||||
m = find_moments(600, chat, [], [], face=laugh_at(calm_face(600), 296))[0]
|
||||
assert (m.peak_s, m.start_s, m.end_s, m.source) == (base.peak_s, base.start_s, base.end_s, "chat")
|
||||
assert m.reasons["face"]["label"] == "risada" and m.reasons["face"]["onsetS"] == 296
|
||||
assert 0 < m.score - base.score <= Params().face_bonus_max + 1e-9
|
||||
|
||||
|
||||
def test_face_alone_never_becomes_a_clip():
|
||||
# Risada no rosto sem áudio nem chat se mexendo: não vira corte (o rosto reforça, não manda).
|
||||
face = laugh_at(calm_face(600), 300)
|
||||
assert find_moments(600, [], noisy_loudness(600), [], face=face) == []
|
||||
|
||||
|
||||
def test_face_with_audio_support_creates_face_moment():
|
||||
loud = noisy_loudness(600)
|
||||
for t in range(299, 305):
|
||||
loud[t] = -28.5 # um pouco acima do normal: sozinho não chega a pico de áudio
|
||||
assert find_moments(600, [], loud, []) == []
|
||||
moments = find_moments(600, [], loud, [], face=laugh_at(calm_face(600), 300))
|
||||
assert len(moments) == 1
|
||||
m = moments[0]
|
||||
assert m.source == "face" and 300 <= m.peak_s <= 305 and m.reasons["face"]["label"] == "risada"
|
||||
assert m.start_s < 300 - 5 and m.reasons["support"]["audioZ"] >= 1.0 and m.score > 0
|
||||
|
||||
|
||||
def test_face_moment_respects_live_settle():
|
||||
loud = noisy_loudness(316)
|
||||
for t in range(299, 305):
|
||||
loud[t] = -28.5
|
||||
assert find_moments(316, [], loud, [], live=True, face=laugh_at(calm_face(316), 300)) == []
|
||||
@@ -0,0 +1,255 @@
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from app.config import Settings
|
||||
from app.db import Database
|
||||
from app.judge import Judge, JudgeError, Verdict, _clean, build_prompt
|
||||
from app.main import create_app
|
||||
from app.scoring import ChatMessage, Word
|
||||
from app.sources import SourceError, parse_source
|
||||
from app.worker import Engine, wall_to_t
|
||||
|
||||
KEY = "k" * 40
|
||||
|
||||
|
||||
@pytest.mark.parametrize("url,platform,channel,kind", [
|
||||
("https://www.twitch.tv/alanzoka", "twitch", "alanzoka", "live"),
|
||||
("twitch.tv/Alanzoka?x=1", "twitch", "alanzoka", "live"),
|
||||
("https://www.twitch.tv/videos/123456789", "twitch", "", "vod"),
|
||||
("https://kick.com/gaules", "kick", "gaules", "live"),
|
||||
("https://www.youtube.com/@canal", "youtube", "@canal", "live"),
|
||||
("https://youtu.be/dQw4w9WgXcQ", "youtube", "", "vod"),
|
||||
("https://www.youtube.com/watch?v=dQw4w9WgXcQ", "youtube", "", "vod"),
|
||||
])
|
||||
def test_parse_source(url, platform, channel, kind):
|
||||
source = parse_source(url)
|
||||
assert (source.platform, source.channel, source.kind) == (platform, channel, kind)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("url", ["", "https://vimeo.com/1", "https://www.twitch.tv/directory", "ftp://twitch.tv/x"])
|
||||
def test_parse_source_rejects(url):
|
||||
with pytest.raises(SourceError):
|
||||
parse_source(url)
|
||||
|
||||
|
||||
def test_wall_to_t_maps_by_segment_arrival():
|
||||
# Bloco 0 (0–30 s) chegou às 1000; bloco 1 (30–60 s) chegou às 1060 (pausa de 30 s: anúncio filtrado).
|
||||
segments = [{"idx": 0, "start_s": 0.0, "end_s": 30.0, "wall_end": 1000.0},
|
||||
{"idx": 1, "start_s": 30.0, "end_s": 60.0, "wall_end": 1060.0}]
|
||||
assert wall_to_t(990.0, segments) == 20.0
|
||||
assert wall_to_t(960.0, segments) is None # antes de a gravação começar
|
||||
assert wall_to_t(1010.0, segments) == 30.0 # durante a pausa: cai no começo do bloco seguinte
|
||||
assert wall_to_t(1050.0, segments) == 50.0
|
||||
assert wall_to_t(1065.0, segments) == 65.0
|
||||
|
||||
|
||||
def test_judge_prompt_and_clean():
|
||||
words = [Word(100.0, 100.4, "não"), Word(100.5, 101.0, "acredito")]
|
||||
chat = [ChatMessage(104.0, "KKKKK"), ChatMessage(105.0, "clipa")]
|
||||
prompt = build_prompt("alanzoka", "twitch", 90, 120, 104, words, chat, {"peakRatio": 4.2})
|
||||
assert "[100s] não acredito" in prompt and "KKKKK" in prompt and "alanzoka" in prompt
|
||||
verdict = _clean({"keep": True, "score": 14, "start_s": 0, "end_s": 500, "title": "t", "caption": "c", "reason": "r"},
|
||||
200, 230, "m")
|
||||
# Padrão novo (16/11/2026): pode voltar até 2 min antes do candidato (a ação vem antes do comentário), nunca
|
||||
# além; duração de 60 a 90 s.
|
||||
assert verdict.score == 10.0 and verdict.start_s == 80 and verdict.end_s == 170
|
||||
assert "Duração do corte: 60 a 90 s" in prompt and "Janela disponível: 0s a 135s" in prompt
|
||||
old = _clean({"keep": True, "score": 8, "start_s": 0, "end_s": 500, "title": "t", "caption": "c", "reason": "r"},
|
||||
90, 120, "m", lo=30, hi=135, min_s=15, max_s=59)
|
||||
assert (old.start_s, old.end_s) == (30, 89) # configuração antiga (15–59 s) continua valendo se o canal pedir
|
||||
longer = _clean({"keep": True, "score": 8, "start_s": 70, "end_s": 160, "title": "t", "caption": "c", "reason": "r"},
|
||||
90, 120, "m", lo=30, hi=135, max_s=90)
|
||||
assert (longer.start_s, longer.end_s) == (70, 135) # duração máxima configurável (até 180 s)
|
||||
|
||||
|
||||
class FakeJudge(Judge):
|
||||
def __init__(self, keep=True, score=8.0):
|
||||
super().__init__("codex", "fake", Path("."))
|
||||
self.keep, self.score_value, self.calls = keep, score, 0
|
||||
|
||||
def ask(self, system, prompt, schema, images, **_kwargs):
|
||||
# Nunca chama a CLI de verdade nos testes (gastaria a cota do dono): analista, varredura e "IA sugere"
|
||||
# seguem o caminho de falha da IA, que o serviço já trata.
|
||||
raise JudgeError("IA falsa nos testes")
|
||||
|
||||
def judge(self, prompt, start_s, end_s, images=None, **_limits):
|
||||
self.calls += 1
|
||||
return Verdict(self.keep, self.score_value, start_s, end_s, "Título da IA", "legenda #cortes", "motivo", "fake")
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def env(tmp_path):
|
||||
settings = Settings.load(env_file=tmp_path / "none.env", service_key=KEY, data_dir=tmp_path / "data",
|
||||
clips_dir=tmp_path / "clips", judge_provider="codex", voice_url=None, voice_key=None)
|
||||
db = Database(settings.data_dir / "clipper.db")
|
||||
engine = Engine(settings, db, judge=FakeJudge())
|
||||
app = create_app(settings, engine, start_engine=False)
|
||||
return TestClient(app), engine
|
||||
|
||||
|
||||
def auth():
|
||||
return {"X-Service-Key": KEY}
|
||||
|
||||
|
||||
def test_auth_required(env):
|
||||
client, _ = env
|
||||
assert client.get("/health").status_code == 200
|
||||
assert client.get("/v1/channels").status_code == 401
|
||||
assert client.get("/v1/channels", headers={"X-Service-Key": "errada"}).status_code == 401
|
||||
|
||||
|
||||
def test_channel_crud(env):
|
||||
client, _ = env
|
||||
r = client.post("/v1/channels", json={"url": "https://www.twitch.tv/alanzoka"}, headers=auth())
|
||||
assert r.status_code == 201 and r.json()["id"] == "twitch-alanzoka" and r.json()["displayName"] == "alanzoka"
|
||||
assert client.post("/v1/channels", json={"url": "twitch.tv/alanzoka"}, headers=auth()).status_code == 409
|
||||
assert client.post("/v1/channels", json={"url": "https://www.twitch.tv/videos/1"}, headers=auth()).status_code == 400
|
||||
r = client.patch("/v1/channels/twitch-alanzoka", json={"monitor": False, "displayName": "Alanzoka"}, headers=auth())
|
||||
assert r.json()["monitor"] is False and r.json()["displayName"] == "Alanzoka"
|
||||
assert client.delete("/v1/channels/twitch-alanzoka", headers=auth()).status_code == 204
|
||||
assert client.get("/v1/channels", headers=auth()).json()["channels"] == []
|
||||
|
||||
|
||||
def seed_session(engine: Engine, duration: int = 600, burst_at: int = 300) -> int:
|
||||
db = engine.db
|
||||
cur = db.run("INSERT INTO sessions (platform, kind, url, status, dir, started_at, duration_s) VALUES"
|
||||
" ('twitch', 'live', 'https://www.twitch.tv/alanzoka', 'processing', '', '2026-11-16T00:00:00+00:00', ?)",
|
||||
duration)
|
||||
sid = cur.lastrowid
|
||||
base_wall = 10_000.0
|
||||
for i in range(duration // 30):
|
||||
db.run("INSERT INTO segments (session_id, idx, file, start_s, end_s, wall_end, analyzed, loudness_json, words_json)"
|
||||
" VALUES (?, ?, ?, ?, ?, ?, 1, ?, ?)",
|
||||
sid, i, f"x/seg_{i:05d}.ts", i * 30.0, (i + 1) * 30.0, base_wall + (i + 1) * 30.0,
|
||||
json.dumps([-30.0] * 30), json.dumps([[i * 30 + 1.0, i * 30 + 1.5, "fala"]]))
|
||||
rows = []
|
||||
for t in range(duration):
|
||||
rows.append((sid, base_wall + t + 0.5, "u", "salve"))
|
||||
rows.append((sid, base_wall + t + 0.7, "u", "oi"))
|
||||
for s in range(8):
|
||||
for k in range(25):
|
||||
rows.append((sid, base_wall + burst_at + s + k / 25, "u", "KKKKKKK"))
|
||||
db.many("INSERT INTO chat (session_id, wall, user, text) VALUES (?, ?, ?, ?)", rows)
|
||||
return sid
|
||||
|
||||
|
||||
def test_pipeline_finds_judges_and_lists_clip(env):
|
||||
client, engine = env
|
||||
sid = seed_session(engine)
|
||||
session = engine.db.get("SELECT * FROM sessions WHERE id = ?", sid)
|
||||
assert engine.find_new_clips(session) == 1
|
||||
assert engine.find_new_clips(session) == 0 # não repete o mesmo trecho
|
||||
engine.judge_candidates()
|
||||
clip = client.get("/v1/clips", headers=auth()).json()["clips"][0]
|
||||
assert clip["status"] == "pending" and clip["title"] == "Título da IA"
|
||||
assert "twitch.tv/alanzoka" in clip["caption"] # crédito do canal sempre na legenda
|
||||
assert clip["judge"]["score"] == 8.0
|
||||
# aprovar antes do render é recusado
|
||||
assert client.patch(f"/v1/clips/{clip['id']}", json={"status": "approved"}, headers=auth()).status_code == 400
|
||||
# mudar o trecho volta para a fila de render
|
||||
r = client.patch(f"/v1/clips/{clip['id']}", json={"startS": clip["startS"] - 3}, headers=auth())
|
||||
assert r.json()["status"] == "pending"
|
||||
tl = client.get(f"/v1/sessions/{sid}/timeline", headers=auth()).json()
|
||||
assert tl["durationS"] == 600 and max(tl["messagesPerS"]) >= 25
|
||||
|
||||
|
||||
def test_judge_config_persists(env, tmp_path):
|
||||
client, engine = env
|
||||
r = client.get("/v1/judge", headers=auth()).json()
|
||||
assert r["provider"] == "codex" and "codex" in r["models"]
|
||||
r = client.put("/v1/judge", json={"provider": "claude", "model": "", "minScore": 7}, headers=auth())
|
||||
assert r.status_code == 200 and r.json()["model"] == "haiku" and r.json()["minScore"] == 7
|
||||
assert client.put("/v1/judge", json={"provider": "gpt", "model": ""}, headers=auth()).status_code == 422
|
||||
assert client.put("/v1/judge", json={"provider": "codex", "model": "x; rm -rf"}, headers=auth()).status_code == 422
|
||||
saved = {r["key"]: r["value"] for r in engine.db.all("SELECT * FROM settings")}
|
||||
assert saved == {"judge_provider": "claude", "judge_model": "haiku", "judge_min_score": "7.0", "judge_analyst_model": ""}
|
||||
|
||||
|
||||
def test_manual_clip_is_never_discarded(env):
|
||||
client, engine = env
|
||||
engine.judge = FakeJudge(keep=False, score=1)
|
||||
sid = seed_session(engine)
|
||||
r = client.post(f"/v1/sessions/{sid}/clips", json={"lastS": 40}, headers=auth())
|
||||
assert r.status_code == 201 and r.json()["startS"] == 560
|
||||
engine.judge_candidates()
|
||||
clip = client.get(f"/v1/clips/{r.json()['id']}", headers=auth()).json()
|
||||
assert clip["status"] == "pending" and (clip["startS"], clip["endS"]) == (560, 600)
|
||||
|
||||
|
||||
def test_codex_models_reads_cache(tmp_path):
|
||||
from app.judge import codex_models
|
||||
cache = tmp_path / "m.json"
|
||||
cache.write_text(json.dumps({"models": [{"slug": "gpt-6-luna", "display_name": "GPT-6-Luna", "visibility": "list"},
|
||||
{"slug": "hidden", "visibility": "hide"}]}))
|
||||
assert [m["id"] for m in codex_models(cache)] == ["gpt-6-luna"]
|
||||
assert codex_models(tmp_path / "nao-existe.json")[0]["id"] == "gpt-6-luna"
|
||||
|
||||
|
||||
def test_codex_lean_overrides(tmp_path):
|
||||
from app.judge import codex_lean_overrides
|
||||
config = tmp_path / "config.toml"
|
||||
config.write_text('[mcp_servers.node_repl]\ncommand = "x"\n[mcp_servers.node_repl.env]\n'
|
||||
'[plugins."computer-use@openai-bundled"]\nenabled = true\n')
|
||||
plain = codex_lean_overrides(False, config)
|
||||
assert plain.count("-c") == len(plain) // 2
|
||||
assert "features.shell_tool=false" in plain and "features.computer_use=false" in plain
|
||||
# Um servidor por nome (a subtabela .env não vira outro servidor) e o plugin presente no config.
|
||||
assert plain.count("mcp_servers.node_repl.enabled=false") == 1
|
||||
assert 'plugins."computer-use@openai-bundled".enabled=false' in plain
|
||||
assert not any("unified-computer-use" in a for a in plain)
|
||||
# Com busca na web, as ferramentas de execução ficam (a web do Codex depende delas).
|
||||
searching = codex_lean_overrides(True, config)
|
||||
assert "features.shell_tool=false" not in searching and "features.computer_use=false" in searching
|
||||
assert codex_lean_overrides(False, tmp_path / "nao-existe.toml")[-1] == "features.browser_use=false"
|
||||
|
||||
|
||||
def test_judge_discard_keeps_record(env):
|
||||
client, engine = env
|
||||
engine.judge = FakeJudge(keep=False, score=3)
|
||||
sid = seed_session(engine)
|
||||
engine.find_new_clips(engine.db.get("SELECT * FROM sessions WHERE id = ?", sid))
|
||||
engine.judge_candidates()
|
||||
clip = client.get("/v1/clips?status=discarded", headers=auth()).json()["clips"][0]
|
||||
assert clip["judge"]["keep"] is False
|
||||
r = client.post(f"/v1/clips/{clip['id']}/render", headers=auth())
|
||||
assert r.json()["status"] == "pending"
|
||||
|
||||
|
||||
def test_data_and_output_dirs_can_be_isolated(tmp_path, monkeypatch):
|
||||
"""CLIPPER_DATA_DIR/CLIPPER_OUTPUT_DIR: instância de teste isolada; padrão igual ao de antes; fora do repo = erro."""
|
||||
from app.config import REPO_ROOT, ConfigError
|
||||
|
||||
for name in ("CLIPPER_DATA_DIR", "CLIPPER_OUTPUT_DIR"):
|
||||
monkeypatch.delenv(name, raising=False)
|
||||
s = Settings.load(env_file=tmp_path / "none.env")
|
||||
assert s.data_dir == REPO_ROOT / "data" / "clipper" and s.clips_dir == REPO_ROOT / "output" / "clipper"
|
||||
monkeypatch.setenv("CLIPPER_DATA_DIR", "output/x-test/data")
|
||||
monkeypatch.setenv("CLIPPER_OUTPUT_DIR", str(REPO_ROOT / "output" / "x-test" / "clips"))
|
||||
s = Settings.load(env_file=tmp_path / "none.env")
|
||||
assert s.data_dir == REPO_ROOT / "output" / "x-test" / "data"
|
||||
assert (s.data_dir / "sessions" / "1").relative_to(REPO_ROOT).as_posix() == "output/x-test/data/sessions/1"
|
||||
assert s.clips_dir == REPO_ROOT / "output" / "x-test" / "clips"
|
||||
monkeypatch.setenv("CLIPPER_DATA_DIR", str(tmp_path / "fora"))
|
||||
with pytest.raises(ConfigError):
|
||||
Settings.load(env_file=tmp_path / "none.env")
|
||||
|
||||
|
||||
def test_list_clips_filters_by_channel_and_ids(env):
|
||||
"""Filtros usados pelo despachante de publicação do painel: fonte (`channel`) e lista de `ids`."""
|
||||
client, engine = env
|
||||
client.post("/v1/channels", json={"url": "https://www.twitch.tv/alanzoka"}, headers=auth())
|
||||
sid = seed_session(engine)
|
||||
engine.db.run("UPDATE sessions SET channel_id = 'twitch-alanzoka' WHERE id = ?", sid)
|
||||
other = seed_session(engine)
|
||||
for s in (sid, other):
|
||||
engine.db.run("INSERT INTO clips (session_id, peak_s, start_s, end_s, score, source, status, created_at, updated_at)"
|
||||
" VALUES (?, 10, 0, 20, 5, 'manual', 'ready', 'x', 'x')", s)
|
||||
mine = client.get("/v1/clips?status=ready,approved&channel=twitch-alanzoka", headers=auth()).json()["clips"]
|
||||
assert [c["channelId"] for c in mine] == ["twitch-alanzoka"]
|
||||
all_ids = [c["id"] for c in client.get("/v1/clips", headers=auth()).json()["clips"]]
|
||||
picked = client.get(f"/v1/clips?ids={all_ids[0]}", headers=auth()).json()["clips"]
|
||||
assert [c["id"] for c in picked] == [all_ids[0]]
|
||||
assert client.get("/v1/clips?ids=1,abc", headers=auth()).status_code == 400
|
||||
Reference in New Issue
Block a user