Claude commited on
Commit
f09a075
·
1 Parent(s): 5125240

fix: images-mode ZIP dropped all images; retry malformed LLM JSON

Browse files

Two issues from a real images-mode run:

ZIP bundle had no images (broken guide). The /jobs/{id}/zip endpoint
gated asset filenames on the video-mode scene_NNNN.jpg pattern, so
images-mode uploads that keep their original names ("slide 1.jpg") were
filtered out — never written to the temp dir, never bundled — leaving
HTML that references static/ files that aren't there. Replace the rigid
pattern with _is_safe_asset_name: a bare basename (no separators / no
traversal, enforced by Path(name).name == name) with an allowed image/
audio extension. Keeps the path-traversal protection (that gate was the
reason for the regex) while accepting any legitimate filename.

Malformed-JSON responses dropped a slide's enrichment. The model
occasionally emits invalid JSON (an unescaped quote → "Expecting ','
delimiter"), which failed the parse and left that segment blank. Now:
json.loads uses strict=False (tolerates literal control chars in
strings), and extract_one retries the call ONCE on a parse/validation
failure — the model is stochastic and usually returns clean JSON the
second time. Transient HTTP errors are still handled by
_create_with_retry (not double-retried).

Tests: safe-name accept/reject; retry recovers a bad-then-good JSON
pair; strict=False tolerates a newline in a string.

https://claude.ai/code/session_01EM8jiYxdVFy1w3LeJ9GBJg

app/main.py CHANGED
@@ -1285,6 +1285,26 @@ _ALT_FILENAME_RE = __import__("re").compile(r"^scene_\d{4}_alt\d+\.(jpg|jpeg|png
1285
  _PRIMARY_FILENAME_RE = __import__("re").compile(r"^scene_\d{4}\.(jpg|jpeg|png)$")
1286
  _AUDIO_FILENAME_RE = __import__("re").compile(r"^segment_\d{4}\.mp3$")
1287
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1288
 
1289
  @app.get("/audio/{job_id}/{filename}")
1290
  async def fetch_audio(job_id: str, filename: str) -> Response:
@@ -1427,7 +1447,7 @@ async def fetch_job_zip(job_id: str, request: Request) -> Response:
1427
  for filename, uri in primary_uris.items():
1428
  if not isinstance(filename, str) or not isinstance(uri, str):
1429
  continue
1430
- if not _ALT_FILENAME_RE.match(filename) and not _PRIMARY_FILENAME_RE.match(filename):
1431
  continue
1432
  m = _DATA_URI_RE.match(uri)
1433
  if not m:
@@ -1460,16 +1480,12 @@ async def fetch_job_zip(job_id: str, request: Request) -> Response:
1460
  frame_paths = [
1461
  frames_dir / s.image_filename
1462
  for s in page.segments
1463
- if s.image_filename
1464
- and (
1465
- _PRIMARY_FILENAME_RE.match(s.image_filename)
1466
- or _ALT_FILENAME_RE.match(s.image_filename)
1467
- )
1468
  ]
1469
  audio_paths = [
1470
  frames_dir / s.audio_filename
1471
  for s in page.segments
1472
- if s.audio_filename and _AUDIO_FILENAME_RE.match(s.audio_filename)
1473
  ]
1474
  zip_bytes = bundle_zip(
1475
  html,
 
1285
  _PRIMARY_FILENAME_RE = __import__("re").compile(r"^scene_\d{4}\.(jpg|jpeg|png)$")
1286
  _AUDIO_FILENAME_RE = __import__("re").compile(r"^segment_\d{4}\.mp3$")
1287
 
1288
+ _IMAGE_ASSET_EXTS = {".jpg", ".jpeg", ".png", ".webp"}
1289
+ _AUDIO_ASSET_EXTS = {".mp3"}
1290
+
1291
+
1292
+ def _is_safe_asset_name(name: str, allowed_exts: set[str]) -> bool:
1293
+ """A bundle-safe filename: a bare basename (no directory components,
1294
+ no traversal) with an allowed extension.
1295
+
1296
+ The ZIP builder joins these onto a temp dir and reads/writes them, so
1297
+ they must not be able to escape it. `Path(name).name == name` rejects
1298
+ anything with a separator or `..` component; the extension whitelist
1299
+ rejects the rest. This replaces the old scene_NNNN-only patterns, which
1300
+ wrongly excluded images-mode uploads that keep their original names
1301
+ (e.g. 'slide 1.jpg')."""
1302
+ if not isinstance(name, str) or not name:
1303
+ return False
1304
+ if Path(name).name != name:
1305
+ return False
1306
+ return Path(name).suffix.lower() in allowed_exts
1307
+
1308
 
1309
  @app.get("/audio/{job_id}/{filename}")
1310
  async def fetch_audio(job_id: str, filename: str) -> Response:
 
1447
  for filename, uri in primary_uris.items():
1448
  if not isinstance(filename, str) or not isinstance(uri, str):
1449
  continue
1450
+ if not _is_safe_asset_name(filename, _IMAGE_ASSET_EXTS):
1451
  continue
1452
  m = _DATA_URI_RE.match(uri)
1453
  if not m:
 
1480
  frame_paths = [
1481
  frames_dir / s.image_filename
1482
  for s in page.segments
1483
+ if _is_safe_asset_name(s.image_filename, _IMAGE_ASSET_EXTS)
 
 
 
 
1484
  ]
1485
  audio_paths = [
1486
  frames_dir / s.audio_filename
1487
  for s in page.segments
1488
+ if _is_safe_asset_name(s.audio_filename, _AUDIO_ASSET_EXTS)
1489
  ]
1490
  zip_bytes = bundle_zip(
1491
  html,
app/pipeline/llm_extract.py CHANGED
@@ -20,7 +20,7 @@ from dataclasses import dataclass
20
  from pathlib import Path
21
  from typing import Any, Callable
22
 
23
- from pydantic import BaseModel, create_model
24
 
25
  from .metadata import MathEquation
26
 
@@ -355,7 +355,10 @@ def _extract_json_object(text: str) -> dict:
355
  end = t.rfind("}")
356
  if start == -1 or end == -1 or end < start:
357
  raise ValueError("no JSON object found in model response")
358
- obj = json.loads(t[start : end + 1])
 
 
 
359
  if not isinstance(obj, dict):
360
  raise ValueError("model response JSON was not an object")
361
  return obj
@@ -453,9 +456,27 @@ def extract_one(
453
  resolved = _resolve_api_key(api_key)
454
  if client is None and resolved is None:
455
  return _EMPTY
 
 
 
 
456
  try:
457
  if client is None:
458
  client = _build_client(resolved) # type: ignore[arg-type]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
459
  response = _create_with_retry(
460
  client,
461
  model=model,
@@ -467,20 +488,7 @@ def extract_one(
467
  "cache_control": {"type": "ephemeral"},
468
  }
469
  ],
470
- messages=[
471
- {
472
- "role": "user",
473
- "content": _build_user_content(
474
- image_path,
475
- narration,
476
- ocr_text,
477
- # When Claude is producing OCR itself, don't also
478
- # send Tesseract's (possibly garbled) version —
479
- # it'd be ignored and we'd pay input tokens for it.
480
- include_ocr=not toggles.ocr_text,
481
- ),
482
- }
483
- ],
484
  )
485
  raw = _extract_json_object(_response_text(response))
486
  parsed = _build_extraction_model(toggles).model_validate(raw)
@@ -494,10 +502,23 @@ def extract_one(
494
  for m in getattr(parsed, "math_equations", []) or []
495
  ],
496
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
497
  except Exception as exc: # pragma: no cover (network-dependent)
498
- # Scrub the API key from the exception message before logging (S4).
499
- safe_msg = str(exc).replace(resolved, "***") if resolved else str(exc)
500
- log.warning("LLM extraction failed for %s: %s", image_path.name, safe_msg)
501
  return _EMPTY
502
 
503
 
 
20
  from pathlib import Path
21
  from typing import Any, Callable
22
 
23
+ from pydantic import BaseModel, ValidationError, create_model
24
 
25
  from .metadata import MathEquation
26
 
 
355
  end = t.rfind("}")
356
  if start == -1 or end == -1 or end < start:
357
  raise ValueError("no JSON object found in model response")
358
+ # strict=False tolerates literal control chars (unescaped newlines/tabs)
359
+ # inside string values, a common model slip. Genuinely broken JSON
360
+ # (e.g. an unescaped quote) still raises — the caller retries once.
361
+ obj = json.loads(t[start : end + 1], strict=False)
362
  if not isinstance(obj, dict):
363
  raise ValueError("model response JSON was not an object")
364
  return obj
 
456
  resolved = _resolve_api_key(api_key)
457
  if client is None and resolved is None:
458
  return _EMPTY
459
+
460
+ def _scrub(exc: Exception) -> str:
461
+ return str(exc).replace(resolved, "***") if resolved else str(exc)
462
+
463
  try:
464
  if client is None:
465
  client = _build_client(resolved) # type: ignore[arg-type]
466
+ except Exception as exc: # pragma: no cover (import/SDK-dependent)
467
+ log.warning("LLM extraction failed for %s: %s", image_path.name, _scrub(exc))
468
+ return _EMPTY
469
+
470
+ user_content = _build_user_content(
471
+ image_path,
472
+ narration,
473
+ ocr_text,
474
+ # When Claude is producing OCR itself, don't also send Tesseract's
475
+ # (possibly garbled) version — it'd be ignored and cost input tokens.
476
+ include_ocr=not toggles.ocr_text,
477
+ )
478
+
479
+ def _attempt() -> ExtractionResult:
480
  response = _create_with_retry(
481
  client,
482
  model=model,
 
488
  "cache_control": {"type": "ephemeral"},
489
  }
490
  ],
491
+ messages=[{"role": "user", "content": user_content}],
 
 
 
 
 
 
 
 
 
 
 
 
 
492
  )
493
  raw = _extract_json_object(_response_text(response))
494
  parsed = _build_extraction_model(toggles).model_validate(raw)
 
502
  for m in getattr(parsed, "math_equations", []) or []
503
  ],
504
  )
