"""L2 API editing E2E: POST /api/subtitle and POST /api/subtitle/remove. The burn is REAL ffmpeg over a real fixture video (the whole point of this lane): the endpoint's SRT/ASS generation, the burn filter and the persistence all run for real. Only the clip itself is supplied by the media factory. """ import json import os import shutil import subprocess import pytest pytestmark = pytest.mark.e2e app_module = pytest.importorskip("clipwright.api.app") TRANSCRIPT = { "language": "en", "segments": [{ "start": 0.0, "end": 6.0, "text": "hello world", "words": [{"word": "hello", "start": 1.0, "end": 1.4}, {"word": "world", "start": 2.0, "end": 2.4}], }], } def _probe(path): out = subprocess.run( ["ffprobe", "-v", "error", "-show_entries", "stream=codec_type:format=duration", "-of", "json", str(path)], capture_output=True, text=True, check=True) return json.loads(out.stdout) def _make_job(app_state, media_factory, job_id="job-sub", base="sub", transcript=TRANSCRIPT): 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") clip = { "start": 0.0, "end": 6.0, "video_title_for_youtube_short": "Sub clip", "video_url": f"/videos/{job_id}/{base}_clip_1.mp4", } meta = {"shorts": [clip], "output_format": "auto", "cost_analysis": {}} if transcript is not None: meta["transcript"] = transcript (job_dir / f"{base}_metadata.json").write_text(json.dumps(meta)) 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"} @pytest.fixture def sub_job(app_state, media_factory): return _make_job(app_state, media_factory) def _output_file(job): matches = list(job["dir"].glob("subtitled_*_sub_clip_1.mp4")) assert len(matches) == 1, matches return matches[0] # --- POST /api/subtitle ----------------------------------------------------- class TestSubtitle: async def test_preset_unknown_400(self, client, sub_job): resp = await client.post("/api/subtitle", json={ "job_id": sub_job["job_id"], "clip_index": 0, "preset": "nope"}) assert resp.status_code == 400 assert "preset" in resp.json()["detail"].lower() async def test_classic_burn_is_playable(self, client, sub_job): resp = await client.post("/api/subtitle", json={ "job_id": sub_job["job_id"], "clip_index": 0, "style": "classic"}) assert resp.status_code == 200, resp.text data = resp.json() assert data["success"] is True assert data["new_video_url"].startswith( f"/videos/{sub_job['job_id']}/subtitled_") assert data["new_video_url"].endswith("_sub_clip_1.mp4") out = _output_file(sub_job) assert out.stat().st_size > 0 assert "video" in {s["codec_type"] for s in _probe(out)["streams"]} # The SRT sidecar was generated too. assert list(sub_job["dir"].glob("subs_0_*.srt")) meta = json.loads(sub_job["meta"].read_text()) assert meta["shorts"][0]["video_url"] == data["new_video_url"] mem = app_module.jobs[sub_job["job_id"]]["result"]["clips"][0] assert mem["video_url"] == data["new_video_url"] async def test_karaoke_preset_burns_ass(self, client, sub_job): resp = await client.post("/api/subtitle", json={ "job_id": sub_job["job_id"], "clip_index": 0, "preset": "default"}) assert resp.status_code == 200, resp.text assert _output_file(sub_job).is_file() # Karaoke renders an ASS sidecar (its own per-word styles). assert list(sub_job["dir"].glob("subs_0_*.ass")) async def test_words_path_burns_edited_captions(self, client, sub_job): resp = await client.post("/api/subtitle", json={ "job_id": sub_job["job_id"], "clip_index": 0, "style": "classic", "words": [ {"text": "edited", "startMs": 500, "endMs": 900}, {"text": "captions", "startMs": 1200, "endMs": 1800}, ]}) assert resp.status_code == 200, resp.text assert _output_file(sub_job).is_file() srt = list(sub_job["dir"].glob("subs_0_*.srt"))[0] assert "edited" in srt.read_text(encoding="utf-8-sig").lower() async def test_too_many_words_400(self, client, sub_job): words = [{"text": "w", "startMs": i, "endMs": i + 1} for i in range(2001)] resp = await client.post("/api/subtitle", json={ "job_id": sub_job["job_id"], "clip_index": 0, "words": words}) assert resp.status_code == 400 assert "Too many" in resp.json()["detail"] async def test_no_words_in_range_is_wrapped_as_500(self, client, app_state, media_factory): # generate_srt() returns False and the route raises its 400 INSIDE the # try whose catch-all turns it into a 500 (documented deviation from # the 400 the spec expected). job = _make_job(app_state, media_factory, job_id="job-sub-nowords", base="nw", transcript={ "language": "en", "segments": [{ "start": 100.0, "end": 106.0, "text": "late", "words": [{"word": "late", "start": 100.0, "end": 100.4}], }], }) resp = await client.post("/api/subtitle", json={ "job_id": job["job_id"], "clip_index": 0, "style": "classic"}) assert resp.status_code == 500 assert "words" in resp.json()["detail"].lower() async def test_missing_transcript_400(self, client, app_state, media_factory): job = _make_job(app_state, media_factory, job_id="job-sub-notx", base="nt", transcript=None) resp = await client.post("/api/subtitle", json={ "job_id": job["job_id"], "clip_index": 0}) assert resp.status_code == 400 async def test_404_unknown_job(self, client): resp = await client.post("/api/subtitle", json={ "job_id": "nope", "clip_index": 0}) assert resp.status_code == 404 async def test_404_missing_metadata(self, client, sub_job): os.remove(sub_job["meta"]) resp = await client.post("/api/subtitle", json={ "job_id": sub_job["job_id"], "clip_index": 0}) assert resp.status_code == 404 async def test_404_clip_out_of_range(self, client, sub_job): resp = await client.post("/api/subtitle", json={ "job_id": sub_job["job_id"], "clip_index": 5}) assert resp.status_code == 404 async def test_404_missing_file(self, client, sub_job): os.remove(sub_job["dir"] / "sub_clip_1.mp4") resp = await client.post("/api/subtitle", json={ "job_id": sub_job["job_id"], "clip_index": 0}) assert resp.status_code == 404 # --- POST /api/subtitle/remove ---------------------------------------------- class TestRemoveSubtitles: async def test_points_back_at_clean_file(self, client, sub_job): burn = await client.post("/api/subtitle", json={ "job_id": sub_job["job_id"], "clip_index": 0, "style": "classic"}) assert burn.status_code == 200 resp = await client.post("/api/subtitle/remove", json={ "job_id": sub_job["job_id"], "clip_index": 0}) assert resp.status_code == 200, resp.text data = resp.json() assert data["new_video_url"] == ( f"/videos/{sub_job['job_id']}/sub_clip_1.mp4") meta = json.loads(sub_job["meta"].read_text()) assert meta["shorts"][0]["video_url"] == data["new_video_url"] mem = app_module.jobs[sub_job["job_id"]]["result"]["clips"][0] assert mem["video_url"] == data["new_video_url"] async def test_404_original_gone(self, client, sub_job): resp = await client.post("/api/subtitle/remove", json={ "job_id": sub_job["job_id"], "clip_index": 0, "input_filename": "gone.mp4"}) assert resp.status_code == 404 async def test_404_unknown_job(self, client): resp = await client.post("/api/subtitle/remove", json={ "job_id": "nope", "clip_index": 0}) assert resp.status_code == 404