pyocr-toolkit 0.5.0__tar.gz → 0.6.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 (107) hide show
  1. {pyocr_toolkit-0.5.0 → pyocr_toolkit-0.6.0}/CHANGELOG.md +33 -0
  2. {pyocr_toolkit-0.5.0 → pyocr_toolkit-0.6.0}/PKG-INFO +7 -5
  3. {pyocr_toolkit-0.5.0 → pyocr_toolkit-0.6.0}/README.md +6 -4
  4. {pyocr_toolkit-0.5.0 → pyocr_toolkit-0.6.0}/pyproject.toml +1 -1
  5. {pyocr_toolkit-0.5.0 → pyocr_toolkit-0.6.0}/src/pyocr_toolkit/__init__.py +1 -1
  6. {pyocr_toolkit-0.5.0 → pyocr_toolkit-0.6.0}/src/pyocr_toolkit/api.py +65 -3
  7. {pyocr_toolkit-0.5.0 → pyocr_toolkit-0.6.0}/src/pyocr_toolkit/cli.py +22 -5
  8. {pyocr_toolkit-0.5.0 → pyocr_toolkit-0.6.0}/src/pyocr_toolkit/documents.py +7 -5
  9. {pyocr_toolkit-0.5.0 → pyocr_toolkit-0.6.0}/src/pyocr_toolkit/export.py +21 -7
  10. pyocr_toolkit-0.6.0/src/pyocr_toolkit/extract.py +892 -0
  11. {pyocr_toolkit-0.5.0 → pyocr_toolkit-0.6.0}/src/pyocr_toolkit/jobs.py +3 -0
  12. {pyocr_toolkit-0.5.0 → pyocr_toolkit-0.6.0}/src/pyocr_toolkit/llm/__init__.py +8 -0
  13. {pyocr_toolkit-0.5.0 → pyocr_toolkit-0.6.0}/src/pyocr_toolkit/llm/anthropic_provider.py +42 -3
  14. {pyocr_toolkit-0.5.0 → pyocr_toolkit-0.6.0}/src/pyocr_toolkit/llm/base.py +18 -3
  15. {pyocr_toolkit-0.5.0 → pyocr_toolkit-0.6.0}/src/pyocr_toolkit/llm/gemini_provider.py +5 -0
  16. {pyocr_toolkit-0.5.0 → pyocr_toolkit-0.6.0}/src/pyocr_toolkit/llm/openai_provider.py +19 -1
  17. {pyocr_toolkit-0.5.0 → pyocr_toolkit-0.6.0}/src/pyocr_toolkit/llm/prompts.py +71 -0
  18. {pyocr_toolkit-0.5.0 → pyocr_toolkit-0.6.0}/src/pyocr_toolkit/service.py +123 -12
  19. pyocr_toolkit-0.6.0/src/pyocr_toolkit/static/common.js +1176 -0
  20. {pyocr_toolkit-0.5.0 → pyocr_toolkit-0.6.0}/src/pyocr_toolkit/static/document.js +5 -4
  21. {pyocr_toolkit-0.5.0 → pyocr_toolkit-0.6.0}/src/pyocr_toolkit/static/styles.css +91 -0
  22. {pyocr_toolkit-0.5.0 → pyocr_toolkit-0.6.0}/src/pyocr_toolkit/static/workspace.js +31 -4
  23. pyocr_toolkit-0.6.0/src/pyocr_toolkit/templates/_llm_picker.html +64 -0
  24. {pyocr_toolkit-0.5.0 → pyocr_toolkit-0.6.0}/src/pyocr_toolkit/templates/help.html +47 -2
  25. {pyocr_toolkit-0.5.0 → pyocr_toolkit-0.6.0}/src/pyocr_toolkit/templates/workspace.html +2 -0
  26. pyocr_toolkit-0.6.0/tests/test_extract.py +466 -0
  27. {pyocr_toolkit-0.5.0 → pyocr_toolkit-0.6.0}/tests/test_providers.py +119 -0
  28. pyocr_toolkit-0.5.0/src/pyocr_toolkit/static/common.js +0 -584
  29. pyocr_toolkit-0.5.0/src/pyocr_toolkit/templates/_llm_picker.html +0 -12
  30. {pyocr_toolkit-0.5.0 → pyocr_toolkit-0.6.0}/.env.example +0 -0
  31. {pyocr_toolkit-0.5.0 → pyocr_toolkit-0.6.0}/.gitignore +0 -0
  32. {pyocr_toolkit-0.5.0 → pyocr_toolkit-0.6.0}/CONTRIBUTING.md +0 -0
  33. {pyocr_toolkit-0.5.0 → pyocr_toolkit-0.6.0}/LICENSE +0 -0
  34. {pyocr_toolkit-0.5.0 → pyocr_toolkit-0.6.0}/hero-video/README.md +0 -0
  35. {pyocr_toolkit-0.5.0 → pyocr_toolkit-0.6.0}/hero-video/src/HeroDemo.tsx +0 -0
  36. {pyocr_toolkit-0.5.0 → pyocr_toolkit-0.6.0}/hero-video/src/Root.tsx +0 -0
  37. {pyocr_toolkit-0.5.0 → pyocr_toolkit-0.6.0}/hero-video/src/assets.d.ts +0 -0
  38. {pyocr_toolkit-0.5.0 → pyocr_toolkit-0.6.0}/hero-video/src/index.ts +0 -0
  39. {pyocr_toolkit-0.5.0 → pyocr_toolkit-0.6.0}/hero-video/src/motion.tsx +0 -0
  40. {pyocr_toolkit-0.5.0 → pyocr_toolkit-0.6.0}/hero-video/src/scenes/CatchScene.tsx +0 -0
  41. {pyocr_toolkit-0.5.0 → pyocr_toolkit-0.6.0}/hero-video/src/scenes/ColdOpenScene.tsx +0 -0
  42. {pyocr_toolkit-0.5.0 → pyocr_toolkit-0.6.0}/hero-video/src/scenes/MeasureScene.tsx +0 -0
  43. {pyocr_toolkit-0.5.0 → pyocr_toolkit-0.6.0}/hero-video/src/scenes/MontageScene.tsx +0 -0
  44. {pyocr_toolkit-0.5.0 → pyocr_toolkit-0.6.0}/hero-video/src/scenes/OutroScene.tsx +0 -0
  45. {pyocr_toolkit-0.5.0 → pyocr_toolkit-0.6.0}/hero-video/src/scenes/ThreeWaysScene.tsx +0 -0
  46. {pyocr_toolkit-0.5.0 → pyocr_toolkit-0.6.0}/hero-video/src/theme.ts +0 -0
  47. {pyocr_toolkit-0.5.0 → pyocr_toolkit-0.6.0}/hero-video/src/ui.tsx +0 -0
  48. {pyocr_toolkit-0.5.0 → pyocr_toolkit-0.6.0}/src/pyocr_toolkit/__main__.py +0 -0
  49. {pyocr_toolkit-0.5.0 → pyocr_toolkit-0.6.0}/src/pyocr_toolkit/brands.py +0 -0
  50. {pyocr_toolkit-0.5.0 → pyocr_toolkit-0.6.0}/src/pyocr_toolkit/compare.py +0 -0
  51. {pyocr_toolkit-0.5.0 → pyocr_toolkit-0.6.0}/src/pyocr_toolkit/config.py +0 -0
  52. {pyocr_toolkit-0.5.0 → pyocr_toolkit-0.6.0}/src/pyocr_toolkit/credentials.py +0 -0
  53. {pyocr_toolkit-0.5.0 → pyocr_toolkit-0.6.0}/src/pyocr_toolkit/env.example +0 -0
  54. {pyocr_toolkit-0.5.0 → pyocr_toolkit-0.6.0}/src/pyocr_toolkit/llm/catalog.py +0 -0
  55. {pyocr_toolkit-0.5.0 → pyocr_toolkit-0.6.0}/src/pyocr_toolkit/ocr/__init__.py +0 -0
  56. {pyocr_toolkit-0.5.0 → pyocr_toolkit-0.6.0}/src/pyocr_toolkit/ocr/base.py +0 -0
  57. {pyocr_toolkit-0.5.0 → pyocr_toolkit-0.6.0}/src/pyocr_toolkit/ocr/cloud.py +0 -0
  58. {pyocr_toolkit-0.5.0 → pyocr_toolkit-0.6.0}/src/pyocr_toolkit/ocr/local.py +0 -0
  59. {pyocr_toolkit-0.5.0 → pyocr_toolkit-0.6.0}/src/pyocr_toolkit/ocr/tesseract.py +0 -0
  60. {pyocr_toolkit-0.5.0 → pyocr_toolkit-0.6.0}/src/pyocr_toolkit/pdftext.py +0 -0
  61. {pyocr_toolkit-0.5.0 → pyocr_toolkit-0.6.0}/src/pyocr_toolkit/preprocess.py +0 -0
  62. {pyocr_toolkit-0.5.0 → pyocr_toolkit-0.6.0}/src/pyocr_toolkit/search.py +0 -0
  63. {pyocr_toolkit-0.5.0 → pyocr_toolkit-0.6.0}/src/pyocr_toolkit/static/compare.js +0 -0
  64. {pyocr_toolkit-0.5.0 → pyocr_toolkit-0.6.0}/src/pyocr_toolkit/static/jobs.js +0 -0
  65. {pyocr_toolkit-0.5.0 → pyocr_toolkit-0.6.0}/src/pyocr_toolkit/static/library.js +0 -0
  66. {pyocr_toolkit-0.5.0 → pyocr_toolkit-0.6.0}/src/pyocr_toolkit/static/logos/README.md +0 -0
  67. {pyocr_toolkit-0.5.0 → pyocr_toolkit-0.6.0}/src/pyocr_toolkit/static/logos/claude.svg +0 -0
  68. {pyocr_toolkit-0.5.0 → pyocr_toolkit-0.6.0}/src/pyocr_toolkit/static/logos/googlecloud.svg +0 -0
  69. {pyocr_toolkit-0.5.0 → pyocr_toolkit-0.6.0}/src/pyocr_toolkit/static/logos/googlegemini.svg +0 -0
  70. {pyocr_toolkit-0.5.0 → pyocr_toolkit-0.6.0}/src/pyocr_toolkit/static/logos/mistralai.svg +0 -0
  71. {pyocr_toolkit-0.5.0 → pyocr_toolkit-0.6.0}/src/pyocr_toolkit/static/logos/paddlepaddle.svg +0 -0
  72. {pyocr_toolkit-0.5.0 → pyocr_toolkit-0.6.0}/src/pyocr_toolkit/static/models.js +0 -0
  73. {pyocr_toolkit-0.5.0 → pyocr_toolkit-0.6.0}/src/pyocr_toolkit/static/providers.js +0 -0
  74. {pyocr_toolkit-0.5.0 → pyocr_toolkit-0.6.0}/src/pyocr_toolkit/static/reader.js +0 -0
  75. {pyocr_toolkit-0.5.0 → pyocr_toolkit-0.6.0}/src/pyocr_toolkit/static/search.js +0 -0
  76. {pyocr_toolkit-0.5.0 → pyocr_toolkit-0.6.0}/src/pyocr_toolkit/static/workspaces.js +0 -0
  77. {pyocr_toolkit-0.5.0 → pyocr_toolkit-0.6.0}/src/pyocr_toolkit/templates/_brand.html +0 -0
  78. {pyocr_toolkit-0.5.0 → pyocr_toolkit-0.6.0}/src/pyocr_toolkit/templates/_doc_card.html +0 -0
  79. {pyocr_toolkit-0.5.0 → pyocr_toolkit-0.6.0}/src/pyocr_toolkit/templates/_doctabs.html +0 -0
  80. {pyocr_toolkit-0.5.0 → pyocr_toolkit-0.6.0}/src/pyocr_toolkit/templates/_icons.html +0 -0
  81. {pyocr_toolkit-0.5.0 → pyocr_toolkit-0.6.0}/src/pyocr_toolkit/templates/base.html +0 -0
  82. {pyocr_toolkit-0.5.0 → pyocr_toolkit-0.6.0}/src/pyocr_toolkit/templates/compare.html +0 -0
  83. {pyocr_toolkit-0.5.0 → pyocr_toolkit-0.6.0}/src/pyocr_toolkit/templates/document.html +0 -0
  84. {pyocr_toolkit-0.5.0 → pyocr_toolkit-0.6.0}/src/pyocr_toolkit/templates/error.html +0 -0
  85. {pyocr_toolkit-0.5.0 → pyocr_toolkit-0.6.0}/src/pyocr_toolkit/templates/home.html +0 -0
  86. {pyocr_toolkit-0.5.0 → pyocr_toolkit-0.6.0}/src/pyocr_toolkit/templates/jobs.html +0 -0
  87. {pyocr_toolkit-0.5.0 → pyocr_toolkit-0.6.0}/src/pyocr_toolkit/templates/library.html +0 -0
  88. {pyocr_toolkit-0.5.0 → pyocr_toolkit-0.6.0}/src/pyocr_toolkit/templates/models.html +0 -0
  89. {pyocr_toolkit-0.5.0 → pyocr_toolkit-0.6.0}/src/pyocr_toolkit/templates/providers.html +0 -0
  90. {pyocr_toolkit-0.5.0 → pyocr_toolkit-0.6.0}/src/pyocr_toolkit/templates/reader.html +0 -0
  91. {pyocr_toolkit-0.5.0 → pyocr_toolkit-0.6.0}/src/pyocr_toolkit/templates/search.html +0 -0
  92. {pyocr_toolkit-0.5.0 → pyocr_toolkit-0.6.0}/src/pyocr_toolkit/templates/workspace_detail.html +0 -0
  93. {pyocr_toolkit-0.5.0 → pyocr_toolkit-0.6.0}/src/pyocr_toolkit/templates/workspaces.html +0 -0
  94. {pyocr_toolkit-0.5.0 → pyocr_toolkit-0.6.0}/src/pyocr_toolkit/web.py +0 -0
  95. {pyocr_toolkit-0.5.0 → pyocr_toolkit-0.6.0}/src/pyocr_toolkit/workspaces.py +0 -0
  96. {pyocr_toolkit-0.5.0 → pyocr_toolkit-0.6.0}/tests/__init__.py +0 -0
  97. {pyocr_toolkit-0.5.0 → pyocr_toolkit-0.6.0}/tests/conftest.py +0 -0
  98. {pyocr_toolkit-0.5.0 → pyocr_toolkit-0.6.0}/tests/test_api.py +0 -0
  99. {pyocr_toolkit-0.5.0 → pyocr_toolkit-0.6.0}/tests/test_batch.py +0 -0
  100. {pyocr_toolkit-0.5.0 → pyocr_toolkit-0.6.0}/tests/test_core.py +0 -0
  101. {pyocr_toolkit-0.5.0 → pyocr_toolkit-0.6.0}/tests/test_makefile.py +0 -0
  102. {pyocr_toolkit-0.5.0 → pyocr_toolkit-0.6.0}/tests/test_models.py +0 -0
  103. {pyocr_toolkit-0.5.0 → pyocr_toolkit-0.6.0}/tests/test_ocr_engines.py +0 -0
  104. {pyocr_toolkit-0.5.0 → pyocr_toolkit-0.6.0}/tests/test_pdftext.py +0 -0
  105. {pyocr_toolkit-0.5.0 → pyocr_toolkit-0.6.0}/tests/test_preprocess.py +0 -0
  106. {pyocr_toolkit-0.5.0 → pyocr_toolkit-0.6.0}/tests/test_web.py +0 -0
  107. {pyocr_toolkit-0.5.0 → pyocr_toolkit-0.6.0}/tests/test_workspaces.py +0 -0
