"""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]