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,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"
|
||||
Reference in New Issue
Block a user