@@ -2,6 +2,39 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ ## 0.6.0 - 2026-11-27
6
+
7
+ - **Structured data extraction**: a new prompt, *Structured data (fields → JSON)*, fills a JSON Schema from each page
8
+ instead of transcribing it. Built-in schemas for invoices, receipts and form fields, or your own JSON Schema
9
+ (checked as you type). Providers enforce the schema natively where they can (Claude structured outputs, OpenAI /
10
+ Azure strict `response_format`, Gemini `response_json_schema`); older Claude models and OpenAI-compatible servers
11
+ get it in the prompt, with a warning. Values are copied as printed, and fields that aren't on the page are `null`.
12
+ The LLM tab shows the result as a field table (fields found, line items, schema problems on their field) with the
13
+ raw JSON one click away. Every reply is parsed and validated against the schema; results store `data`,
14
+ `data_errors`, `fields_filled` and `fields_total` next to the text.
15
+ - **Schema editor**: build your own schema field by field (name, type, hint for the model, required; tables and
16
+ groups nest) without writing JSON Schema, or edit it as JSON in an editor with colours, line numbers and the
17
+ error line marked. *Fix syntax* repairs quotes, unquoted keys, missing or trailing commas, unclosed brackets,
18
+ comments, Python `True`/`None` and type names such as `str` or `bool`. Each edit is checked: mistakes come with
19
+ suggestions ("did you mean 'properties'?"), and a note says whether the chosen provider and model enforce the
20
+ schema or only get it in the prompt. An example output, as the field table or as JSON, shows what a result will
21
+ look like before you pay for a run.
22
+ - **Draft fields from plain words**: describe what to extract ("invoice number, date, every line item with its
23
+ amount") and the chosen model drafts the fields, optionally looking at the current page. The draft opens in the
24
+ field editor for review, and *Change my current fields* refines it step by step ("also add the due date"). One
25
+ paid call per draft (tokens and cost shown), through `LLM_CONCURRENCY`. API: `POST /api/extract/draft-schema`
26
+ (`description`, `provider`, `model`, optional `current_schema`, `doc_id` and `page`; same-origin only).
27
+ - The schema is part of the LLM cache key, so each schema is its own source. Plain transcriptions keep their
28
+ existing keys, so cached results are unaffected.
29
+ - API: `prompt_mode: "extract"` with `extract_schema` (a preset id or a JSON Schema) on
30
+ `POST /api/documents/{id}/pages/{n}/llm` and in job bodies, `POST /api/extract/check-schema` (validation notes,
31
+ example output, syntax error position and a repaired version; takes an optional `provider` and `model`), `extract_presets` in
32
+ `/api/config`, and a per-page `data` object in JSON / JSONL exports of an extraction (one source, and
33
+ *Export all* as `data: {source_id: fields}`). CLI:
34
+ `pyocr extract --mode extract --schema invoice|receipt|form|<file.json>`.
35
+ - The README and website now install from PyPI (`pipx install pyocr-toolkit`) instead of from GitHub.
36
+ - Existing results and cache keys are unchanged.
37
+
5
38
  ## 0.5.0 - 2026-11-27
6
39
 
7
40
  - **More OCR engines.** Besides Tesseract: RapidOCR, EasyOCR, PaddleOCR and docTR (local, optional extras such as
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: pyocr-toolkit
3
- Version: 0.5.0
3
+ Version: 0.6.0
4
4
  Summary: Inspect and compare PDF/image text extraction - native text, OCR engines (Tesseract, EasyOCR, PaddleOCR, docTR, RapidOCR, Google Vision, Azure, Textract, Mistral) 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
@@ -361,19 +361,20 @@ choco install tesseract # Windows (or the UB Man
361
361
  **Option A: pipx** (recommended, installs it as an isolated command):
362
362
 
363
363
  ```bash
364
- pipx install git+https://github.com/utkarsh5026/pyocr
364
+ pipx install pyocr-toolkit
365
365
  ```
366
366
 
367
367
  **Option B: pip** in a virtual environment:
368
368
 
369
369
  ```bash
370
370
  python -m venv .venv && source .venv/bin/activate # Windows: .venv\Scripts\activate
371
- pip install git+https://github.com/utkarsh5026/pyocr
371
+ pip install pyocr-toolkit
372
372
  ```
373
373
 
374
374
  > [!NOTE]
375
- > The PyPI name is `pyocr-toolkit` (plain `pyocr` is a different, unrelated library). Once it's published to
376
- > PyPI, `pipx install pyocr-toolkit` will also work.
375
+ > The PyPI name is `pyocr-toolkit` (plain `pyocr` is a different, unrelated library). Optional extras add more
376
+ > engines, e.g. `pipx install "pyocr-toolkit[pdf,rapidocr]"`. To run the latest unreleased code, install from
377
+ > GitHub instead: `pipx install git+https://github.com/utkarsh5026/pyocr`.
377
378
 
378
379
  **Option C: Docker** (Tesseract and several language packs included):
379
380
 
@@ -485,6 +486,7 @@ pyocr extract born-digital.pdf --engine native # embedded text only
485
486
  pyocr extract born-digital.pdf --engine native:pypdf # the same text layer as pypdf reads it
486
487
  pyocr compare scan.pdf -p openai -m gpt-6.2-sol # per-page OCR / native CER vs an LLM
487
488
  pyocr extract scan.pdf -p anthropic --preprocess 'gray;auto;contrast=1.5' # adjust the image first (or a preset: clean, bw, ...)
489
+ pyocr extract invoice.pdf -p anthropic --mode extract --schema invoice --format json # fields, not text (or a JSON Schema file)
488
490
  pyocr import a.pdf b.pdf scans.zip folder/ -w invoices # add many files as one workspace (zips unpacked)
489
491
  pyocr providers # which providers are ready
490
492
  pyocr engines # which OCR engines are ready
@@ -96,19 +96,20 @@ choco install tesseract # Windows (or the UB Man
96
96
  **Option A: pipx** (recommended, installs it as an isolated command):
97
97
 
98
98
  ```bash
99
- pipx install git+https://github.com/utkarsh5026/pyocr
99
+ pipx install pyocr-toolkit
100
100
  ```
101
101
 
102
102
  **Option B: pip** in a virtual environment:
103
103
 
104
104
  ```bash
105
105
  python -m venv .venv && source .venv/bin/activate # Windows: .venv\Scripts\activate
106
- pip install git+https://github.com/utkarsh5026/pyocr
106
+ pip install pyocr-toolkit
107
107
  ```
108
108
 
109
109
  > [!NOTE]
110
- > The PyPI name is `pyocr-toolkit` (plain `pyocr` is a different, unrelated library). Once it's published to
111
- > PyPI, `pipx install pyocr-toolkit` will also work.
110
+ > The PyPI name is `pyocr-toolkit` (plain `pyocr` is a different, unrelated library). Optional extras add more
111
+ > engines, e.g. `pipx install "pyocr-toolkit[pdf,rapidocr]"`. To run the latest unreleased code, install from
112
+ > GitHub instead: `pipx install git+https://github.com/utkarsh5026/pyocr`.
112
113
 
113
114
  **Option C: Docker** (Tesseract and several language packs included):
114
115
 
@@ -220,6 +221,7 @@ pyocr extract born-digital.pdf --engine native # embedded text only
220
221
  pyocr extract born-digital.pdf --engine native:pypdf # the same text layer as pypdf reads it
221
222
  pyocr compare scan.pdf -p openai -m gpt-6.2-sol # per-page OCR / native CER vs an LLM
222
223
  pyocr extract scan.pdf -p anthropic --preprocess 'gray;auto;contrast=1.5' # adjust the image first (or a preset: clean, bw, ...)
224
+ pyocr extract invoice.pdf -p anthropic --mode extract --schema invoice --format json # fields, not text (or a JSON Schema file)
223
225
  pyocr import a.pdf b.pdf scans.zip folder/ -w invoices # add many files as one workspace (zips unpacked)
224
226
  pyocr providers # which providers are ready
225
227
  pyocr engines # which OCR engines are ready
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "pyocr-toolkit"
3
- version = "0.5.0"
3
+ version = "0.6.0"
4
4
  description = "Inspect and compare PDF/image text extraction - native text, OCR engines (Tesseract, EasyOCR, PaddleOCR, docTR, RapidOCR, Google Vision, Azure, Textract, Mistral) and LLMs (Claude, GPT, Gemini, Azure, local) - in your browser."
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.10"
@@ -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.5.0"
3
+ __version__ = "0.6.0"
@@ -6,6 +6,7 @@ http://127.0.0.1:8000. Interactive API docs live at ``/docs``.
6
6
 
7
7
  from __future__ import annotations
8
8
 
9
+ import json
9
10
  import re
10
11
  import shutil
11
12
  from dataclasses import asdict
@@ -20,7 +21,7 @@ from fastapi.responses import FileResponse, JSONResponse, Response
20
21
  from fastapi.staticfiles import StaticFiles
21
22
  from pydantic import BaseModel, Field
22
23
 
23
- from . import __version__, compare, export, search
24
+ from . import __version__, compare, export, extract, search
24
25
  from .brands import brands_json
25
26
  from .config import Settings, get_settings
26
27
  from .documents import DEFAULT_OCR_ENGINE, DocumentError, DocumentStore, OCRUnavailableError, OpenDocument
@@ -44,11 +45,32 @@ class LLMRunBody(BaseModel):
44
45
  preprocess: str | None = Field(None, description="image preprocessing, e.g. 'gray;contrast=1.5' or a preset id")
45
46
  pages_per_request: int = Field(1, ge=1, le=MAX_PAGES_PER_REQUEST,
46
47
  description="pages sent together in one LLM request (1 = one page per request)")
48
+ extract_schema: str | dict | None = Field(
49
+ None, description="for prompt_mode 'extract': a preset id ('invoice', 'receipt', 'form') or a JSON Schema")
47
50
  force: bool = False
48
51
 
49
52
  def spec(self) -> LLMSpec:
53
+ schema = self.extract_schema
54
+ if isinstance(schema, dict):
55
+ schema = json.dumps(schema, ensure_ascii=False)
50
56
  return LLMSpec(self.provider, self.model, self.prompt_mode, self.custom_prompt,
51
- preprocess=self.preprocess or "", pages_per_request=self.pages_per_request)
57
+ preprocess=self.preprocess or "", pages_per_request=self.pages_per_request,
58
+ extract_schema=schema or "")
59
+
60
+
61
+ class DraftSchemaBody(BaseModel):
62
+ description: str = Field(..., max_length=4000, description="what to extract, in plain words")
63
+ provider: str
64
+ model: str | None = None
65
+ current_schema: str | None = Field(None, max_length=50_000, description="change this schema instead of starting over")
66
+ doc_id: str | None = Field(None, description="show the model a page of this document")
67
+ page: int = Field(0, ge=0, description="0-based page of doc_id")
68
+
69
+
70
+ class SchemaCheckBody(BaseModel):
71
+ extract_schema: str | dict
72
+ provider: str | None = Field(None, description="add a note on how this provider/model handles the schema")
73
+ model: str | None = None
52
74
 
53
75
 
54
76
  class TextRef(BaseModel):
@@ -178,6 +200,7 @@ def build_api(settings: Settings, store: DocumentStore, services: Services, jobs
178
200
  "llm_max_edge_px": settings.llm_max_edge_px,
179
201
  "ocr_dpi": settings.ocr_dpi,
180
202
  "preprocess_presets": presets_json(),
203
+ "extract_presets": extract.presets_json(),
181
204
  }
182
205
 
183
206
  @api.get("/models", tags=["models"])
@@ -347,6 +370,44 @@ def build_api(settings: Settings, store: DocumentStore, services: Services, jobs
347
370
  """Validate and normalise a preprocessing spec (400 with a readable message if it's wrong)."""
348
371
  return parse_pre(spec).to_json()
349
372
 
373
+ @api.post("/extract/check-schema", tags=["llm"])
374
+ def check_schema(body: SchemaCheckBody):
375
+ """Check a structured-extraction schema as it's being written (always 200; see ``ok``).
376
+
377
+ Returns the normalized schema, an ``example`` of the output, ``notes``
378
+ (mistakes with suggestions, what the chosen provider does with the schema),
379
+ and for broken JSON the ``line``/``column`` plus a ``repaired`` version.
380
+ """
381
+ return checked_schema(body.extract_schema, body.provider, body.model)
382
+
383
+ def checked_schema(spec: str | dict, provider_id: str | None, model: str | None) -> dict:
384
+ result = extract.check(spec)
385
+ provider = providers.get(provider_id or "")
386
+ if provider is not None and result["ok"]:
387
+ level, message = provider.schema_support((model or provider.default_model or "").strip() or None)
388
+ result["notes"].insert(0, {"level": level, "path": "(provider)", "message": message})
389
+ return result
390
+
391
+ @api.post("/extract/draft-schema", tags=["llm"])
392
+ async def draft_schema(body: DraftSchemaBody, request: Request):
393
+ """Draft extraction fields from a plain-words description (a paid model call; not cached).
394
+
395
+ Returns the drafted JSON Schema, the model's ``notes``, tokens and cost, and
396
+ the same ``check`` the schema editor shows. Nothing is extracted until the
397
+ user runs the schema on pages.
398
+ """
399
+ _require_same_origin(request) # it spends money: no cross-site triggering
400
+ doc = get_doc(body.doc_id) if body.doc_id else None
401
+ if doc is not None and body.page >= doc.meta.page_count:
402
+ raise DocumentError(f"page {body.page} out of range")
403
+ try:
404
+ draft = await services.draft_schema(body.provider, body.model, body.description, body.current_schema,
405
+ doc, body.page)
406
+ except ValueError as exc:
407
+ raise HTTPException(400, str(exc)) from exc
408
+ draft["check"] = checked_schema(draft["schema"], body.provider, body.model)
409
+ return draft
410
+
350
411
  @api.get("/documents/{doc_id}/sources", tags=["text"])
351
412
  def sources(doc_id: str):
352
413
  """Text sources available for the document (native, OCR, each LLM config) with page coverage."""
@@ -641,7 +702,8 @@ def build_api(settings: Settings, store: DocumentStore, services: Services, jobs
641
702
  source = f"llm:{key}"
642
703
  texts = [services.page_text(doc, n, source) for n in doc.iter_pages()]
643
704
  name = f"{_safe_stem(doc.meta.filename)}.{export.file_tag(source)}.{fmt}"
644
- body = export.one_source(doc.meta.__dict__, source, services.source_label(doc, source), texts, fmt)
705
+ data = [services.page_data(doc, n, source) for n in doc.iter_pages()] # structured extraction's fields
706
+ body = export.one_source(doc.meta.__dict__, source, services.source_label(doc, source), texts, fmt, data)
645
707
  return Response(body, media_type=export.MEDIA_TYPES[fmt],
646
708
  headers={"Content-Disposition": f'attachment; filename="{name}"'})
647
709
 
@@ -217,6 +217,7 @@ async def _extract(args: argparse.Namespace) -> int:
217
217
  doc = _load_document(args.file)
218
218
  pages = parse_pages(args.pages, doc.meta.page_count)
219
219
  texts: dict[int, str] = {}
220
+ data: dict[int, object] = {} # structured extraction (--mode extract): parsed fields per page
220
221
  if args.engine == "native" or args.engine.startswith("native:"):
221
222
  library = args.engine[7:] or None if args.engine.startswith("native:") else None
222
223
  lib = services.text_library(library)
@@ -235,11 +236,17 @@ async def _extract(args: argparse.Namespace) -> int:
235
236
  print(f" {engine.label} page {n + 1}/{doc.meta.page_count}: {(layer.elapsed_ms or 0) / 1000:.1f}s",
236
237
  file=sys.stderr)
237
238
  else:
239
+ schema = args.schema or ""
240
+ if args.mode == "extract" and schema and not schema.lstrip().startswith("{") and Path(schema).is_file():
241
+ schema = Path(schema).read_text(encoding="utf-8")
242
+ elif args.mode != "extract" and schema:
243
+ print("--schema only applies with --mode extract", file=sys.stderr)
244
+ return 2
238
245
  spec = LLMSpec(args.provider, args.model, args.mode, preprocess=args.preprocess or "",
239
- pages_per_request=args.pages_per_request)
246
+ pages_per_request=args.pages_per_request, extract_schema=schema)
240
247
  try:
241
248
  provider, model, _ = services.resolve_spec(spec)
242
- except ValueError as exc: # bad --pages-per-request or --preprocess
249
+ except ValueError as exc: # bad --pages-per-request, --preprocess or --schema
243
250
  print(str(exc), file=sys.stderr)
244
251
  return 2
245
252
  if not provider.configured:
@@ -252,19 +259,26 @@ async def _extract(args: argparse.Namespace) -> int:
252
259
  continue
253
260
  note = "cached" if res["cached"] else f"{res['latency_ms'] / 1000:.1f}s"
254
261
  print(f" LLM page {n + 1}: {note}" + "".join(f" ⚠ {w}" for w in res["warnings"]), file=sys.stderr)
262
+ for e in res.get("data_errors") or []:
263
+ print(f" ⚠ {e['path']}: {e['message']}", file=sys.stderr)
255
264
  texts[n] = res["text"]
265
+ if "data" in res:
266
+ data[n] = res["data"]
256
267
 
257
268
  ordered = [(n, texts.get(n, "")) for n in pages]
258
269
  from .service import ocr_source_id
259
270
 
260
271
  source = (f"llm:{args.provider}" if args.engine == "llm" else
261
272
  ocr_source_id(_ocr_engine_arg(args)) if args.engine.startswith("ocr") else args.engine)
273
+ extra = (lambda n: {"data": data.get(n)}) if data else (lambda n: {})
262
274
  if args.format == "jsonl":
263
275
  out = "".join(json.dumps({"document_id": doc.meta.id, "filename": doc.meta.filename, "page": n + 1,
264
- "source": source, "text": t}, ensure_ascii=False) + "\n" for n, t in ordered)
276
+ "source": source, "text": t, **extra(n)}, ensure_ascii=False) + "\n"
277
+ for n, t in ordered)
265
278
  elif args.format == "json":
