pyocr-toolkit 0.3.0__tar.gz → 0.4.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (89) hide show
  1. {pyocr_toolkit-0.3.0 → pyocr_toolkit-0.4.0}/.env.example +1 -0
  2. {pyocr_toolkit-0.3.0 → pyocr_toolkit-0.4.0}/CHANGELOG.md +29 -0
  3. {pyocr_toolkit-0.3.0 → pyocr_toolkit-0.4.0}/PKG-INFO +21 -3
  4. {pyocr_toolkit-0.3.0 → pyocr_toolkit-0.4.0}/README.md +19 -2
  5. {pyocr_toolkit-0.3.0 → pyocr_toolkit-0.4.0}/pyproject.toml +2 -1
  6. {pyocr_toolkit-0.3.0 → pyocr_toolkit-0.4.0}/src/pyocr_toolkit/__init__.py +1 -1
  7. {pyocr_toolkit-0.3.0 → pyocr_toolkit-0.4.0}/src/pyocr_toolkit/api.py +46 -5
  8. {pyocr_toolkit-0.3.0 → pyocr_toolkit-0.4.0}/src/pyocr_toolkit/cli.py +22 -10
  9. {pyocr_toolkit-0.3.0 → pyocr_toolkit-0.4.0}/src/pyocr_toolkit/config.py +4 -0
  10. {pyocr_toolkit-0.3.0 → pyocr_toolkit-0.4.0}/src/pyocr_toolkit/documents.py +12 -3
  11. {pyocr_toolkit-0.3.0 → pyocr_toolkit-0.4.0}/src/pyocr_toolkit/env.example +1 -0
  12. {pyocr_toolkit-0.3.0 → pyocr_toolkit-0.4.0}/src/pyocr_toolkit/jobs.py +54 -20
  13. {pyocr_toolkit-0.3.0 → pyocr_toolkit-0.4.0}/src/pyocr_toolkit/llm/__init__.py +15 -1
  14. {pyocr_toolkit-0.3.0 → pyocr_toolkit-0.4.0}/src/pyocr_toolkit/llm/anthropic_provider.py +18 -11
  15. {pyocr_toolkit-0.3.0 → pyocr_toolkit-0.4.0}/src/pyocr_toolkit/llm/base.py +24 -1
  16. {pyocr_toolkit-0.3.0 → pyocr_toolkit-0.4.0}/src/pyocr_toolkit/llm/gemini_provider.py +11 -4
  17. {pyocr_toolkit-0.3.0 → pyocr_toolkit-0.4.0}/src/pyocr_toolkit/llm/openai_provider.py +7 -8
  18. pyocr_toolkit-0.4.0/src/pyocr_toolkit/llm/prompts.py +135 -0
  19. pyocr_toolkit-0.4.0/src/pyocr_toolkit/preprocess.py +332 -0
  20. pyocr_toolkit-0.4.0/src/pyocr_toolkit/service.py +493 -0
  21. {pyocr_toolkit-0.3.0 → pyocr_toolkit-0.4.0}/src/pyocr_toolkit/static/common.js +13 -0
  22. pyocr_toolkit-0.4.0/src/pyocr_toolkit/static/document.js +269 -0
  23. {pyocr_toolkit-0.3.0 → pyocr_toolkit-0.4.0}/src/pyocr_toolkit/static/styles.css +94 -2
  24. {pyocr_toolkit-0.3.0 → pyocr_toolkit-0.4.0}/src/pyocr_toolkit/static/workspace.js +327 -11
  25. {pyocr_toolkit-0.3.0 → pyocr_toolkit-0.4.0}/src/pyocr_toolkit/templates/_icons.html +1 -0
  26. {pyocr_toolkit-0.3.0 → pyocr_toolkit-0.4.0}/src/pyocr_toolkit/templates/document.html +47 -2
  27. {pyocr_toolkit-0.3.0 → pyocr_toolkit-0.4.0}/src/pyocr_toolkit/templates/help.html +58 -1
  28. {pyocr_toolkit-0.3.0 → pyocr_toolkit-0.4.0}/src/pyocr_toolkit/templates/providers.html +1 -0
  29. {pyocr_toolkit-0.3.0 → pyocr_toolkit-0.4.0}/src/pyocr_toolkit/templates/workspace.html +52 -1
  30. pyocr_toolkit-0.4.0/tests/test_batch.py +258 -0
  31. pyocr_toolkit-0.4.0/tests/test_preprocess.py +187 -0
  32. pyocr_toolkit-0.3.0/src/pyocr_toolkit/llm/prompts.py +0 -61
  33. pyocr_toolkit-0.3.0/src/pyocr_toolkit/service.py +0 -269
  34. pyocr_toolkit-0.3.0/src/pyocr_toolkit/static/document.js +0 -89
  35. {pyocr_toolkit-0.3.0 → pyocr_toolkit-0.4.0}/.gitignore +0 -0
  36. {pyocr_toolkit-0.3.0 → pyocr_toolkit-0.4.0}/CONTRIBUTING.md +0 -0
  37. {pyocr_toolkit-0.3.0 → pyocr_toolkit-0.4.0}/LICENSE +0 -0
  38. {pyocr_toolkit-0.3.0 → pyocr_toolkit-0.4.0}/hero-video/README.md +0 -0
  39. {pyocr_toolkit-0.3.0 → pyocr_toolkit-0.4.0}/hero-video/src/HeroDemo.tsx +0 -0
  40. {pyocr_toolkit-0.3.0 → pyocr_toolkit-0.4.0}/hero-video/src/Root.tsx +0 -0
  41. {pyocr_toolkit-0.3.0 → pyocr_toolkit-0.4.0}/hero-video/src/assets.d.ts +0 -0
  42. {pyocr_toolkit-0.3.0 → pyocr_toolkit-0.4.0}/hero-video/src/index.ts +0 -0
  43. {pyocr_toolkit-0.3.0 → pyocr_toolkit-0.4.0}/hero-video/src/motion.tsx +0 -0
  44. {pyocr_toolkit-0.3.0 → pyocr_toolkit-0.4.0}/hero-video/src/scenes/CatchScene.tsx +0 -0
  45. {pyocr_toolkit-0.3.0 → pyocr_toolkit-0.4.0}/hero-video/src/scenes/ColdOpenScene.tsx +0 -0
  46. {pyocr_toolkit-0.3.0 → pyocr_toolkit-0.4.0}/hero-video/src/scenes/MeasureScene.tsx +0 -0
  47. {pyocr_toolkit-0.3.0 → pyocr_toolkit-0.4.0}/hero-video/src/scenes/MontageScene.tsx +0 -0
  48. {pyocr_toolkit-0.3.0 → pyocr_toolkit-0.4.0}/hero-video/src/scenes/OutroScene.tsx +0 -0
  49. {pyocr_toolkit-0.3.0 → pyocr_toolkit-0.4.0}/hero-video/src/scenes/ThreeWaysScene.tsx +0 -0
  50. {pyocr_toolkit-0.3.0 → pyocr_toolkit-0.4.0}/hero-video/src/theme.ts +0 -0
  51. {pyocr_toolkit-0.3.0 → pyocr_toolkit-0.4.0}/hero-video/src/ui.tsx +0 -0
  52. {pyocr_toolkit-0.3.0 → pyocr_toolkit-0.4.0}/src/pyocr_toolkit/__main__.py +0 -0
  53. {pyocr_toolkit-0.3.0 → pyocr_toolkit-0.4.0}/src/pyocr_toolkit/compare.py +0 -0
  54. {pyocr_toolkit-0.3.0 → pyocr_toolkit-0.4.0}/src/pyocr_toolkit/credentials.py +0 -0
  55. {pyocr_toolkit-0.3.0 → pyocr_toolkit-0.4.0}/src/pyocr_toolkit/llm/catalog.py +0 -0
  56. {pyocr_toolkit-0.3.0 → pyocr_toolkit-0.4.0}/src/pyocr_toolkit/search.py +0 -0
  57. {pyocr_toolkit-0.3.0 → pyocr_toolkit-0.4.0}/src/pyocr_toolkit/static/compare.js +0 -0
  58. {pyocr_toolkit-0.3.0 → pyocr_toolkit-0.4.0}/src/pyocr_toolkit/static/jobs.js +0 -0
  59. {pyocr_toolkit-0.3.0 → pyocr_toolkit-0.4.0}/src/pyocr_toolkit/static/library.js +0 -0
  60. {pyocr_toolkit-0.3.0 → pyocr_toolkit-0.4.0}/src/pyocr_toolkit/static/models.js +0 -0
  61. {pyocr_toolkit-0.3.0 → pyocr_toolkit-0.4.0}/src/pyocr_toolkit/static/providers.js +0 -0
  62. {pyocr_toolkit-0.3.0 → pyocr_toolkit-0.4.0}/src/pyocr_toolkit/static/reader.js +0 -0
  63. {pyocr_toolkit-0.3.0 → pyocr_toolkit-0.4.0}/src/pyocr_toolkit/static/search.js +0 -0
  64. {pyocr_toolkit-0.3.0 → pyocr_toolkit-0.4.0}/src/pyocr_toolkit/static/workspaces.js +0 -0
  65. {pyocr_toolkit-0.3.0 → pyocr_toolkit-0.4.0}/src/pyocr_toolkit/templates/_doc_card.html +0 -0
  66. {pyocr_toolkit-0.3.0 → pyocr_toolkit-0.4.0}/src/pyocr_toolkit/templates/_doctabs.html +0 -0
  67. {pyocr_toolkit-0.3.0 → pyocr_toolkit-0.4.0}/src/pyocr_toolkit/templates/_llm_picker.html +0 -0
  68. {pyocr_toolkit-0.3.0 → pyocr_toolkit-0.4.0}/src/pyocr_toolkit/templates/base.html +0 -0
  69. {pyocr_toolkit-0.3.0 → pyocr_toolkit-0.4.0}/src/pyocr_toolkit/templates/compare.html +0 -0
  70. {pyocr_toolkit-0.3.0 → pyocr_toolkit-0.4.0}/src/pyocr_toolkit/templates/error.html +0 -0
  71. {pyocr_toolkit-0.3.0 → pyocr_toolkit-0.4.0}/src/pyocr_toolkit/templates/home.html +0 -0
  72. {pyocr_toolkit-0.3.0 → pyocr_toolkit-0.4.0}/src/pyocr_toolkit/templates/jobs.html +0 -0
  73. {pyocr_toolkit-0.3.0 → pyocr_toolkit-0.4.0}/src/pyocr_toolkit/templates/library.html +0 -0
  74. {pyocr_toolkit-0.3.0 → pyocr_toolkit-0.4.0}/src/pyocr_toolkit/templates/models.html +0 -0
  75. {pyocr_toolkit-0.3.0 → pyocr_toolkit-0.4.0}/src/pyocr_toolkit/templates/reader.html +0 -0
  76. {pyocr_toolkit-0.3.0 → pyocr_toolkit-0.4.0}/src/pyocr_toolkit/templates/search.html +0 -0
  77. {pyocr_toolkit-0.3.0 → pyocr_toolkit-0.4.0}/src/pyocr_toolkit/templates/workspace_detail.html +0 -0
  78. {pyocr_toolkit-0.3.0 → pyocr_toolkit-0.4.0}/src/pyocr_toolkit/templates/workspaces.html +0 -0
  79. {pyocr_toolkit-0.3.0 → pyocr_toolkit-0.4.0}/src/pyocr_toolkit/web.py +0 -0
  80. {pyocr_toolkit-0.3.0 → pyocr_toolkit-0.4.0}/src/pyocr_toolkit/workspaces.py +0 -0
  81. {pyocr_toolkit-0.3.0 → pyocr_toolkit-0.4.0}/tests/__init__.py +0 -0
  82. {pyocr_toolkit-0.3.0 → pyocr_toolkit-0.4.0}/tests/conftest.py +0 -0
  83. {pyocr_toolkit-0.3.0 → pyocr_toolkit-0.4.0}/tests/test_api.py +0 -0
  84. {pyocr_toolkit-0.3.0 → pyocr_toolkit-0.4.0}/tests/test_core.py +0 -0
  85. {pyocr_toolkit-0.3.0 → pyocr_toolkit-0.4.0}/tests/test_makefile.py +0 -0
  86. {pyocr_toolkit-0.3.0 → pyocr_toolkit-0.4.0}/tests/test_models.py +0 -0
  87. {pyocr_toolkit-0.3.0 → pyocr_toolkit-0.4.0}/tests/test_providers.py +0 -0
  88. {pyocr_toolkit-0.3.0 → pyocr_toolkit-0.4.0}/tests/test_web.py +0 -0
  89. {pyocr_toolkit-0.3.0 → pyocr_toolkit-0.4.0}/tests/test_workspaces.py +0 -0