505
+
506
+ # Up to two attempts. A malformed-JSON / validation failure is retried
507
+ # once — the model is stochastic and usually returns clean JSON the
508
+ # second time. Transient HTTP errors are already retried inside
509
+ # _create_with_retry, so any exception it surfaces is treated as
510
+ # terminal (no extra call spent).
511
+ try:
512
+ return _attempt()
513
+ except (ValueError, ValidationError) as exc:
514
+ log.info("Retrying %s after unparseable model output: %s", image_path.name, _scrub(exc))
515
+ try:
516
+ return _attempt()
517
+ except Exception as exc2: # pragma: no cover (model-dependent)
518
+ log.warning("LLM extraction failed for %s: %s", image_path.name, _scrub(exc2))
519
+ return _EMPTY
520
  except Exception as exc: # pragma: no cover (network-dependent)
521
+ log.warning("LLM extraction failed for %s: %s", image_path.name, _scrub(exc))
 
 
522
  return _EMPTY
523
 
524
 
tests/test_llm_extract.py CHANGED
@@ -102,6 +102,36 @@ def test_extract_json_object_ignores_surrounding_prose():
102
  assert llm_extract._extract_json_object(text) == {"description": "A slide."}
103
 
104
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
105
  def test_extract_json_object_raises_on_no_object():