266
279
  out = json.dumps({"document": doc.meta.__dict__, "source": source,
267
- "pages": [{"page": n + 1, "text": t} for n, t in ordered]}, ensure_ascii=False, indent=1)
280
+ "pages": [{"page": n + 1, "text": t, **extra(n)} for n, t in ordered]},
281
+ ensure_ascii=False, indent=1)
268
282
  elif args.format == "md":
269
283
  out = f"# {doc.meta.filename}\n" + "".join(f"\n## Page {n + 1}\n\n{t.strip()}\n" for n, t in ordered)
270
284
  else:
@@ -347,7 +361,10 @@ def build_parser() -> argparse.ArgumentParser:
347
361
  e.add_argument("--ocr-engine", default="tesseract", help="for --engine ocr; see `pyocr engines`")
348
362
  e.add_argument("-p", "--provider", default="anthropic", help="for --engine llm")
349
363
  e.add_argument("-m", "--model", default=None)
350
- e.add_argument("--mode", default="verbatim", choices=["verbatim", "markdown"], help="LLM prompt")
364
+ e.add_argument("--mode", default="verbatim", choices=["verbatim", "markdown", "extract"],
365
+ help="LLM prompt; 'extract' fills --schema with structured data (JSON) instead of transcribing")
366
+ e.add_argument("--schema", default=None, metavar="SCHEMA",
367
+ help="for --mode extract: a preset (invoice, receipt, form), a JSON Schema file, or JSON text")
351
368
  e.add_argument("--pages-per-request", type=int, default=1, metavar="N",
352
369
  help="send N pages to the LLM in one request (default 1); a separate source from N=1")
