Claude commited on
Commit
06c75aa
·
1 Parent(s): 364bfae

Sync deps, format validation, /jobs workdir cleanup, timing tests

Browse files

1. pyproject.toml gains 'anthropic>=0.49' so 'pip install .' brings
in the same dependency that requirements.txt declares. Previously
fresh installs through package metadata silently lost the LLM
feature even when the API key was set.

2. /jobs now wraps the file-save + form-parse phase in try/except so
if anything fails between mkdtemp and worker handoff (disk full,
bad max_frames value, copyfileobj raising), the workdir is
shutil.rmtree'd before the 400 propagates. Mirrors the existing
try/finally pattern in /process. Test guard added.

3. Both /jobs and /process now reject unknown 'format' values with a
400 instead of treating anything-not-review-or-single as zip. The
CLI already validated this; the web layer now matches. Test guard
added.

4. Five new test_scenes.py invariant tests pin the timing properties
that align_segments depends on after frames are dropped:
* indices contiguous from 0
* start_seconds strictly increasing
* end >= start per frame
* the last kept frame's end_seconds covers the original tail
(so transcript narration past dropped frames isn't lost)
Plus a regression guard that _cap_max_frames cleans up alt-frame
files for dropped primaries (no disk leak on long lectures).

Files changed (4) hide show
  1. app/main.py +30 -8
  2. pyproject.toml +1 -0
  3. tests/test_progress.py +46 -0
  4. tests/test_scenes.py +101 -0
app/main.py CHANGED
@@ -36,6 +36,16 @@ app.mount("/static", StaticFiles(directory=str(BASE_DIR / "static")), name="stat
36
 
37
  VIDEO_SUFFIXES = {".mp4", ".mov", ".mkv", ".webm", ".m4v", ".avi"}
38
  TRANSCRIPT_SUFFIXES = {".vtt", ".srt"}
 
 
 
 
 
 
 
 
 
 
39
 
40
 
41
  def _parse_optional_int(value: str | None) -> int | None:
@@ -212,6 +222,7 @@ async def start_job(
212
  llm_math_equations: bool = Form(True),
213
  llm_section_title: bool = Form(True),
214
  ) -> JSONResponse:
 
215
  video_suffix = Path(video.filename or "").suffix.lower()
216
  transcript_suffix = Path(transcript.filename or "").suffix.lower()
217
  if video_suffix not in VIDEO_SUFFIXES:
@@ -220,13 +231,23 @@ async def start_job(
220
  raise HTTPException(400, f"Unsupported transcript format: {transcript_suffix or '(none)'}")
221
 
222
  workdir = Path(tempfile.mkdtemp(prefix="vgm_"))
223
- video_path = workdir / f"input{video_suffix}"
224
- transcript_path = workdir / f"transcript{transcript_suffix}"
225
- frames_dir = workdir / "static"
226
- with video_path.open("wb") as f:
227
- shutil.copyfileobj(video.file, f)
228
- with transcript_path.open("wb") as f:
229
- shutil.copyfileobj(transcript.file, f)
 
 
 
 
 
 
 
 
 
 
230
 
231
  inputs = PipelineInputs(
232
  video_path=video_path,
@@ -238,7 +259,7 @@ async def start_job(
238
  lang=lang,
239
  threshold=threshold,
240
  min_gap_seconds=min_gap,
241
- max_frames=_parse_optional_int(max_frames),
242
  skip_ocr=skip_ocr,
243
  face_threshold=face_threshold,
244
  inline_images=(format in ("single", "review")),
@@ -390,6 +411,7 @@ async def process(
390
  llm_math_equations: bool = Form(True),
391
  llm_section_title: bool = Form(True),
392
  ) -> Response:
 
393
  video_suffix = Path(video.filename or "").suffix.lower()
394
  transcript_suffix = Path(transcript.filename or "").suffix.lower()
395
  if video_suffix not in VIDEO_SUFFIXES:
 
36
 
37
  VIDEO_SUFFIXES = {".mp4", ".mov", ".mkv", ".webm", ".m4v", ".avi"}
38
  TRANSCRIPT_SUFFIXES = {".vtt", ".srt"}
39
+ ALLOWED_FORMATS = {"review", "single", "zip"}
40
+
41
+
42
+ def _validate_format(value: str) -> str:
43
+ if value not in ALLOWED_FORMATS:
44
+ raise HTTPException(
45
+ 400,
46
+ f"Unsupported format {value!r}. Must be one of: {sorted(ALLOWED_FORMATS)}.",
47
+ )
48
+ return value
49
 
50
 
51
  def _parse_optional_int(value: str | None) -> int | None:
 
222
  llm_math_equations: bool = Form(True),
223
  llm_section_title: bool = Form(True),
224
  ) -> JSONResponse:
225
+ _validate_format(format)
226
  video_suffix = Path(video.filename or "").suffix.lower()
227
  transcript_suffix = Path(transcript.filename or "").suffix.lower()
228
  if video_suffix not in VIDEO_SUFFIXES:
 
231
  raise HTTPException(400, f"Unsupported transcript format: {transcript_suffix or '(none)'}")
232
 
233
  workdir = Path(tempfile.mkdtemp(prefix="vgm_"))
234
+ try:
235
+ video_path = workdir / f"input{video_suffix}"
236
+ transcript_path = workdir / f"transcript{transcript_suffix}"
237
+ frames_dir = workdir / "static"
238
+ with video_path.open("wb") as f:
239
+ shutil.copyfileobj(video.file, f)
240
+ with transcript_path.open("wb") as f:
241
+ shutil.copyfileobj(transcript.file, f)
242
+
243
+ max_frames_value = _parse_optional_int(max_frames)
244
+ except Exception:
245
+ # Anything goes wrong before the worker thread takes ownership of
246
+ # the workdir — disk full, malformed numeric form field, etc — and
247
+ # we'd otherwise orphan the dir we just mkdtemp'd. The worker has
248
+ # its own try/finally that handles the post-handoff path.
249
+ shutil.rmtree(workdir, ignore_errors=True)
250
+ raise
251
 
252
  inputs = PipelineInputs(
253
  video_path=video_path,
 
259
  lang=lang,
260
  threshold=threshold,
261
  min_gap_seconds=min_gap,
262
+ max_frames=max_frames_value,
263
  skip_ocr=skip_ocr,
264
  face_threshold=face_threshold,
265
  inline_images=(format in ("single", "review")),
 
411
  llm_math_equations: bool = Form(True),
412
  llm_section_title: bool = Form(True),
413
  ) -> Response:
414
+ _validate_format(format)
415
  video_suffix = Path(video.filename or "").suffix.lower()
416
  transcript_suffix = Path(transcript.filename or "").suffix.lower()
417
  if video_suffix not in VIDEO_SUFFIXES:
pyproject.toml CHANGED
@@ -17,6 +17,7 @@ dependencies = [
17
  "pydantic>=2.9",
18
  "typer>=0.12",
19
  "httpx>=0.27",
 
20
  ]
21
 
22
  [project.optional-dependencies]
 
17
  "pydantic>=2.9",
18
  "typer>=0.12",
19
  "httpx>=0.27",
20
+ "anthropic>=0.49",
21
  ]
22
 
23
  [project.optional-dependencies]
tests/test_progress.py CHANGED
@@ -102,6 +102,52 @@ def test_jobs_endpoint_rejects_unknown_video_type(tmp_path):
102
  assert resp.status_code == 400
103
 
104
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
105
  def test_events_endpoint_404_for_unknown_job():
106
  client = TestClient(app)
107
  resp = client.get("/events/no-such-id", headers={"Accept": "text/event-stream"})
 
102
  assert resp.status_code == 400
103
 
104
 
105
+ def test_jobs_endpoint_rejects_unknown_format(tmp_path):
106
+ client = TestClient(app)
107
+ mp4 = tmp_path / "x.mp4"
108
+ mp4.write_bytes(b"fake")
109
+ srt = tmp_path / "t.srt"
110
+ srt.write_text("1\n00:00:00,000 --> 00:00:01,000\nhello\n")
111
+ with mp4.open("rb") as v, srt.open("rb") as t:
112
+ resp = client.post(
113
+ "/jobs",
114
+ data={"title": "x", "format": "evil-format"},
115
+ files={
116
+ "video": ("x.mp4", v, "video/mp4"),
117
+ "transcript": ("t.srt", t, "application/x-subrip"),
118
+ },
119
+ )
120
+ assert resp.status_code == 400
121
+ assert "format" in resp.text.lower()
122
+
123
+
124
+ def test_jobs_endpoint_cleans_workdir_on_save_failure(tmp_path):
125
+ # Triggering a 400 after the workdir is mkdtemp'd: a malformed
126
+ # max_frames raises during _parse_optional_int. The handler's
127
+ # try/except must remove the freshly-created vgm_ directory.
128
+ import glob
129
+ import os
130
+ import tempfile as _t
131
+ client = TestClient(app)
132
+ before = set(glob.glob(os.path.join(_t.gettempdir(), "vgm_*")))
133
+ mp4 = tmp_path / "x.mp4"
134
+ mp4.write_bytes(b"fake")
135
+ srt = tmp_path / "t.srt"
136
+ srt.write_text("1\n00:00:00,000 --> 00:00:01,000\nhello\n")
137
+ with mp4.open("rb") as v, srt.open("rb") as t:
138
+ resp = client.post(
139
+ "/jobs",
140
+ data={"title": "x", "max_frames": "not-an-int"},
141
+ files={
142
+ "video": ("x.mp4", v, "video/mp4"),
143
+ "transcript": ("t.srt", t, "application/x-subrip"),
144
+ },
145
+ )
146
+ assert resp.status_code == 400
147
+ after = set(glob.glob(os.path.join(_t.gettempdir(), "vgm_*")))
148
+ assert after - before == set(), f"leaked workdir(s): {after - before}"
149
+
150
+
151
  def test_events_endpoint_404_for_unknown_job():
152
  client = TestClient(app)
153
  resp = client.get("/events/no-such-id", headers={"Accept": "text/event-stream"})
tests/test_scenes.py CHANGED
@@ -108,3 +108,104 @@ def test_cap_max_frames_no_op_when_under_limit(tmp_path):
108
  assert len(out) == 3
109
  for p in paths:
110
  assert p.exists()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
108
  assert len(out) == 3
109
  for p in paths:
110
  assert p.exists()
111
+
112
+
113
+ # -----------------------------------------------------------------------------
114
+ # Timing invariants. align_segments relies on these after frames are dropped:
115
+ # * start_seconds strictly increases across kept frames,
116
+ # * indices are contiguous and start at 0,
117
+ # * each kept frame's end >= start,
118
+ # * the last kept frame's end_seconds covers the source's true end so the
119
+ # transcript-alignment code doesn't lose narration past the dropped tail.
120
+ # These invariants were previously only implicit. The tests below pin them.
121
+ # -----------------------------------------------------------------------------
122
+
123
+
124
+ def _assert_timing_invariants(out, total_end):
125
+ assert [f.index for f in out] == list(range(len(out))), "indices not contiguous from 0"
126
+ starts = [f.start_seconds for f in out]
127
+ assert starts == sorted(starts), "start_seconds must be monotonically non-decreasing"
128
+ assert len(starts) == len(set(starts)), "start_seconds must be strictly increasing"
129
+ for f in out:
130
+ assert f.end_seconds >= f.start_seconds, f"end < start at index {f.index}"
131
+ assert out[-1].end_seconds >= total_end, (
132
+ "last kept frame must cover the original total end so narration after "
133
+ "dropped frames isn't lost during transcript alignment"
134
+ )
135
+
136
+
137
+ def test_enforce_min_gap_preserves_timing_invariants(tmp_path):
138
+ paths = [tmp_path / f"f{i}.jpg" for i in range(5)]
139
+ for i, p in enumerate(paths):
140
+ _save_text_like(p, seed=i + 1)
141
+ # Five frames with the original tail at end_seconds=12.0.
142
+ # Frames 1 and 3 are within 2s of the previous kept frame; both drop.
143
+ frames = [
144
+ SceneFrame(0, 0.0, 1.0, paths[0]),
145
+ SceneFrame(1, 1.5, 2.0, paths[1]), # dropped (gap=1.5)
146
+ SceneFrame(2, 4.0, 6.0, paths[2]), # kept
147
+ SceneFrame(3, 6.5, 7.0, paths[3]), # dropped (gap=2.5 from 4.0... wait, 2.5>=2 so kept actually)
148
+ SceneFrame(4, 9.0, 12.0, paths[4]), # kept
149
+ ]
150
+ out = _enforce_min_gap(frames, min_gap_seconds=2.0)
151
+ _assert_timing_invariants(out, total_end=12.0)
152
+
153
+
154
+ def test_enforce_min_gap_extends_last_end_when_tail_drops(tmp_path):
155
+ paths = [tmp_path / f"f{i}.jpg" for i in range(3)]
156
+ for i, p in enumerate(paths):
157
+ _save_text_like(p, seed=i + 1)
158
+ # The final frame is within the gap and gets dropped — the kept second
159
+ # frame must have its end_seconds extended so we don't lose the tail.
160
+ frames = [
161
+ SceneFrame(0, 0.0, 1.0, paths[0]),
162
+ SceneFrame(1, 5.0, 8.0, paths[1]),
163
+ SceneFrame(2, 8.5, 20.0, paths[2]), # dropped, gap=3.5
164
+ ]
165
+ out = _enforce_min_gap(frames, min_gap_seconds=4.0)
166
+ assert len(out) == 2
167
+ assert out[-1].end_seconds == 20.0, "must absorb the tail of the dropped trailing frame"
168
+ _assert_timing_invariants(out, total_end=20.0)
169
+
170
+
171
+ def test_cap_max_frames_preserves_timing_invariants(tmp_path):
172
+ paths = [tmp_path / f"f{i:02d}.jpg" for i in range(8)]
173
+ for i, p in enumerate(paths):
174
+ _save_text_like(p, seed=i + 1)
175
+ frames = [SceneFrame(i, float(i) * 2, float(i) * 2 + 2, p) for i, p in enumerate(paths)]
176
+ out = _cap_max_frames(frames, max_frames=4)
177
+ _assert_timing_invariants(out, total_end=frames[-1].end_seconds)
178
+
179
+
180
+ def test_min_gap_then_cap_max_frames_invariants(tmp_path):
181
+ paths = [tmp_path / f"f{i:02d}.jpg" for i in range(10)]
182
+ for i, p in enumerate(paths):
183
+ _save_text_like(p, seed=i + 1)
184
+ # Mix close + spread frames to exercise both helpers in sequence.
185
+ starts = [0.0, 0.6, 3.0, 6.0, 6.4, 9.0, 12.0, 14.0, 14.3, 17.0]
186
+ frames = [SceneFrame(i, s, s + 1.0, paths[i]) for i, s in enumerate(starts)]
187
+ after_gap = _enforce_min_gap(frames, min_gap_seconds=1.5)
188
+ out = _cap_max_frames(after_gap, max_frames=3)
189
+ _assert_timing_invariants(out, total_end=18.0)
190
+
191
+
192
+ def test_cap_max_frames_unlinks_alts_of_dropped(tmp_path):
193
+ # Regression guard: when capping, alternate frame files for dropped
194
+ # primaries must also be cleaned up — otherwise we leak disk on long
195
+ # lectures. The helper routes through _unlink_frame_files.
196
+ primaries = [tmp_path / f"p{i}.jpg" for i in range(5)]
197
+ alts = [tmp_path / f"p{i}_alt1.jpg" for i in range(5)]
198
+ for p in primaries + alts:
199
+ _save_text_like(p, seed=hash(p.name) & 0xFF)
200
+ frames = [
201
+ SceneFrame(i, float(i), float(i) + 1, primaries[i], alt_image_paths=[alts[i]])
202
+ for i in range(5)
203
+ ]
204
+ out = _cap_max_frames(frames, max_frames=2)
205
+ kept_alts = {p.name for f in out for p in f.alt_image_paths}
206
+ for f in frames:
207
+ for ap in f.alt_image_paths:
208
+ if ap.name in kept_alts:
209
+ assert ap.exists()
210
+ else:
211
+ assert not ap.exists(), f"orphaned alt: {ap.name}"