106
  """A purely conversational reply ('I'm ready to analyze…') has no JSON;
107
  the caller catches this and returns empty for that segment."""
 
102
  assert llm_extract._extract_json_object(text) == {"description": "A slide."}
103
 
104
 
105
+ def test_extract_one_retries_once_on_malformed_json(tmp_path, monkeypatch):
106
+ """A malformed-JSON response (e.g. an unescaped quote) is retried once;
107
+ the model usually returns clean JSON the second time."""
108
+ _fake_anthropic_module(monkeypatch)
109
+ from unittest.mock import MagicMock
110
+ img = tmp_path / "slide 1.jpg"
111
+ Image.new("RGB", (16, 16), "white").save(img, "JPEG")
112
+
113
+ def resp(text):
114
+ blk = MagicMock(); blk.type = "text"; blk.text = text
115
+ r = MagicMock(); r.content = [blk]; return r
116
+
117
+ client = MagicMock()
118
+ client.messages.create.side_effect = [
119
+ resp('{"section_title": "The "big" idea"}'), # invalid JSON
120
+ resp('{"section_title": "Projecting Future Climate"}'), # valid
121
+ ]
122
+ res = llm_extract.extract_one(
123
+ img, [], "", api_key="sk-ant-x",
124
+ toggles=LLMToggles(section_title=True), client=client,
125
+ )
126
+ assert res.section_title == "Projecting Future Climate"
127
+ assert client.messages.create.call_count == 2
128
+
129
+
130
+ def test_extract_json_object_tolerates_control_chars():
131
+ """strict=False lets a literal newline inside a string value parse."""
132
+ assert llm_extract._extract_json_object('{"a": "line1\nline2"}') == {"a": "line1\nline2"}
133
+
134
+
135
  def test_extract_json_object_raises_on_no_object():
136
  """A purely conversational reply ('I'm ready to analyze…') has no JSON;
137
  the caller catches this and returns empty for that segment."""