353
370
  e.add_argument("--pages", default=None, help="1-based ranges, e.g. 1-3,7 (default: all)")
@@ -298,14 +298,16 @@ class OpenDocument:
298
298
  return self.folder / "llm" / str(number)
299
299
 
300
300
  @staticmethod
301
- def llm_cache_key(provider: str, model: str, prompt: str, preprocess: str = "") -> str:
301
+ def llm_cache_key(provider: str, model: str, prompt: str, preprocess: str = "", schema: str = "") -> str:
302
302
  """Stable id of one LLM configuration, identical on every page of a document.
303
303
 
304
- ``preprocess`` is the canonical image-preprocessing spec. It is only mixed
305
- into the digest when non-empty, so runs on the plain page image keep the
306
- keys they had before preprocessing existed (no orphaned caches).
304
+ ``preprocess`` is the canonical image-preprocessing spec and ``schema`` the
305
+ canonical JSON of a structured-extraction schema. Each is only mixed into the
306
+ digest when non-empty, so plain transcriptions keep the keys they had before
307
+ those features existed (no orphaned caches).
307
308
  """
308
- material = f"{provider}\0{model}\0{prompt}" + (f"\0{preprocess}" if preprocess else "")
309
+ material = (f"{provider}\0{model}\0{prompt}" + (f"\0{preprocess}" if preprocess else "")
310
+ + (f"\0schema={schema}" if schema else ""))
309
311
  digest = hashlib.sha256(material.encode()).hexdigest()[:16]
