clipwright/tests/e2e/api/test_scenes_reframe.py
pedro-bento 0040aa49da
All checks were successful
CI / dashboard-e2e (push) Successful in 1m44s
CI / unit (push) Successful in 29s
CI / backend-e2e (push) Successful in 1m17s
test/e2e-coverage (#5)
Reviewed-on: #5
Co-authored-by: pedro-bento <mail@pbento.pt>
Co-committed-by: pedro-bento <mail@pbento.pt>
2026-10-04 22:28:46 +01:00

256 lines
10 KiB
Python

"""L2 API editing E2E: GET .../scenes and POST /api/clip/reframe.
``/scenes`` cuts the clip from source with real ffmpeg and encodes a preview,
but the ML detectors it calls live in the heavy ``clipwright.pipeline.main``
module (absent in the thin E2E env). A fake module is injected into
``sys.modules`` returning deterministic scene/face data — the real module is
never imported. The re-render path is stubbed at ``recut.perform_recut``.
"""
import json
import os
import shutil
import sys
import types
import pytest
pytestmark = pytest.mark.e2e
app_module = pytest.importorskip("clipwright.api.app")
from clipwright.media import recut # noqa: E402
TRANSCRIPT = {
"language": "en",
"segments": [{
"start": 0.0, "end": 6.0, "text": "hello there",
"words": [{"word": "hello", "start": 1.0, "end": 1.4},
{"word": "there", "start": 3.0, "end": 3.4}],
}],
}
class _Frames:
def __init__(self, n):
self._n = n
def get_frames(self):
return self._n
def _fake_main():
"""The three functions app.py's scenes builder actually calls."""
fake = types.ModuleType("clipwright.pipeline.main")
def detect_scenes(path):
return [(_Frames(0), _Frames(30)), (_Frames(30), _Frames(60))], 10.0
def get_video_resolution(path):
return 320, 180
def detect_face_candidates(frame):
return [{"box": [100, 40, 60, 60]}]
fake.detect_scenes = detect_scenes
fake.get_video_resolution = get_video_resolution
fake.detect_face_candidates = detect_face_candidates
return fake
@pytest.fixture
def fake_pipeline_main(monkeypatch):
import clipwright.pipeline as pipeline_pkg
fake = _fake_main()
monkeypatch.setitem(sys.modules, "clipwright.pipeline.main", fake)
# Belt and braces: `from clipwright.pipeline import main` resolves the
# parent attribute before falling back to the sys.modules entry.
monkeypatch.setattr(pipeline_pkg, "main", fake, raising=False)
return fake
def _make_job(app_state, media_factory, job_id="job-scenes", base="scenes",
output_format="auto", crop_overrides=None):
job_dir = app_state.out / job_id
job_dir.mkdir(parents=True, exist_ok=True)
shutil.copy(media_factory.six, job_dir / f"{base}_clip_1.mp4")
# Source lives in uploads/<job_id>_*, which is where _locate_source looks
# first for an upload job.
shutil.copy(media_factory.six, app_state.up / f"{job_id}_source.mp4")
clip = {
"start": 0.0,
"end": 6.0,
"video_title_for_youtube_short": "Scenes clip",
"video_url": f"/videos/{job_id}/{base}_clip_1.mp4",
}
if crop_overrides is not None:
clip["crop_overrides"] = crop_overrides
(job_dir / f"{base}_metadata.json").write_text(json.dumps({
"shorts": [clip],
"transcript": TRANSCRIPT,
"output_format": output_format,
"cost_analysis": {},
}))
app_module.jobs[job_id] = {
"status": "completed",
"logs": [],
"result": {"clips": [dict(clip)], "cost_analysis": {}},
"user_id": None,
}
return {"job_id": job_id, "base": base, "dir": job_dir,
"meta": job_dir / f"{base}_metadata.json",
"source": app_state.up / f"{job_id}_source.mp4"}
@pytest.fixture
def scenes_job(app_state, media_factory):
return _make_job(app_state, media_factory)
@pytest.fixture
def fake_recut(monkeypatch):
calls = []
def fake(**kwargs):
calls.append(kwargs)
name = f"recut_1_{kwargs['clean_name']}"
with open(os.path.join(kwargs["output_dir"], name), "wb") as fh:
fh.write(b"recut")
return name, name
monkeypatch.setattr(recut, "perform_recut", fake)
return calls
# --- GET /api/clip/{job}/{clip}/scenes --------------------------------------
class TestScenes:
async def test_success_lists_scenes_and_preview(self, client, scenes_job,
fake_pipeline_main):
resp = await client.get(f"/api/clip/{scenes_job['job_id']}/0/scenes")
assert resp.status_code == 200, resp.text
data = resp.json()
assert data["source_width"] == 320
assert data["source_height"] == 180
# 9:16 crop of a 320x180 source: min(320, 180*9/16) / 320.
assert data["crop_width_fraction"] == pytest.approx(
(180 * 9 / 16) / 320, abs=1e-3)
assert data["saved_overrides"] == {}
assert len(data["scenes"]) == 2
first = data["scenes"][0]
assert first["index"] == 0
assert (first["start"], first["end"]) == (0.0, 3.0)
# The face box [100,40,60,60] centres at x=130/320, y=70/180.
assert first["suggested_center"] == pytest.approx(130 / 320, abs=1e-3)
assert first["suggested_center_y"] == pytest.approx(70 / 180, abs=1e-3)
# The preview and the per-scene thumbnails were really written.
assert data["preview_url"] == (
f"/videos/{scenes_job['job_id']}/temp_preview_0.mp4")
assert (scenes_job["dir"] / "temp_preview_0.mp4").is_file()
assert first["thumbnail_url"].endswith("temp_scene_0_000.jpg")
assert (scenes_job["dir"] / "temp_scene_0_000.jpg").is_file()
# The temp cut was cleaned up (the canonical clip is scenes_clip_1.mp4,
# so scope the glob to the per-call work token).
assert not list(scenes_job["dir"].glob("scenes_0_*.mp4"))
async def test_serves_saved_overrides(self, client, app_state,
media_factory, fake_pipeline_main):
job = _make_job(app_state, media_factory, job_id="job-scenes-ov",
base="ov", crop_overrides={"0": 0.25})
data = (await client.get(f"/api/clip/{job['job_id']}/0/scenes")).json()
assert data["saved_overrides"] == {"0": 0.25}
async def test_horizontal_400(self, client, app_state, media_factory,
fake_pipeline_main):
job = _make_job(app_state, media_factory, job_id="job-scenes-h",
base="h", output_format="horizontal")
resp = await client.get(f"/api/clip/{job['job_id']}/0/scenes")
assert resp.status_code == 400
async def test_no_source_409(self, client, scenes_job, fake_pipeline_main):
os.remove(scenes_job["source"])
resp = await client.get(f"/api/clip/{scenes_job['job_id']}/0/scenes")
assert resp.status_code == 409
async def test_404_unknown_job(self, client, fake_pipeline_main):
assert (await client.get(
"/api/clip/nope/0/scenes")).status_code == 404
async def test_404_missing_metadata(self, client, scenes_job,
fake_pipeline_main):
os.remove(scenes_job["meta"])
assert (await client.get(
f"/api/clip/{scenes_job['job_id']}/0/scenes")).status_code == 404
async def test_404_clip_out_of_range(self, client, scenes_job,
fake_pipeline_main):
assert (await client.get(
f"/api/clip/{scenes_job['job_id']}/4/scenes")).status_code == 404
# --- POST /api/clip/reframe -------------------------------------------------
class TestReframe:
async def test_success_persists_overrides(self, client, scenes_job,
fake_recut):
resp = await client.post("/api/clip/reframe", json={
"job_id": scenes_job["job_id"], "clip_index": 0,
"crop_overrides": {
"0": 0.2,
"1": {"top": 0.6, "bottom": {"x": 0.3, "y": 0.4}},
}})
assert resp.status_code == 200, resp.text
data = resp.json()
assert data["framed_scenes"] == [0, 1]
call = fake_recut[0]
assert call["input_path"].endswith(f"{scenes_job['job_id']}_source.mp4")
assert call["reframe"] is True
assert call["crop_overrides"][0] == 0.2
assert call["crop_overrides"][1]["top"] == {"x": 0.6, "y": 0.5}
assert call["crop_overrides"][1]["bottom"] == {"x": 0.3, "y": 0.4}
assert call["captions_transcript"]["segments"][0]["words"]
meta = json.loads(scenes_job["meta"].read_text())
stored = meta["shorts"][0]
assert stored["crop_overrides"]["0"] == 0.2
assert stored["video_url"] == data["new_video_url"]
mem = app_module.jobs[scenes_job["job_id"]]["result"]["clips"][0]
assert mem["crop_overrides"]["0"] == 0.2
async def test_400_no_usable_overrides(self, client, scenes_job,
fake_recut):
for overrides in ({}, {"nope": "x"}, {"0": "garbage"}):
resp = await client.post("/api/clip/reframe", json={
"job_id": scenes_job["job_id"], "clip_index": 0,
"crop_overrides": overrides})
assert resp.status_code == 400, overrides
assert fake_recut == []
async def test_horizontal_400(self, client, app_state, media_factory,
fake_recut):
job = _make_job(app_state, media_factory, job_id="job-reframe-h",
base="rh", output_format="horizontal")
resp = await client.post("/api/clip/reframe", json={
"job_id": job["job_id"], "clip_index": 0,
"crop_overrides": {"0": 0.5}})
assert resp.status_code == 400
assert fake_recut == []
async def test_409_no_source(self, client, scenes_job, fake_recut):
os.remove(scenes_job["source"])
resp = await client.post("/api/clip/reframe", json={
"job_id": scenes_job["job_id"], "clip_index": 0,
"crop_overrides": {"0": 0.5}})
assert resp.status_code == 409
assert fake_recut == []
async def test_404_unknown_job(self, client, fake_recut):
assert (await client.post("/api/clip/reframe", json={
"job_id": "nope", "clip_index": 0,
"crop_overrides": {"0": 0.5}})).status_code == 404
async def test_404_clip_out_of_range(self, client, scenes_job, fake_recut):
assert (await client.post("/api/clip/reframe", json={
"job_id": scenes_job["job_id"], "clip_index": 4,
"crop_overrides": {"0": 0.5}})).status_code == 404