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