310
312
  safe_model = re.sub(r"[^A-Za-z0-9._-]+", "_", model)[:60]
311
313
  return f"{provider}__{safe_model}__{digest}"
@@ -30,7 +30,7 @@ MEDIA_TYPES = {"txt": "text/plain; charset=utf-8", "md": "text/markdown; charset
30
30
  "csv": "text/csv; charset=utf-8", "zip": "application/zip"}
31
31
 
32
32
  # Source fields worth keeping in an export; the rest (page lists, timestamps) is UI bookkeeping.
33
- _SOURCE_FIELDS = ("id", "kind", "label", "engine", "provider", "model", "prompt_mode", "preprocess",
33
+ _SOURCE_FIELDS = ("id", "kind", "label", "engine", "provider", "model", "prompt_mode", "schema_label", "preprocess",
34
34
  "pages_per_request", "page_count", "input_tokens", "output_tokens")
35
35
 
36
36
 
@@ -40,6 +40,8 @@ class SourceTexts:
40
40
 
41
41
  source: dict[str, Any]
42
42
  texts: list[str | None]
43
+ #: structured extraction: the parsed fields per page (``None`` for other sources)
44
+ data: list[Any] | None = None
43
45
 
44
46
  @property
45
47
  def id(self) -> str:
@@ -66,14 +68,21 @@ def file_tag(source: str) -> str:
66
68
 
67
69
 
68
70
  # --------------------------------------------------------------- one source
69
- def one_source(doc_meta: dict[str, Any], source: str, label: str, texts: list[str | None], fmt: str) -> str:
71
+ def _with_data(data: list[Any] | None, i: int) -> dict[str, Any]:
72
+ """``{"data": ...}`` for a structured-extraction source (JSON / JSONL exports), else nothing."""
73
+ return {"data": data[i]} if data and any(d is not None for d in data) else {}
74
+
75
+
76
+ def one_source(doc_meta: dict[str, Any], source: str, label: str, texts: list[str | None], fmt: str,
77
+ data: list[Any] | None = None) -> str:
78
+ """``data``: structured extraction's parsed fields per page; JSON and JSONL add them as ``data``."""
70
79
  if fmt == "json":
71
80
  return json.dumps({"document": doc_meta, "source": source, "source_label": label,
72
- "pages": [{"page": i + 1, "text": t, "extracted": t is not None}
81
+ "pages": [{"page": i + 1, "text": t, "extracted": t is not None, **_with_data(data, i)}
73
82
  for i, t in enumerate(texts)]}, ensure_ascii=False)
74
83
  if fmt == "jsonl":
75
84
  return "".join(json.dumps({"document_id": doc_meta["id"], "filename": doc_meta["filename"], "page": i + 1,
76
- "source": source, "text": t or ""}, ensure_ascii=False) + "\n"
85
+ "source": source, "text": t or "", **_with_data(data, i)}, ensure_ascii=False) + "\n"
77
86
  for i, t in enumerate(texts))
