diff --git a/CLAUDE.md b/CLAUDE.md index 2d7e041..bca9817 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -237,6 +237,18 @@ Stripe retry the same doomed event for three days. ### Concurrency Model Async job queue with semaphore-based concurrency control. Configure via `MAX_CONCURRENT_JOBS` env var (default: 5). Jobs auto-cleanup after 1 hour. +### Deploys interrupt running jobs + +Every push to `main` redeploys the API container and Coolify does not wait for +the queue to drain. An interrupted job is re-enqueued on startup from its +`.resume.json` manifest (`app.py:_resume_interrupted_jobs`, max 2 attempts) and +re-runs with the same command and output directory. `main.py` leaves the +finished transcript in that directory (`.transcript_checkpoint.json`) so the +re-run skips the slow, paid transcription; the download and the +Gemini analysis still repeat. Before pushing: batch small commits (tests, docs) +with the next real change instead of giving them their own deploy, and check +that no job is mid-flight in the prod container. + ## Environment Variables **Server-side (.env):** diff --git a/main.py b/main.py index 8fc70e0..a4d1d32 100644 --- a/main.py +++ b/main.py @@ -1318,6 +1318,69 @@ def process_video_to_vertical(input_video, final_output_video, aspect_ratio=ASPE return True +# --- Transcript checkpoint (survive a redeploy without paying twice) --------- +# A job interrupted by a container restart is re-run from its resume manifest +# (app.py) with the SAME output directory. Transcription is the slow, paid part +# of the pipeline that ran before the interruption, so the finished transcript +# is left in the job directory and picked up by the re-run instead of +# transcribing again. Same shape and same validation as --transcript. +TRANSCRIPT_CHECKPOINT = ".transcript_checkpoint.json" + + +def _checkpoint_source_key(input_video, duration): + """What ties a checkpoint to ONE source. Not the path: a resumed cloud job + re-downloads to the same name, and the CLI may be pointed at a different + file in a directory where an earlier run died. Name plus duration is what + both the server and a careful CLI user keep stable across the two runs.""" + return {"name": os.path.basename(input_video), "duration": round(float(duration), 1)} + + +def save_transcript_checkpoint(output_dir, transcript, input_video, duration): + """Best effort: a failure here must never fail the job.""" + try: + payload = {"source": _checkpoint_source_key(input_video, duration), + "transcript": transcript} + with open(os.path.join(output_dir, TRANSCRIPT_CHECKPOINT), "w") as f: + json.dump(payload, f) + except Exception as e: + print(f"⚠️ Could not save transcript checkpoint: {e}") + + +def load_transcript_checkpoint(output_dir, input_video, duration): + """The transcript an interrupted run left behind for THIS source, or None. + + A checkpoint for a different source (a CLI run that died, then a new video + processed in the same directory) is ignored, not reused.""" + path = os.path.join(output_dir, TRANSCRIPT_CHECKPOINT) + if not os.path.isfile(path): + return None + try: + with open(path) as f: + payload = json.load(f) + source = payload.get("source") or {} + expected = _checkpoint_source_key(input_video, duration) + if source.get("name") != expected["name"] \ + or abs(float(source.get("duration", -1)) - expected["duration"]) > 0.5: + print("⏭️ Transcript checkpoint belongs to another source — ignoring it.") + return None + transcript = payload.get("transcript") or {} + if not transcript.get("segments"): + raise ValueError("checkpoint has no segments") + return transcript + except Exception as e: + print(f"⚠️ Ignoring unusable transcript checkpoint ({e}).") + return None + + +def clear_transcript_checkpoint(output_dir): + try: + os.remove(os.path.join(output_dir, TRANSCRIPT_CHECKPOINT)) + except FileNotFoundError: + pass + except Exception as e: + print(f"⚠️ Could not remove transcript checkpoint: {e}") + + def transcribe_video(video_path): print("🎙️ Transcribing video...") from transcribe_backends import transcribe_media @@ -1681,9 +1744,15 @@ if __name__ == '__main__': except Exception as e: print(f"⚠️ Could not use precomputed transcript ({e}) — transcribing normally.") transcript = None + if transcript is None: + transcript = load_transcript_checkpoint(output_dir, input_video, duration) + if transcript is not None: + print(f"♻️ Reusing the transcript from the interrupted run " + f"({len(transcript['segments'])} segments) — skipping transcription.") if transcript is None: try: transcript = transcribe_video(input_video) + save_transcript_checkpoint(output_dir, transcript, input_video, duration) except NoAudioError as e: print(f"🔇 {e} — switching to visual analysis.") @@ -1796,6 +1865,9 @@ if __name__ == '__main__': if args.url and not args.keep_original and os.path.exists(input_video): os.remove(input_video) print(f"🗑️ Cleaned up downloaded video.") + # The job finished: a later run in this directory must transcribe afresh. + if not args.skip_analysis: + clear_transcript_checkpoint(output_dir) total_time = time.time() - script_start_time print(f"\n⏱️ Total execution time: {total_time:.2f}s") diff --git a/tests/test_transcript_checkpoint.py b/tests/test_transcript_checkpoint.py new file mode 100644 index 0000000..b09c4b9 --- /dev/null +++ b/tests/test_transcript_checkpoint.py @@ -0,0 +1,86 @@ +"""Transcript checkpoint: a job re-run after a container restart must not +transcribe (the slow, paid stage) a second time, and must never reuse the +transcript of a DIFFERENT video. + +app.py re-enqueues an interrupted job with the same command and the same +output directory (resume manifest). main.py leaves the finished transcript +there, tied to the source's name and duration, picks it up on the re-run, and +removes it once the job completes. +""" +import json +import os + +import pytest + +main = pytest.importorskip("main") # needs cv2/mediapipe, absent in minimal CI + +TRANSCRIPT = {"text": "hola", "language": "es", + "segments": [{"start": 0.0, "end": 1.0, "text": "hola", "words": []}]} +SRC = "/app/output/job1/video.mp4" +DUR = 58.64 + + +def _save(d, transcript=TRANSCRIPT, src=SRC, dur=DUR): + main.save_transcript_checkpoint(str(d), transcript, src, dur) + + +def _load(d, src=SRC, dur=DUR): + return main.load_transcript_checkpoint(str(d), src, dur) + + +class TestRoundTrip: + def test_same_source_is_reused(self, tmp_path): + _save(tmp_path) + assert os.path.isfile(tmp_path / main.TRANSCRIPT_CHECKPOINT) + assert _load(tmp_path) == TRANSCRIPT + + def test_resumed_cloud_job_redownloads_to_the_same_name(self, tmp_path): + # The re-run's file lives at the same path; a slightly different + # duration reading (container decoders differ by a frame) still matches. + _save(tmp_path) + assert _load(tmp_path, dur=DUR + 0.3) == TRANSCRIPT + + def test_missing_checkpoint_is_none(self, tmp_path): + assert _load(tmp_path) is None + + +class TestNeverTheWrongTranscript: + def test_another_file_in_the_same_directory_is_ignored(self, tmp_path): + # THE RISK: CLI run on A dies after transcribing, then B is processed + # in the same directory without -o. B must get its own transcript. + _save(tmp_path, src="/videos/A.mp4") + assert _load(tmp_path, src="/videos/B.mp4") is None + + def test_same_name_but_different_length_is_ignored(self, tmp_path): + _save(tmp_path, dur=600.0) + assert _load(tmp_path, dur=58.6) is None + + def test_legacy_shape_without_source_is_ignored(self, tmp_path): + (tmp_path / main.TRANSCRIPT_CHECKPOINT).write_text(json.dumps(TRANSCRIPT)) + assert _load(tmp_path) is None + + +class TestRobustness: + def test_empty_transcript_is_ignored(self, tmp_path): + _save(tmp_path, transcript={"segments": []}) + assert _load(tmp_path) is None + + def test_truncated_file_is_ignored(self, tmp_path): + (tmp_path / main.TRANSCRIPT_CHECKPOINT).write_text('{"source": {"name": "vi') + assert _load(tmp_path) is None + + def test_unwritable_directory_does_not_raise(self, tmp_path): + main.save_transcript_checkpoint(str(tmp_path / "missing" / "dir"), TRANSCRIPT, SRC, DUR) + + def test_clear_is_idempotent(self, tmp_path): + _save(tmp_path) + main.clear_transcript_checkpoint(str(tmp_path)) + main.clear_transcript_checkpoint(str(tmp_path)) + assert _load(tmp_path) is None + + def test_checkpoint_is_hidden_from_job_listings(self): + # app.py globs *_metadata.json and *.mp4 in the job dir; a dotfile + # named unlike either can never be mistaken for a deliverable. + assert main.TRANSCRIPT_CHECKPOINT.startswith(".") + assert not main.TRANSCRIPT_CHECKPOINT.endswith("_metadata.json") + assert not main.TRANSCRIPT_CHECKPOINT.endswith(".mp4")