Files
CenaForge/clipper/tests/test_scoring.py
T
MateuusandClaude Opus 5.5 84f30bbc2d 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>
2026-11-17 16:35:09 -03:00

197 lines
8.6 KiB
Python

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)) == []