78
87
  if fmt == "md":
79
88
  body = f"# {doc_meta['filename']}\n\n_Source: {label}_\n" + "".join(
@@ -88,13 +97,18 @@ def _source_info(s: SourceTexts) -> dict[str, Any]:
88
97
 
89
98
 
90
99
  def all_json(data: DocumentTexts) -> str:
91
- """``{document, sources: [...], pages: [{page, texts: {source_id: text | null}}]}``."""
100
+ """``{document, sources: [...], pages: [{page, texts: {source_id: text | null}}]}``.
101
+
102
+ Structured-extraction sources also get ``data: {source_id: fields | null}`` per page.
103
+ """
104
+ structured = [s for s in data.sources if s.data is not None]
92
105
  return json.dumps({
93
106
  "pyocr_version": __version__,
94
107
  "exported_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
95
108
  "document": data.document,
96
109
  "sources": [_source_info(s) for s in data.sources],
97
- "pages": [{"page": n + 1, "texts": {s.id: s.texts[n] for s in data.sources}}
110
+ "pages": [{"page": n + 1, "texts": {s.id: s.texts[n] for s in data.sources},
111
+ **({"data": {s.id: s.data[n] for s in structured}} if structured else {})}
98
112
  for n in range(data.page_count)],
99
113
  }, ensure_ascii=False, indent=2)
100
114
 
@@ -103,7 +117,7 @@ def all_jsonl(data: DocumentTexts) -> str:
103
117
  """One line per extracted (page, source) pair; pages a source never extracted are left out."""
104
118
  return "".join(
105
119
  json.dumps({"document_id": data.document["id"], "filename": data.document["filename"], "page": n + 1,
106
- "source": s.id, "source_label": s.label, "text": t}, ensure_ascii=False) + "\n"
120
+ "source": s.id, "source_label": s.label, "text": t, **_with_data(s.data, n)}, ensure_ascii=False) + "\n"
107
121
  for n in range(data.page_count) for s in data.sources if (t := s.texts[n]) is not None)
108
122
 
109
123