@@ -45,4 +45,5 @@ GEMINI_API_KEY=
45
45
  # TESSERACT_LANGUAGE=eng # e.g. eng+deu (install the language packs first)
46
46
  # LLM_CONCURRENCY=4
47
47
  # LLM_TIMEOUT_S=300
48
+ # LLM_BATCH_MAX_OUTPUT_TOKENS=32000 # output limit when several pages go in one request
48
49
  # USD_INR_RATE=92.5 # rupees per dollar, for showing LLM costs in ₹ (not fetched live)
@@ -2,6 +2,35 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ ## 0.4.0 - 2026-11-27
6
+
7
+ - Several pages per LLM request: set **Pages per request** on the Overview page, `--pages-per-request N` on
8
+ `pyocr extract`, or `pages_per_request` in the API's LLM body (1–20, default 1). Pages go out as labelled images
9
+ in one call and the reply is split back into pages at `=== PAGE n ===` markers. A page the reply can't be matched
10
+ to (marker missing or repeated, or cut off by the output limit) is re-sent on its own, with a warning. A batched
11
+ run is its own source (`… · N pages/request`), so you can compare it with one page per request; existing
12
+ single-page results and cache keys are unchanged. Tokens of a shared request are split evenly over its pages, and
13
+ each page's record has a `batch` object with the request totals. New setting `LLM_BATCH_MAX_OUTPUT_TOKENS`
14
+ (default 32000).
15
+ - Easier page selection on the Overview page. The page-range box checks what you type as you type ("9 of 14 pages",
16
+ or what's wrong with the range) and stays in sync with a clickable page map (Shift-click for a range), with
17
+ presets for all pages, the first 5, scans only, and pages with no text from the chosen engine yet. The map marks
18
+ scans and pages that already have text. "Pages per request" has presets (1, 2, 3, 4, 5, 10), a box for any other
19
+ value, and shows how many requests the job will make.
20
+ - **Adjust image** (page inspector, shortcut `e`): preprocess the page image before it is sent to an LLM, then
21
+ check whether that helped. It has a strip of filters, each a thumbnail of the current page (Clean scan, High contrast,
22
+ Black & white with Otsu thresholding, Fix faded, Denoise, Bring out detail, Invert), and fine-tuning for
23
+ brightness, contrast, sharpness, denoise, threshold, resolution, rotation and crop. The viewer shows exactly the
24
+ image the model receives, with its pixel and file size; *Hold to compare* shows the original.
25
+ *A/B: original vs adjusted* transcribes both versions with the same model and diffs them, next to their token
26
+ counts and timings. The settings are remembered per document and also apply to batch extraction from the Overview page.
27
+ - Preprocessing settings are part of the LLM cache key, so each setting is its own source to read, export and
28
+ compare. Runs without preprocessing keep their existing keys, so cached results are unaffected.
29
+ - API: `preprocess` on `POST /api/documents/{id}/pages/{n}/llm` and in job bodies, `?preprocess=` on the page image
30
+ endpoint, `GET /api/documents/{id}/pages/{n}/llm-image` (the exact image a model receives), `GET /api/preprocess`
31
+ (validate / normalise a spec), and `preprocess_presets` in `/api/config`. CLI: `pyocr extract|compare --preprocess`.
32
+ - New dependency: Pillow (image processing).
33
+
5
34
  ## 0.3.0 - 2026-11-27
6
35
 
7
36
  - Now on PyPI: `pip install pyocr-toolkit`. Releases are built, tested and published from GitHub Actions.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: pyocr-toolkit
3
- Version: 0.3.0
3
+ Version: 0.4.0
4
4
  Summary: Inspect and compare PDF/image text extraction - native text, Tesseract OCR and LLMs (Claude, GPT, Gemini, Azure, local) - in your browser.
5
5
  Project-URL: Homepage, https://github.com/utkarsh5026/pyocr
6
6
  Project-URL: Issues, https://github.com/utkarsh5026/pyocr/issues
@@ -228,6 +228,7 @@ Requires-Dist: fastapi>=0.110
228
228
  Requires-Dist: google-genai>=1.0
229
229
  Requires-Dist: jinja2>=3.1
230
230
  Requires-Dist: openai>=1.40
231
+ Requires-Dist: pillow>=10.1
231
232
  Requires-Dist: pydantic-settings>=2.2
232
233
  Requires-Dist: pymupdf>=1.24
233
234
  Requires-Dist: python-multipart>=0.0.9
@@ -373,8 +374,8 @@ Everything you upload and extract is stored in `./data` (change it with `DATA_DI
373
374
  | **Home** `/` | Drop files to upload; see setup status and recent documents. |
374
375
  | **Library** `/documents` | Document cards showing native / OCR / LLM coverage and how many pages still have no text. Filter by status, workspace or name; delete. |
375
376
  | **Workspaces** `/workspaces` | Named groups of documents. Uploading several files or a `.zip` offers to create one, with suggested names (from the file names, or `adjective-scientist` like `festive-albattani`). Open one to rename it, add files or remove documents. |
376
- | **Overview** `/documents/{id}` | Start background extraction (Tesseract or any LLM) for all pages or a range such as `1-5,9`; follow progress; see every *source* (engine + model + prompt) with token usage; export; page thumbnails. |
377
- | **Page inspector** `/documents/{id}/pages/{n}` | Page image next to native, OCR and LLM text; run OCR or an LLM on just this page; per-page diff; a *Side by side* tab with all three texts in synced columns; search hits drawn on the image. Keyboard: `←/→`, `/`, `1-5`, `t`, `o`. |
377
+ | **Overview** `/documents/{id}` | Start background extraction (Tesseract or any LLM) for all pages or a range such as `1-5,9`, typed or picked on a clickable page map (Shift-click for a range; presets for scans only or pages without text yet); choose pages per LLM request; follow progress; see every *source* (engine + model + prompt) with token usage; export; page thumbnails. |
378
+ | **Page inspector** `/documents/{id}/pages/{n}` | Page image next to native, OCR and LLM text; run OCR or an LLM on just this page; per-page diff; a *Side by side* tab with all three texts in synced columns; search hits drawn on the image; *Adjust* to preprocess the image the LLM receives (filters, fine-tuning, crop/rotate) and A/B it against the original. Keyboard: `←/→`, `/`, `1-5`, `t`, `o`, `e`. |
378
379
  | **Full text** `/documents/{id}/text` | Read the whole document from one source, optionally beside the page images; find, copy, download. |
379
380
  | **Compare** `/documents/{id}/compare` | Score source B against source A on every page: document-level CER/WER, a clickable CER-per-page chart, and an aligned side-by-side diff of the selected page (opens on the worst page). Works for OCR vs LLM, native vs LLM, or **model vs model**. |
380
381
  | **Search** `/search` | Search all documents at once. |
@@ -408,9 +409,11 @@ images. For a fully local setup, run Ollama with a vision model and set
408
409
 
409
410
  ```bash
410
411
  pyocr extract report.pdf --engine llm -p anthropic --pages 1-5 --format jsonl -o report.jsonl
412
+ pyocr extract report.pdf --engine llm --pages-per-request 5 # 5 pages in each LLM request
411
413
  pyocr extract scan.tiff --engine ocr --format md # Tesseract, Markdown to stdout
412
414
  pyocr extract born-digital.pdf --engine native # embedded text only, no network
413
415
  pyocr compare scan.pdf -p openai -m gpt-6.2-sol # per-page OCR / native CER vs an LLM
416
+ pyocr extract scan.pdf -p anthropic --preprocess 'gray;auto;contrast=1.5' # adjust the image first (or a preset: clean, bw, ...)
414
417
  pyocr import a.pdf b.pdf scans.zip folder/ -w invoices # add many files as one workspace (zips unpacked)
415
418
  pyocr providers # which providers are ready
416
419
  python -m pyocr_toolkit --help # same CLI without the script on PATH
@@ -418,6 +421,18 @@ python -m pyocr_toolkit --help # same CLI without t
418
421
 
419
422
  Documents processed on the command line also appear in the web app's library.
420
423
 
424
+ ### Several pages per LLM request
425
+
426
+ If your pipeline sends a few pages in one LLM call, set **Pages per request** on the Overview page (or
427
+ `--pages-per-request N`, up to 20) to measure that setup. Each image goes out right after a label like `Page 5`, and the
428
+ model starts each page with `=== PAGE 5 ===`. The reply is split there, and each page is stored, scored and exported on
429
+ its own. A page whose marker is missing or repeated, or that the output limit cut off, is sent again on its own and
430
+ gets a warning, so text is never assigned to a page by guessing. The batch size is part of the prompt, so a batched
431
+ run is its own source: compare it with one page per request to see what batching costs in accuracy. Tokens of a
432
+ shared request are split evenly over its pages. Batching saves only the repeated system prompt (about 10% of input
433
+ tokens), so its main effect is fewer requests. `LLM_BATCH_MAX_OUTPUT_TOKENS` (default 32000) sets the output limit
434
+ for these requests.
435
+
421
436
  ### Batch uploads and workspaces
422
437
 
423
438
  Upload several files, or a `.zip`, and they land together in a **workspace** whose name you can edit. pyocr suggests
@@ -436,6 +451,9 @@ you ask otherwise.
436
451
  3. **LLM.** The page image goes to a vision model with a strict "transcribe, don't correct" prompt
437
452
  ([`prompts.py`](https://github.com/utkarsh5026/pyocr/blob/main/src/pyocr_toolkit/llm/prompts.py)). It reads in context, so it is strong on hard pages, but it can
438
453
  "fix" typos, which the diff view exposes.
454
+ Optionally the image is preprocessed first (grayscale, levels, contrast, denoise, black & white, crop, rotate;
455
+ [`preprocess.py`](src/pyocr_toolkit/preprocess.py)). The settings are part of the cache key, so a run on the
456
+ cleaned-up page is a separate source you can diff against the run on the original.
439
457
  4. **Comparison.** *Edit distance* is the minimum number of character insertions, deletions and substitutions
440
458
  between two texts. **CER** = edits / reference characters; **WER** is the same count over words. For example,
441
459
  "the cat sat" → "the bat sat" has 1 edit, so CER = 1/11 = 9%. Whitespace is normalised first, because line
@@ -131,8 +131,8 @@ Everything you upload and extract is stored in `./data` (change it with `DATA_DI
131
131
  | **Home** `/` | Drop files to upload; see setup status and recent documents. |
132
132
  | **Library** `/documents` | Document cards showing native / OCR / LLM coverage and how many pages still have no text. Filter by status, workspace or name; delete. |
133
133
  | **Workspaces** `/workspaces` | Named groups of documents. Uploading several files or a `.zip` offers to create one, with suggested names (from the file names, or `adjective-scientist` like `festive-albattani`). Open one to rename it, add files or remove documents. |
134
- | **Overview** `/documents/{id}` | Start background extraction (Tesseract or any LLM) for all pages or a range such as `1-5,9`; follow progress; see every *source* (engine + model + prompt) with token usage; export; page thumbnails. |
135
- | **Page inspector** `/documents/{id}/pages/{n}` | Page image next to native, OCR and LLM text; run OCR or an LLM on just this page; per-page diff; a *Side by side* tab with all three texts in synced columns; search hits drawn on the image. Keyboard: `←/→`, `/`, `1-5`, `t`, `o`. |
134
+ | **Overview** `/documents/{id}` | Start background extraction (Tesseract or any LLM) for all pages or a range such as `1-5,9`, typed or picked on a clickable page map (Shift-click for a range; presets for scans only or pages without text yet); choose pages per LLM request; follow progress; see every *source* (engine + model + prompt) with token usage; export; page thumbnails. |
135
+ | **Page inspector** `/documents/{id}/pages/{n}` | Page image next to native, OCR and LLM text; run OCR or an LLM on just this page; per-page diff; a *Side by side* tab with all three texts in synced columns; search hits drawn on the image; *Adjust* to preprocess the image the LLM receives (filters, fine-tuning, crop/rotate) and A/B it against the original. Keyboard: `←/→`, `/`, `1-5`, `t`, `o`, `e`. |
136
136
  | **Full text** `/documents/{id}/text` | Read the whole document from one source, optionally beside the page images; find, copy, download. |
137
137
  | **Compare** `/documents/{id}/compare` | Score source B against source A on every page: document-level CER/WER, a clickable CER-per-page chart, and an aligned side-by-side diff of the selected page (opens on the worst page). Works for OCR vs LLM, native vs LLM, or **model vs model**. |
138
138
  | **Search** `/search` | Search all documents at once. |
@@ -166,9 +166,11 @@ images. For a fully local setup, run Ollama with a vision model and set
166
166
 
167
167
  ```bash
168
168
  pyocr extract report.pdf --engine llm -p anthropic --pages 1-5 --format jsonl -o report.jsonl
169
+ pyocr extract report.pdf --engine llm --pages-per-request 5 # 5 pages in each LLM request
169
170
  pyocr extract scan.tiff --engine ocr --format md # Tesseract, Markdown to stdout
170
171
  pyocr extract born-digital.pdf --engine native # embedded text only, no network
171
172
  pyocr compare scan.pdf -p openai -m gpt-6.2-sol # per-page OCR / native CER vs an LLM
173
+ pyocr extract scan.pdf -p anthropic --preprocess 'gray;auto;contrast=1.5' # adjust the image first (or a preset: clean, bw, ...)
172
174
  pyocr import a.pdf b.pdf scans.zip folder/ -w invoices # add many files as one workspace (zips unpacked)
173
175
  pyocr providers # which providers are ready
174
176
  python -m pyocr_toolkit --help # same CLI without the script on PATH
@@ -176,6 +178,18 @@ python -m pyocr_toolkit --help # same CLI without t
176
178
 
177
179
  Documents processed on the command line also appear in the web app's library.
178
180
 
181
+ ### Several pages per LLM request
182
+
183
+ If your pipeline sends a few pages in one LLM call, set **Pages per request** on the Overview page (or
184
+ `--pages-per-request N`, up to 20) to measure that setup. Each image goes out right after a label like `Page 5`, and the
185
+ model starts each page with `=== PAGE 5 ===`. The reply is split there, and each page is stored, scored and exported on
186
+ its own. A page whose marker is missing or repeated, or that the output limit cut off, is sent again on its own and
187
+ gets a warning, so text is never assigned to a page by guessing. The batch size is part of the prompt, so a batched
188
+ run is its own source: compare it with one page per request to see what batching costs in accuracy. Tokens of a
189
+ shared request are split evenly over its pages. Batching saves only the repeated system prompt (about 10% of input
190
+ tokens), so its main effect is fewer requests. `LLM_BATCH_MAX_OUTPUT_TOKENS` (default 32000) sets the output limit
191
+ for these requests.
192
+
179
193
  ### Batch uploads and workspaces
180
194
 
181
195
  Upload several files, or a `.zip`, and they land together in a **workspace** whose name you can edit. pyocr suggests
@@ -194,6 +208,9 @@ you ask otherwise.
194
208
  3. **LLM.** The page image goes to a vision model with a strict "transcribe, don't correct" prompt
195
209
  ([`prompts.py`](https://github.com/utkarsh5026/pyocr/blob/main/src/pyocr_toolkit/llm/prompts.py)). It reads in context, so it is strong on hard pages, but it can
196
210
  "fix" typos, which the diff view exposes.
211
+ Optionally the image is preprocessed first (grayscale, levels, contrast, denoise, black & white, crop, rotate;
212
+ [`preprocess.py`](src/pyocr_toolkit/preprocess.py)). The settings are part of the cache key, so a run on the
213
+ cleaned-up page is a separate source you can diff against the run on the original.
197
214
  4. **Comparison.** *Edit distance* is the minimum number of character insertions, deletions and substitutions
198
215
  between two texts. **CER** = edits / reference characters; **WER** is the same count over words. For example,
199
216
  "the cat sat" → "the bat sat" has 1 edit, so CER = 1/11 = 9%. Whitespace is normalised first, because line
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "pyocr-toolkit"
3
- version = "0.3.0"
3
+ version = "0.4.0"
4
4
  description = "Inspect and compare PDF/image text extraction - native text, Tesseract OCR and LLMs (Claude, GPT, Gemini, Azure, local) - in your browser."
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.10"
@@ -25,6 +25,7 @@ classifiers = [
25
25
  ]
26
26
  dependencies = [
27
27
  "pymupdf>=1.24",
28
+ "pillow>=10.1",
28
29
  "fastapi>=0.110",
29
30
  "uvicorn[standard]>=0.29",
30
31
  "jinja2>=3.1",
@@ -1,3 +1,3 @@
1
1
  """pyocr-toolkit - inspect PDF/image text extraction: native text vs Tesseract OCR vs LLM transcription."""
2
2
 
3
- __version__ = "0.3.0"
3
+ __version__ = "0.4.0"
@@ -12,6 +12,7 @@ import shutil
12
12
  from dataclasses import asdict
13
13
  from pathlib import Path
14
14
  from typing import Literal
15
+ from urllib.parse import quote
15
16
 
16
17
  from fastapi import APIRouter, FastAPI, File, Form, HTTPException, Query, Request, UploadFile
17
18
  from fastapi.concurrency import run_in_threadpool
@@ -23,7 +24,8 @@ from . import __version__, compare, search
23
24
  from .config import Settings, get_settings
24
25
  from .documents import DocumentError, DocumentStore, OCRUnavailableError, OpenDocument
25
26
  from .jobs import JobManager
26
- from .llm import PROMPT_MODES, ProviderError, build_providers, catalog
27
+ from .llm import MAX_PAGES_PER_REQUEST, PROMPT_MODES, ProviderError, build_providers, catalog
28
+ from .preprocess import Preprocess, presets_json, process_bytes
27
29
  from .service import LLMSpec, Services, parse_pages
28
30
  from .workspaces import WorkspaceStore, ingest, suggest_names
29
31
 
@@ -36,10 +38,14 @@ class LLMRunBody(BaseModel):
36
38
  model: str | None = None
37
39
  prompt_mode: str = "verbatim"
38
40
  custom_prompt: str | None = None
41
+ preprocess: str | None = Field(None, description="image preprocessing, e.g. 'gray;contrast=1.5' or a preset id")
42
+ pages_per_request: int = Field(1, ge=1, le=MAX_PAGES_PER_REQUEST,
43
+ description="pages sent together in one LLM request (1 = one page per request)")
39
44
  force: bool = False
40
45
 
41
46
  def spec(self) -> LLMSpec:
42
- return LLMSpec(self.provider, self.model, self.prompt_mode, self.custom_prompt)
47
+ return LLMSpec(self.provider, self.model, self.prompt_mode, self.custom_prompt,
48
+ preprocess=self.preprocess or "", pages_per_request=self.pages_per_request)
43
49
 
44
50
 
45
51
  class TextRef(BaseModel):
@@ -122,6 +128,12 @@ def build_api(settings: Settings, store: DocumentStore, services: Services, jobs
122
128
  def get_doc(doc_id: str) -> OpenDocument:
123
129
  return store.get(doc_id)
124
130
 
131
+ def parse_pre(spec: str | None) -> Preprocess:
132
+ try:
133
+ return Preprocess.parse(spec)
134
+ except ValueError as exc:
135
+ raise HTTPException(400, str(exc)) from exc
136
+
125
137
  def doc_summary(doc: OpenDocument) -> dict:
126
138
  """Meta + extraction coverage, used by the library and overview pages."""
127
139
  n = doc.meta.page_count
@@ -138,12 +150,15 @@ def build_api(settings: Settings, store: DocumentStore, services: Services, jobs
138
150
  "version": __version__,
139
151
  "providers": [p.describe() for p in providers.values()],
140
152
  "prompt_modes": [{"id": k, "label": v["label"], "prompt": v["system"]} for k, v in PROMPT_MODES.items()],
153
+ "max_pages_per_request": MAX_PAGES_PER_REQUEST,
141
154
  "tesseract_available": shutil.which("tesseract") is not None,
142
155
  "tesseract_language": settings.tesseract_language,
143
156
  "max_upload_mb": settings.max_upload_mb,
144
157
  "preview_dpi": settings.preview_dpi,
145
158
  "llm_dpi": settings.llm_dpi,
159
+ "llm_max_edge_px": settings.llm_max_edge_px,
146
160
  "ocr_dpi": settings.ocr_dpi,
161
+ "preprocess_presets": presets_json(),
147
162
  }
148
163
 
149
164
  @api.get("/models", tags=["models"])
@@ -255,9 +270,35 @@ def build_api(settings: Settings, store: DocumentStore, services: Services, jobs
255
270
  return [doc.page_info(n) for n in doc.iter_pages()]
256
271
 
257
272
  @api.get("/documents/{doc_id}/pages/{page}/image", tags=["pages"])
258
- def page_image(doc_id: str, page: int, dpi: int = Query(None, ge=36, le=600)):
259
- png = get_doc(doc_id).render(page, dpi or settings.preview_dpi)
260
- return Response(png, media_type="image/png", headers={"Cache-Control": "max-age=3600"})
273
+ def page_image(doc_id: str, page: int, dpi: int = Query(None, ge=36, le=600),
274
+ preprocess: str | None = Query(None, description="apply image preprocessing (preview / thumbnails)")):
275
+ """Page render for display. With ``preprocess`` the filters run at this ``dpi`` (its own ``dpi=`` step is
276
+ ignored), which is right for thumbnails; use ``/llm-image`` to see exactly what a model receives."""
277
+ doc, pre = get_doc(doc_id), parse_pre(preprocess)
278
+ dpi = dpi or settings.preview_dpi
279
+ if pre.changes_pixels:
280
+ body, mime = process_bytes(doc.render(page, dpi, "ppm"), pre)
281
+ else:
282
+ body, mime = doc.render(page, dpi), "image/png"
283
+ return Response(body, media_type=mime, headers={"Cache-Control": "max-age=3600"})
284
+
285
+ @api.get("/documents/{doc_id}/pages/{page}/llm-image", tags=["pages"])
286
+ def page_llm_image(doc_id: str, page: int, preprocess: str | None = None):
287
+ """The exact image an LLM run sends for this page (LLM_DPI, LLM_MAX_EDGE_PX, PNG/JPEG choice, preprocessing).
288
+
289
+ Headers describe it, so the UI can show size and cost-relevant facts without decoding it.
290
+ """
291
+ doc, pre = get_doc(doc_id), parse_pre(preprocess)
292
+ body, mime = services.llm_image(doc, page, pre)
293
+ return Response(body, media_type=mime, headers={
294
+ # percent-encoded: header values are latin-1 and the label may contain × or °
295
+ "Cache-Control": "max-age=600", "X-Preprocess": quote(str(pre)), "X-Preprocess-Label": quote(pre.describe()),
296
+ })
297
+
298
+ @api.get("/preprocess", tags=["pages"])
299
+ def check_preprocess(spec: str = ""):
300
+ """Validate and normalise a preprocessing spec (400 with a readable message if it's wrong)."""
301
+ return parse_pre(spec).to_json()
261
302
 
262
303
  @api.get("/documents/{doc_id}/sources", tags=["text"])
263
304
  def sources(doc_id: str):
@@ -184,23 +184,25 @@ async def _extract(args: argparse.Namespace) -> int:
184
184
  texts[n] = (await asyncio.to_thread(services.run_ocr_page, doc, n)).text
185
185
  print(f" OCR page {n + 1}/{doc.meta.page_count}", file=sys.stderr)
186
186
  else:
187
- spec = LLMSpec(args.provider, args.model, args.mode)
188
- provider, model, _ = services.resolve_spec(spec)
187
+ spec = LLMSpec(args.provider, args.model, args.mode, preprocess=args.preprocess or "",
188
+ pages_per_request=args.pages_per_request)
189
+ try:
190
+ provider, model, _ = services.resolve_spec(spec)
191
+ except ValueError as exc: # bad --pages-per-request or --preprocess
192
+ print(str(exc), file=sys.stderr)
193
+ return 2
189
194
  if not provider.configured:
190
195
  print(f"{provider.label} is not configured: set {', '.join(provider.missing_settings())}", file=sys.stderr)
191
196
  return 2
192
197
 
193
- async def one(n: int):
194
- res = await services.run_llm_page(doc, n, spec)
198
+ for n, res in (await services.run_llm_pages(doc, pages, spec)).items():
199
+ if isinstance(res, BaseException):
200
+ print(f" page {n + 1} failed: {res}", file=sys.stderr)
201
+ continue
195
202
  note = "cached" if res["cached"] else f"{res['latency_ms'] / 1000:.1f}s"
196
203
  print(f" LLM page {n + 1}: {note}" + "".join(f" ⚠ {w}" for w in res["warnings"]), file=sys.stderr)
197
204
  texts[n] = res["text"]
198
205
 
199
- results = await asyncio.gather(*(one(n) for n in pages), return_exceptions=True)
200
- for n, r in zip(pages, results):
201
- if isinstance(r, Exception):
202
- print(f" page {n + 1} failed: {r}", file=sys.stderr)
203
-
204
206
  ordered = [(n, texts.get(n, "")) for n in pages]
205
207
  source = args.engine if args.engine != "llm" else f"llm:{args.provider}"
206
208
  if args.format == "jsonl":
@@ -224,7 +226,7 @@ async def _compare(args: argparse.Namespace) -> int:
224
226
 
225
227
  settings, services = _services()
226
228
  doc = _load_document(args.file)
227
- spec = LLMSpec(args.provider, args.model, "verbatim")
229
+ spec = LLMSpec(args.provider, args.model, "verbatim", preprocess=args.preprocess or "")
228
230
  provider, _, _ = services.resolve_spec(spec)
229
231
  if not provider.configured:
230
232
  print(f"{provider.label} is not configured: set {', '.join(provider.missing_settings())}", file=sys.stderr)
@@ -248,6 +250,12 @@ async def _compare(args: argparse.Namespace) -> int:
248
250
 
249
251
 
250
252
  # ---------------------------------------------------------------- parser
253
+ PREPROCESS_HELP = (
254
+ "image preprocessing before the LLM sees the page: a preset (clean, contrast, bw, faded, denoise, detail, "
255
+ "invert) or steps like 'gray;auto;contrast=1.5;threshold=otsu' (tune them visually with Adjust image in "
256
+ "`pyocr serve`, then copy the spec)"
257
+ )
258
+
251
259
  def build_parser() -> argparse.ArgumentParser:
252
260
  parser = argparse.ArgumentParser(prog="pyocr", description=__doc__,
253
261
  formatter_class=argparse.RawDescriptionHelpFormatter)
@@ -275,7 +283,10 @@ def build_parser() -> argparse.ArgumentParser:
275
283
  e.add_argument("-p", "--provider", default="anthropic", help="for --engine llm")
276
284
  e.add_argument("-m", "--model", default=None)
277
285
  e.add_argument("--mode", default="verbatim", choices=["verbatim", "markdown"], help="LLM prompt")
286
+ e.add_argument("--pages-per-request", type=int, default=1, metavar="N",
287
+ help="send N pages to the LLM in one request (default 1); a separate source from N=1")
278
288
  e.add_argument("--pages", default=None, help="1-based ranges, e.g. 1-3,7 (default: all)")
289
+ e.add_argument("--preprocess", default=None, metavar="SPEC", help=PREPROCESS_HELP)
279
290
  e.add_argument("--format", choices=["txt", "md", "json", "jsonl"], default="txt")
280
291
  e.add_argument("-o", "--output", type=Path, default=None, help="file to write (default: stdout)")
281
292
  e.set_defaults(func=lambda a: asyncio.run(_extract(a)))
@@ -291,6 +302,7 @@ def build_parser() -> argparse.ArgumentParser:
291
302
  c.add_argument("-p", "--provider", default="anthropic")
292
303
  c.add_argument("-m", "--model", default=None)
293
304
  c.add_argument("--pages", default=None)
305
+ c.add_argument("--preprocess", default=None, metavar="SPEC", help=PREPROCESS_HELP)
294
306
  c.set_defaults(func=lambda a: asyncio.run(_compare(a)))
295
307
  return parser
296
308
 
@@ -32,6 +32,10 @@ class Settings(BaseSettings):
32
32
  # How many LLM calls may run at once when transcribing many pages.
33
33
  llm_concurrency: int = 4
34
34
  llm_timeout_s: float = 300.0
35
+ # Output-token limit for a request that carries several pages ("pages per
36
+ # request" > 1). Single-page requests keep 16000. Lower it if a model's own
37
+ # output limit is smaller (the API then rejects the request).
38
+ llm_batch_max_output_tokens: int = 32000
35
39
  # Rupees per US dollar, used to show LLM costs in ₹ next to the USD list
36
40
  # prices from the model catalog. Not fetched live (no outbound calls besides
37
41
  # the chosen provider); ~92.5 on 2026-11-26. Set it to today's rate.
@@ -166,7 +166,7 @@ class OpenDocument:
166
166
 
167
167
  def render(self, number: int, dpi: int, fmt: str = "png", max_edge_px: int | None = None,
168
168
  jpg_quality: int = 90) -> bytes:
169
- """Rasterise a page. ``fmt`` is ``png`` or ``jpeg``."""
169
+ """Rasterise a page. ``fmt`` is ``png``, ``jpeg`` or ``ppm`` (uncompressed, for further processing)."""
170
170
  with self._lock:
171
171
  page = self._page(number)
172
172
  if max_edge_px:
@@ -176,6 +176,8 @@ class OpenDocument:
176
176
  pix = page.get_pixmap(dpi=dpi, alpha=False)
177
177
  if fmt == "jpeg":
178
178
  return pix.tobytes("jpeg", jpg_quality=jpg_quality)
179
+ if fmt == "ppm":
180
+ return pix.tobytes("ppm")
179
181
  return pix.tobytes("png")
180
182
 
181
183
  # -- text layers ----------------------------------------------------------
@@ -224,8 +226,15 @@ class OpenDocument:
224
226
  return self.folder / "llm" / str(number)
225
227
 
226
228
  @staticmethod
227
- def llm_cache_key(provider: str, model: str, prompt: str) -> str:
228
- digest = hashlib.sha256(f"{provider}\0{model}\0{prompt}".encode()).hexdigest()[:16]
229
+ def llm_cache_key(provider: str, model: str, prompt: str, preprocess: str = "") -> str:
230
+ """Stable id of one LLM configuration, identical on every page of a document.
231
+
232
+ ``preprocess`` is the canonical image-preprocessing spec. It is only mixed
233
+ into the digest when non-empty, so runs on the plain page image keep the
234
+ keys they had before preprocessing existed (no orphaned caches).
235
+ """
236
+ material = f"{provider}\0{model}\0{prompt}" + (f"\0{preprocess}" if preprocess else "")
237
+ digest = hashlib.sha256(material.encode()).hexdigest()[:16]
229
238
  safe_model = re.sub(r"[^A-Za-z0-9._-]+", "_", model)[:60]
230
239
  return f"{provider}__{safe_model}__{digest}"
231
240
 
@@ -45,4 +45,5 @@ GEMINI_API_KEY=
45
45
  # TESSERACT_LANGUAGE=eng # e.g. eng+deu (install the language packs first)
46
46
  # LLM_CONCURRENCY=4
47
47
  # LLM_TIMEOUT_S=300
48
+ # LLM_BATCH_MAX_OUTPUT_TOKENS=32000 # output limit when several pages go in one request
48
49
  # USD_INR_RATE=92.5 # rupees per dollar, for showing LLM costs in ₹ (not fetched live)
@@ -13,6 +13,11 @@ Progress is reported in pages. ``current_pages`` are pages the engine is working
13
13
  on right now; LLM pages that are still waiting for an ``LLM_CONCURRENCY`` slot
14
14
  (another job or a workspace run holds it) are in ``waiting_pages`` instead, so
15
15
  the UI doesn't claim the model is reading a page it hasn't been sent yet.
16
+
17
+ With ``pages_per_request`` > 1 a worker takes a *chunk* of pages and sends them in
18
+ one request (``Services.plan_llm_chunks`` leaves cached pages out first, so each
19
+ request is full). The chunk holds one ``LLM_CONCURRENCY`` slot, since it is one
20
+ call, and progress is still counted in pages.
16
21
  """
17
22
 
18
23
  from __future__ import annotations
@@ -25,6 +30,7 @@ from typing import Any, Literal
25
30
 
26
31
  from .documents import DocumentStore
27
32
  from .llm import catalog
33
+ from .preprocess import Preprocess
28
34
  from .service import LLMSpec, Services
29
35
 
30
36
  JobKind = Literal["ocr", "llm"]
@@ -131,6 +137,11 @@ class JobManager:
131
137
  if not provider.configured:
132
138
  raise ValueError(f"{provider.label} is not configured: set {', '.join(provider.missing_settings())}")
133
139
  label = f"LLM · {provider.label} · {model} · {llm.prompt_mode}"
140
+ pre = Preprocess.parse(llm.preprocess)
141
+ if not pre.is_identity:
142
+ label += f" · image: {pre.describe()}"
143
+ if llm.pages_per_request > 1:
144
+ label += f" · {llm.pages_per_request} pages/request"
134
145
  found = catalog.price(model, provider.id)
135
146
  if found:
136
147
  price = {"in": found[0], "out": found[1], "model": found[2],
@@ -154,48 +165,71 @@ class JobManager:
154
165
  doc = self.store.get(job.doc_id)
155
166
  job.status = "running"
156
167
  job.started_at = time.time()
157
- queue: asyncio.Queue[int] = asyncio.Queue()
158
- for p in job.pages:
159
- queue.put_nowait(p)
160
168
  spec = LLMSpec(**job.llm) if job.llm else None
169
+ batched = spec is not None and spec.pages_per_request > 1
170
+ chunks: list[list[int]] = [[p] for p in job.pages]
171
+ if batched:
172
+ cached, chunks = self.services.plan_llm_chunks(doc, job.pages, spec, job.force)
173
+ job.cached += len(cached)
174
+ job.done += len(cached)
175
+ queue: asyncio.Queue[list[int]] = asyncio.Queue()
176
+ for chunk in chunks:
177
+ queue.put_nowait(chunk)
178
+
179
+ def count(res: dict[str, Any]) -> None:
180
+ if res.get("cached"):
181
+ job.cached += 1
182
+ else:
183
+ job.input_tokens += res.get("input_tokens") or 0
184
+ job.output_tokens += res.get("output_tokens") or 0
161
185
 
162
186
  async def worker() -> None:
163
187
  while not queue.empty():
164
- page = queue.get_nowait()
188
+ chunk = queue.get_nowait()
165
189
  # LLM pages wait for a semaphore slot before the model sees them.
166
- (job.waiting_pages if job.kind == "llm" else job.current_pages).append(page)
190
+ (job.waiting_pages if job.kind == "llm" else job.current_pages).extend(chunk)
167
191
 
168
- def started(page: int = page) -> None:
169
- job.waiting_pages.remove(page)
170
- job.current_pages.append(page)
192
+ def started(chunk: list[int] = chunk) -> None:
193
+ for page in chunk:
194
+ if page in job.waiting_pages:
195
+ job.waiting_pages.remove(page)
196
+ job.current_pages.append(page)
171
197
 
172
198
  try:
173
199
  if job.kind == "ocr":
200
+ page = chunk[0]
174
201
  if not job.force and doc.cached_ocr_text(page) is not None:
175
202
  job.cached += 1
176
203
  else:
177
204
  await asyncio.to_thread(self.services.run_ocr_page, doc, page, job.force)
205
+ elif batched:
206
+ outcomes = await self.services.run_llm_batch(doc, chunk, spec, force=job.force,
207
+ on_start=started)
208
+ for page, res in outcomes.items():
209
+ if isinstance(res, Exception):
210
+ job.failed += 1
211
+ job.errors.append(f"page {page + 1}: {res}")
212
+ else:
213
+ count(res)
178
214
  else:
179
- res = await self.services.run_llm_page(doc, page, spec, force=job.force, on_start=started)
180
- if res.get("cached"):
181
- job.cached += 1
182
- else:
183
- job.input_tokens += res.get("input_tokens") or 0
184
- job.output_tokens += res.get("output_tokens") or 0
215
+ count(await self.services.run_llm_page(doc, chunk[0], spec, force=job.force,
216
+ on_start=started))
185
217
  except asyncio.CancelledError:
186
218
  raise
187
219
  except Exception as exc: # keep going; report per page
188
- job.failed += 1
189
- job.errors.append(f"page {page + 1}: {exc}")
220
+ job.failed += len(chunk)
221
+ pages = ", ".join(str(p + 1) for p in chunk)
222
+ job.errors.append(f"page{'s' if len(chunk) > 1 else ''} {pages}: {exc}")
190
223
  finally:
191
224
  for active in (job.current_pages, job.waiting_pages):
192
- if page in active:
193
- active.remove(page)
194
- job.done += 1
225
+ for page in chunk:
226
+ if page in active:
227
+ active.remove(page)
228
+ job.done += len(chunk)
195
229
 
196
230
  concurrency = self.ocr_concurrency if job.kind == "ocr" else self.services.settings.llm_concurrency
197
231
  try:
198
- await asyncio.gather(*(worker() for _ in range(max(1, min(concurrency, job.total)))))
232
+ await asyncio.gather(*(worker() for _ in range(max(1, min(concurrency, len(chunks))))))
199
233
  job.status = "failed" if job.failed == job.total else "done"
200
234
  except asyncio.CancelledError:
201
235
  job.status = "cancelled"
@@ -6,6 +6,7 @@ from ..config import Settings
6
6
  from . import catalog
7
7
  from .anthropic_provider import AnthropicFoundryProvider, AnthropicProvider
8
8
  from .base import (
9
+ PageImage,
9
10
  Provider,
10
11
  ProviderError,
11
12
  ProviderNotConfigured,
@@ -14,7 +15,15 @@ from .base import (
14
15
  )
15
16
  from .gemini_provider import GeminiProvider
16
17
  from .openai_provider import AzureOpenAIProvider, OpenAICompatibleProvider, OpenAIProvider
17
- from .prompts import PROMPT_MODES, USER_PROMPT, resolve_prompt
18
+ from .prompts import (
19
+ BATCH_USER_PROMPT,
20
+ MAX_PAGES_PER_REQUEST,
21
+ PROMPT_MODES,
22
+ USER_PROMPT,
23
+ batch_rules,
24
+ resolve_prompt,
25
+ split_batch,
26
+ )
18
27
 
19
28
  PROVIDER_CLASSES: list[type[Provider]] = [
20
29
  AnthropicProvider,
@@ -32,6 +41,11 @@ def build_providers(settings: Settings) -> dict[str, Provider]:
32
41
 
33
42
  __all__ = [
34
43
  "catalog",
44
+ "BATCH_USER_PROMPT",
45
+ "MAX_PAGES_PER_REQUEST",
46
+ "PageImage",
47
+ "batch_rules",
48
+ "split_batch",
35
49
  "PROMPT_MODES",
36
50
  "USER_PROMPT",
37
51
  "Provider",
@@ -38,6 +38,23 @@ def _supports_effort(model: str) -> bool:
38
38
  return version >= (4, 6)
39
39
 
40
40
 
41
+ def _image_blocks(req: TranscriptionRequest) -> list[dict]:
42
+ """Image blocks, each preceded by its label when the request holds several pages."""
43
+ blocks: list[dict] = []
44
+ for page in req.page_images():
45
+ if page.label:
46
+ blocks.append({"type": "text", "text": page.label})
47
+ blocks.append({
48
+ "type": "image",
49
+ "source": {
50
+ "type": "base64",
51
+ "media_type": page.mime_type,
52
+ "data": base64.standard_b64encode(page.image).decode("ascii"),
53
+ },
54
+ })
55
+ return blocks
56
+
57
+
41
58
  class _ClaudeBase(Provider):
42
59
  suggested_models = catalog.recommended("anthropic") + ["claude-haiku-5-5"]
43
60
  supports_server_fallback = True
@@ -62,17 +79,7 @@ class _ClaudeBase(Provider):
62
79
  "system": req.system_prompt,
63
80
  "messages": [{
64
81
  "role": "user",
65
- "content": [
66
- {
67
- "type": "image",
68
- "source": {
69
- "type": "base64",
70
- "media_type": req.mime_type,
71
- "data": base64.standard_b64encode(req.image).decode("ascii"),
72
- },
73
- },
74
- {"type": "text", "text": req.user_prompt},
75
- ],
82
+ "content": [*_image_blocks(req), {"type": "text", "text": req.user_prompt}],
76
83
  }],
77
84
  }
78
85
  if _supports_effort(model) and self.settings.anthropic_effort: