pyocr-toolkit 0.6.0__tar.gz → 0.7.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 (116) hide show
  1. {pyocr_toolkit-0.6.0 → pyocr_toolkit-0.7.0}/CHANGELOG.md +72 -0
  2. {pyocr_toolkit-0.6.0 → pyocr_toolkit-0.7.0}/PKG-INFO +9 -5
  3. {pyocr_toolkit-0.6.0 → pyocr_toolkit-0.7.0}/README.md +8 -4
  4. {pyocr_toolkit-0.6.0 → pyocr_toolkit-0.7.0}/pyproject.toml +1 -1
  5. {pyocr_toolkit-0.6.0 → pyocr_toolkit-0.7.0}/src/pyocr_toolkit/__init__.py +1 -1
  6. {pyocr_toolkit-0.6.0 → pyocr_toolkit-0.7.0}/src/pyocr_toolkit/api.py +209 -4
  7. {pyocr_toolkit-0.6.0 → pyocr_toolkit-0.7.0}/src/pyocr_toolkit/cli.py +8 -4
  8. pyocr_toolkit-0.7.0/src/pyocr_toolkit/compare.py +656 -0
  9. {pyocr_toolkit-0.6.0 → pyocr_toolkit-0.7.0}/src/pyocr_toolkit/documents.py +162 -20
  10. {pyocr_toolkit-0.6.0 → pyocr_toolkit-0.7.0}/src/pyocr_toolkit/service.py +154 -2
  11. {pyocr_toolkit-0.6.0 → pyocr_toolkit-0.7.0}/src/pyocr_toolkit/static/common.js +163 -0
  12. pyocr_toolkit-0.7.0/src/pyocr_toolkit/static/compare.js +651 -0
  13. {pyocr_toolkit-0.6.0 → pyocr_toolkit-0.7.0}/src/pyocr_toolkit/static/document.js +77 -7
  14. pyocr_toolkit-0.7.0/src/pyocr_toolkit/static/leaderboard.js +137 -0
  15. {pyocr_toolkit-0.6.0 → pyocr_toolkit-0.7.0}/src/pyocr_toolkit/static/styles.css +313 -13
  16. {pyocr_toolkit-0.6.0 → pyocr_toolkit-0.7.0}/src/pyocr_toolkit/static/workspace.js +44 -12
  17. pyocr_toolkit-0.7.0/src/pyocr_toolkit/templates/_doctabs.html +17 -0
  18. pyocr_toolkit-0.7.0/src/pyocr_toolkit/templates/_section_tabs.html +14 -0
  19. {pyocr_toolkit-0.6.0 → pyocr_toolkit-0.7.0}/src/pyocr_toolkit/templates/base.html +12 -14
  20. pyocr_toolkit-0.7.0/src/pyocr_toolkit/templates/compare.html +162 -0
  21. pyocr_toolkit-0.7.0/src/pyocr_toolkit/templates/document.html +141 -0
  22. {pyocr_toolkit-0.6.0 → pyocr_toolkit-0.7.0}/src/pyocr_toolkit/templates/help.html +111 -12
  23. pyocr_toolkit-0.7.0/src/pyocr_toolkit/templates/home.html +69 -0
  24. pyocr_toolkit-0.7.0/src/pyocr_toolkit/templates/leaderboard.html +73 -0
  25. {pyocr_toolkit-0.6.0 → pyocr_toolkit-0.7.0}/src/pyocr_toolkit/templates/workspace.html +32 -14
  26. {pyocr_toolkit-0.6.0 → pyocr_toolkit-0.7.0}/src/pyocr_toolkit/templates/workspace_detail.html +1 -0
  27. {pyocr_toolkit-0.6.0 → pyocr_toolkit-0.7.0}/src/pyocr_toolkit/web.py +6 -7
  28. pyocr_toolkit-0.7.0/tests/test_api.py +281 -0
  29. pyocr_toolkit-0.7.0/tests/test_core.py +307 -0
  30. {pyocr_toolkit-0.6.0 → pyocr_toolkit-0.7.0}/tests/test_web.py +21 -2
  31. pyocr_toolkit-0.6.0/src/pyocr_toolkit/compare.py +0 -142
  32. pyocr_toolkit-0.6.0/src/pyocr_toolkit/static/compare.js +0 -160
  33. pyocr_toolkit-0.6.0/src/pyocr_toolkit/templates/_doctabs.html +0 -14
  34. pyocr_toolkit-0.6.0/src/pyocr_toolkit/templates/compare.html +0 -84
  35. pyocr_toolkit-0.6.0/src/pyocr_toolkit/templates/document.html +0 -138
  36. pyocr_toolkit-0.6.0/src/pyocr_toolkit/templates/home.html +0 -91
  37. pyocr_toolkit-0.6.0/tests/test_api.py +0 -124
  38. pyocr_toolkit-0.6.0/tests/test_core.py +0 -129
  39. {pyocr_toolkit-0.6.0 → pyocr_toolkit-0.7.0}/.env.example +0 -0
  40. {pyocr_toolkit-0.6.0 → pyocr_toolkit-0.7.0}/.gitignore +0 -0
  41. {pyocr_toolkit-0.6.0 → pyocr_toolkit-0.7.0}/CONTRIBUTING.md +0 -0
  42. {pyocr_toolkit-0.6.0 → pyocr_toolkit-0.7.0}/LICENSE +0 -0
  43. {pyocr_toolkit-0.6.0 → pyocr_toolkit-0.7.0}/hero-video/README.md +0 -0
  44. {pyocr_toolkit-0.6.0 → pyocr_toolkit-0.7.0}/hero-video/src/HeroDemo.tsx +0 -0
  45. {pyocr_toolkit-0.6.0 → pyocr_toolkit-0.7.0}/hero-video/src/Root.tsx +0 -0
  46. {pyocr_toolkit-0.6.0 → pyocr_toolkit-0.7.0}/hero-video/src/assets.d.ts +0 -0
  47. {pyocr_toolkit-0.6.0 → pyocr_toolkit-0.7.0}/hero-video/src/index.ts +0 -0
  48. {pyocr_toolkit-0.6.0 → pyocr_toolkit-0.7.0}/hero-video/src/motion.tsx +0 -0
  49. {pyocr_toolkit-0.6.0 → pyocr_toolkit-0.7.0}/hero-video/src/scenes/CatchScene.tsx +0 -0
  50. {pyocr_toolkit-0.6.0 → pyocr_toolkit-0.7.0}/hero-video/src/scenes/ColdOpenScene.tsx +0 -0
  51. {pyocr_toolkit-0.6.0 → pyocr_toolkit-0.7.0}/hero-video/src/scenes/MeasureScene.tsx +0 -0
  52. {pyocr_toolkit-0.6.0 → pyocr_toolkit-0.7.0}/hero-video/src/scenes/MontageScene.tsx +0 -0
  53. {pyocr_toolkit-0.6.0 → pyocr_toolkit-0.7.0}/hero-video/src/scenes/OutroScene.tsx +0 -0
  54. {pyocr_toolkit-0.6.0 → pyocr_toolkit-0.7.0}/hero-video/src/scenes/ThreeWaysScene.tsx +0 -0
  55. {pyocr_toolkit-0.6.0 → pyocr_toolkit-0.7.0}/hero-video/src/theme.ts +0 -0
  56. {pyocr_toolkit-0.6.0 → pyocr_toolkit-0.7.0}/hero-video/src/ui.tsx +0 -0
  57. {pyocr_toolkit-0.6.0 → pyocr_toolkit-0.7.0}/src/pyocr_toolkit/__main__.py +0 -0
  58. {pyocr_toolkit-0.6.0 → pyocr_toolkit-0.7.0}/src/pyocr_toolkit/brands.py +0 -0
  59. {pyocr_toolkit-0.6.0 → pyocr_toolkit-0.7.0}/src/pyocr_toolkit/config.py +0 -0
  60. {pyocr_toolkit-0.6.0 → pyocr_toolkit-0.7.0}/src/pyocr_toolkit/credentials.py +0 -0
  61. {pyocr_toolkit-0.6.0 → pyocr_toolkit-0.7.0}/src/pyocr_toolkit/env.example +0 -0
  62. {pyocr_toolkit-0.6.0 → pyocr_toolkit-0.7.0}/src/pyocr_toolkit/export.py +0 -0
  63. {pyocr_toolkit-0.6.0 → pyocr_toolkit-0.7.0}/src/pyocr_toolkit/extract.py +0 -0
  64. {pyocr_toolkit-0.6.0 → pyocr_toolkit-0.7.0}/src/pyocr_toolkit/jobs.py +0 -0
  65. {pyocr_toolkit-0.6.0 → pyocr_toolkit-0.7.0}/src/pyocr_toolkit/llm/__init__.py +0 -0
  66. {pyocr_toolkit-0.6.0 → pyocr_toolkit-0.7.0}/src/pyocr_toolkit/llm/anthropic_provider.py +0 -0
  67. {pyocr_toolkit-0.6.0 → pyocr_toolkit-0.7.0}/src/pyocr_toolkit/llm/base.py +0 -0
  68. {pyocr_toolkit-0.6.0 → pyocr_toolkit-0.7.0}/src/pyocr_toolkit/llm/catalog.py +0 -0
  69. {pyocr_toolkit-0.6.0 → pyocr_toolkit-0.7.0}/src/pyocr_toolkit/llm/gemini_provider.py +0 -0
  70. {pyocr_toolkit-0.6.0 → pyocr_toolkit-0.7.0}/src/pyocr_toolkit/llm/openai_provider.py +0 -0
  71. {pyocr_toolkit-0.6.0 → pyocr_toolkit-0.7.0}/src/pyocr_toolkit/llm/prompts.py +0 -0
  72. {pyocr_toolkit-0.6.0 → pyocr_toolkit-0.7.0}/src/pyocr_toolkit/ocr/__init__.py +0 -0
  73. {pyocr_toolkit-0.6.0 → pyocr_toolkit-0.7.0}/src/pyocr_toolkit/ocr/base.py +0 -0
  74. {pyocr_toolkit-0.6.0 → pyocr_toolkit-0.7.0}/src/pyocr_toolkit/ocr/cloud.py +0 -0
  75. {pyocr_toolkit-0.6.0 → pyocr_toolkit-0.7.0}/src/pyocr_toolkit/ocr/local.py +0 -0
  76. {pyocr_toolkit-0.6.0 → pyocr_toolkit-0.7.0}/src/pyocr_toolkit/ocr/tesseract.py +0 -0
  77. {pyocr_toolkit-0.6.0 → pyocr_toolkit-0.7.0}/src/pyocr_toolkit/pdftext.py +0 -0
  78. {pyocr_toolkit-0.6.0 → pyocr_toolkit-0.7.0}/src/pyocr_toolkit/preprocess.py +0 -0
  79. {pyocr_toolkit-0.6.0 → pyocr_toolkit-0.7.0}/src/pyocr_toolkit/search.py +0 -0
  80. {pyocr_toolkit-0.6.0 → pyocr_toolkit-0.7.0}/src/pyocr_toolkit/static/jobs.js +0 -0
  81. {pyocr_toolkit-0.6.0 → pyocr_toolkit-0.7.0}/src/pyocr_toolkit/static/library.js +0 -0
  82. {pyocr_toolkit-0.6.0 → pyocr_toolkit-0.7.0}/src/pyocr_toolkit/static/logos/README.md +0 -0
  83. {pyocr_toolkit-0.6.0 → pyocr_toolkit-0.7.0}/src/pyocr_toolkit/static/logos/claude.svg +0 -0
  84. {pyocr_toolkit-0.6.0 → pyocr_toolkit-0.7.0}/src/pyocr_toolkit/static/logos/googlecloud.svg +0 -0
  85. {pyocr_toolkit-0.6.0 → pyocr_toolkit-0.7.0}/src/pyocr_toolkit/static/logos/googlegemini.svg +0 -0
  86. {pyocr_toolkit-0.6.0 → pyocr_toolkit-0.7.0}/src/pyocr_toolkit/static/logos/mistralai.svg +0 -0
  87. {pyocr_toolkit-0.6.0 → pyocr_toolkit-0.7.0}/src/pyocr_toolkit/static/logos/paddlepaddle.svg +0 -0
  88. {pyocr_toolkit-0.6.0 → pyocr_toolkit-0.7.0}/src/pyocr_toolkit/static/models.js +0 -0
  89. {pyocr_toolkit-0.6.0 → pyocr_toolkit-0.7.0}/src/pyocr_toolkit/static/providers.js +0 -0
  90. {pyocr_toolkit-0.6.0 → pyocr_toolkit-0.7.0}/src/pyocr_toolkit/static/reader.js +0 -0
  91. {pyocr_toolkit-0.6.0 → pyocr_toolkit-0.7.0}/src/pyocr_toolkit/static/search.js +0 -0
  92. {pyocr_toolkit-0.6.0 → pyocr_toolkit-0.7.0}/src/pyocr_toolkit/static/workspaces.js +0 -0
  93. {pyocr_toolkit-0.6.0 → pyocr_toolkit-0.7.0}/src/pyocr_toolkit/templates/_brand.html +0 -0
  94. {pyocr_toolkit-0.6.0 → pyocr_toolkit-0.7.0}/src/pyocr_toolkit/templates/_doc_card.html +0 -0
  95. {pyocr_toolkit-0.6.0 → pyocr_toolkit-0.7.0}/src/pyocr_toolkit/templates/_icons.html +0 -0
  96. {pyocr_toolkit-0.6.0 → pyocr_toolkit-0.7.0}/src/pyocr_toolkit/templates/_llm_picker.html +0 -0
  97. {pyocr_toolkit-0.6.0 → pyocr_toolkit-0.7.0}/src/pyocr_toolkit/templates/error.html +0 -0
  98. {pyocr_toolkit-0.6.0 → pyocr_toolkit-0.7.0}/src/pyocr_toolkit/templates/jobs.html +0 -0
  99. {pyocr_toolkit-0.6.0 → pyocr_toolkit-0.7.0}/src/pyocr_toolkit/templates/library.html +0 -0
  100. {pyocr_toolkit-0.6.0 → pyocr_toolkit-0.7.0}/src/pyocr_toolkit/templates/models.html +0 -0
  101. {pyocr_toolkit-0.6.0 → pyocr_toolkit-0.7.0}/src/pyocr_toolkit/templates/providers.html +0 -0
  102. {pyocr_toolkit-0.6.0 → pyocr_toolkit-0.7.0}/src/pyocr_toolkit/templates/reader.html +0 -0
  103. {pyocr_toolkit-0.6.0 → pyocr_toolkit-0.7.0}/src/pyocr_toolkit/templates/search.html +0 -0
  104. {pyocr_toolkit-0.6.0 → pyocr_toolkit-0.7.0}/src/pyocr_toolkit/templates/workspaces.html +0 -0
  105. {pyocr_toolkit-0.6.0 → pyocr_toolkit-0.7.0}/src/pyocr_toolkit/workspaces.py +0 -0
  106. {pyocr_toolkit-0.6.0 → pyocr_toolkit-0.7.0}/tests/__init__.py +0 -0
  107. {pyocr_toolkit-0.6.0 → pyocr_toolkit-0.7.0}/tests/conftest.py +0 -0
  108. {pyocr_toolkit-0.6.0 → pyocr_toolkit-0.7.0}/tests/test_batch.py +0 -0
  109. {pyocr_toolkit-0.6.0 → pyocr_toolkit-0.7.0}/tests/test_extract.py +0 -0
  110. {pyocr_toolkit-0.6.0 → pyocr_toolkit-0.7.0}/tests/test_makefile.py +0 -0
  111. {pyocr_toolkit-0.6.0 → pyocr_toolkit-0.7.0}/tests/test_models.py +0 -0
  112. {pyocr_toolkit-0.6.0 → pyocr_toolkit-0.7.0}/tests/test_ocr_engines.py +0 -0
  113. {pyocr_toolkit-0.6.0 → pyocr_toolkit-0.7.0}/tests/test_pdftext.py +0 -0
  114. {pyocr_toolkit-0.6.0 → pyocr_toolkit-0.7.0}/tests/test_preprocess.py +0 -0
  115. {pyocr_toolkit-0.6.0 → pyocr_toolkit-0.7.0}/tests/test_providers.py +0 -0
  116. {pyocr_toolkit-0.6.0 → pyocr_toolkit-0.7.0}/tests/test_workspaces.py +0 -0
@@ -2,6 +2,78 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ ## 0.7.0 - 2026-11-28
6
+
7
+ - **Calmer interface, same features.** The top bar has three sections, *Documents* (Workspaces / All files / Leaderboard),
8
+ *Search* and *Settings* (Providers / Models), plus a *Jobs* pill that shows how many extractions are running.
9
+ **Ctrl+K / ⌘K** opens a command palette on every page: jump to any page or document by name, run the current
10
+ document's actions (extract, compare, every export) or search all documents' text. Inside a document, the
11
+ breadcrumb, the view tabs and a new **Extract** button share one row.
12
+ - *Overview*: sources are a simple list (coverage, Read, an export menu); only running or failed jobs are shown;
13
+ the original file, metadata and Delete move to the bottom. Extraction opens in a side panel (the Extract
14
+ button, `x`, or `#extract` in the URL) with engine, model and pages up front and image preprocessing, pages
15
+ per request and re-run under *More options*, whose summary line shows their current values.
16
+ - *Pages* (the page inspector): sources (Native / OCR / LLM) on the left of the text panel and the two views,
17
+ *Diff* and *Columns* (was *Side by side*), on the right; page and zoom controls float over the page image.
18
+ The LLM tab folds provider, model, prompt and image into one line ("Model: demo-vision · Verbatim Change"),
19
+ which opens by itself when the chosen provider isn't configured; Re-run and Delete move to a ⋯ menu, and the
20
+ stored-result picker shows only when the page has more than one result.
21
+ - Fixed: re-running an LLM transcription in the inspector no longer counts it twice in the page list.
22
+ - *Home* and *Compare* drop the explainer text and stat tiles; Compare's case/punctuation options move to an
23
+ Options menu.
24
+
25
+ - **Compare explains its numbers.** A single CER can't tell a dropped umlaut from a wrong invoice total or an invented
26
+ sentence, so the Compare page now also shows:
27
+ - word errors split into **misread / missed / added** (they add up to the word edit distance behind WER), for the
28
+ whole document and per page;
29
+ - **numbers read exactly**: every token with a digit (amounts, dates, IDs) checked on its own, with the wrong ones
30
+ listed (`2,530.54 → 2.530,54`);
31
+ - each page's errors **by kind** (numbers, misread words, accents / ß, case, punctuation, split or joined words,
32
+ missed, added, stray scan marks) and the most common **character confusions** (`0→O`, `m→rn`);
33
+ - **CER as differences are forgiven**: the page's CER with case, punctuation and accents ignored and added text
34
+ dropped, step by step, so you can see how much of it is real misreading.
35
+ The page inspector's compare tab shows the misread / missed / added split and the number check too, and
36
+ `pyocr compare` prints an *OCR numbers* column. API: `errors`, `numbers` and `ladder` on
37
+ `POST /api/documents/{id}/pages/{n}/compare`; `errors` and `numbers` per page and in `overall` on
38
+ `GET /api/documents/{id}/compare`. Existing fields are unchanged.
39
+ - **Compare all sources at once.** The Compare page has a new *All sources* mode: tick three or more sources and
40
+ they are voted word by word into a **consensus**, so no source has to be assumed right. Each source is scored
41
+ against the consensus (CER, WER, misread / missed / added, numbers), with a sources × pages grid, the consensus
42
+ text showing every disputed word with its vote count and what the other sources read (close calls, where no
43
+ reading has a majority, in amber; "only lines that disagree" hides the rest), a copy button, and a matrix of how
44
+ much each pair of sources agrees. Sources with no text on a page don't vote there, and pages with only two voters
45
+ are flagged, since two readings can't outvote each other. API: `GET /api/documents/{id}/consensus` and
46
+ `GET /api/documents/{id}/pages/{n}/consensus` (`?sources=` 2–8 ids).
47
+ - **Review & correct.** On the consensus page view, *Review & correct* puts the page image next to the text: click a
48
+ word to see it highlighted on the image and every source's reading of it, pick the right one or type your own, and
49
+ the next close call is selected. *Save corrected text* stores the page as a new **Corrected** source (ground
50
+ truth): it can be exported, read on *Full text*, and becomes the default reference in two-source mode. Stored in
51
+ `corrected/<page>.json` in the document's folder; existing folders are unaffected. API:
52
+ `GET/PUT/DELETE /api/documents/{id}/pages/{n}/corrected`; the page consensus adds a word `box` per column (from
53
+ native text or OCR), `page_size` and the page's `corrected` state.
54
+ - **WER in any order** (order-free WER): the texts compared as bags of words, so words read in a different order
55
+ (columns read across, table rows or side notes in another sequence) aren't counted as errors. The gap to WER is
56
+ the cost of reading order alone. Shown next to WER on the Compare page (whole document, per page, in the table),
57
+ in the inspector, on consensus source cards and as a Leaderboard column. When most of a page's word error is
58
+ reading order, the page's breakdown says so, and the number check reports how many numbers are present at another
59
+ position. API: `wer_order_free`, `word_distance_order_free`, `words_missing` and `words_extra` in every `metrics`
60
+ (`score()`); `wer_order_free` in document `overall`, consensus `overall` and leaderboard entries; `present` in
61
+ `numbers`.
62
+ - **Leaderboard** (new page, `/leaderboard`, also linked from each workspace): every OCR engine, LLM run and PDF
63
+ library ranked across the whole library or one workspace, with CER and WER, misread / missed / added, numbers read
64
+ exactly, pages scored, and for LLM runs cost per page at catalog list price and model time per page; sortable, with
65
+ a sources × documents grid. Each page is scored against corrected text where it has it (real accuracy), otherwise
66
+ the consensus of three or more independent sources (agreement: the page says so); *Score against* can force either.
67
+ *Only pages every source has read* compares like for like. Extraction runs and corrected text aren't ranked.
68
+ API: `GET /api/leaderboard?workspace=&reference=auto|corrected|consensus&shared=`.
69
+ - Faster Overview for large documents: per-page facts (size, text-layer characters, images) are computed once and
70
+ saved to `pages.json` in the document folder, so later visits to a 2,000-page PDF's Overview drop from ~2.5 s
71
+ to ~40 ms. Uploads build `pages.json` in the background right away, so the first visit is fast too, and page
72
+ renders keep working while it runs. The page grid draws thumbnails in batches of 200 as you scroll. Existing
73
+ folders (and documents added with `pyocr add`) get `pages.json` on first view; it is derived data and is rebuilt
74
+ if missing or damaged.
75
+ - No new settings, and LLM prompts and cache keys are unchanged, so existing results stay valid.
76
+
5
77
  ## 0.6.0 - 2026-11-27
6
78
 
7
79
  - **Structured data extraction**: a new prompt, *Structured data (fields → JSON)*, fills a JSON Schema from each page
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: pyocr-toolkit
3
- Version: 0.6.0
3
+ Version: 0.7.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
@@ -402,14 +402,16 @@ Everything you upload and extract is stored in `./data` (change it with `DATA_DI
402
402
  | **Home** `/` | Drop files to upload; see setup status and recent documents. |
403
403
  | **Library** `/documents` | Document cards showing native / OCR / LLM coverage and how many pages still have no text. Filter by status, workspace or name; delete. |
404
404
  | **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. |
405
- | **Overview** `/documents/{id}` | Start background extraction (any OCR engine or 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. |
406
- | **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`. |
405
+ | **Overview** `/documents/{id}` | Every *source* (engine + model + prompt) with coverage and token usage; read or export it; running jobs; page thumbnails. The **Extract** button in the document header (or `x`) opens a side panel to start background extraction (any OCR engine or LLM) for all pages or a range such as `1-5,9`, typed or picked on a clickable page map; *More options* holds image preprocessing, pages per LLM request and re-running. |
406
+ | **Pages** (page inspector) `/documents/{id}/pages/{n}` | Page image next to native, OCR and LLM text; run OCR or an LLM on just this page; a *Diff* view; a *Columns* view 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`. |
407
407
  | **Full text** `/documents/{id}/text` | Read the whole document from one source, optionally beside the page images; find, copy, download. |
408
- | **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**. |
408
+ | **Compare** `/documents/{id}/compare` | Score source B against source A on every page: document-level CER/WER (plus WER in any order, which ignores reading order), word errors split into misread / missed / added, how many numbers (amounts, dates, IDs) were read exactly, a clickable CER-per-page chart, and an aligned side-by-side diff of the selected page with a breakdown of its errors by kind (opens on the worst page). **All sources** votes three or more sources into a word-by-word consensus and scores each against it, so you don't need to know which one is right; close calls are marked for review. **Review & correct** shows the page image next to the text, highlights each disputed word on it, and saves your choices as a *Corrected* source: ground truth to score every engine against. Works for OCR vs LLM, native vs LLM, or **model vs model**. |
409
409
  | **Search** `/search` | Search all documents at once. |
410
410
  | **Jobs** `/jobs` | All background extractions, with progress, errors and tokens. |
411
411
  | **Providers** `/providers` | Which settings are set or missing, a form to set keys/endpoints in the browser, plus a **Test connection** button per provider. |
412
412
  | **Models** `/models` | Search a catalog of vision models rated for transcription (excellent / good / fair / not suitable, with price and reason); list the models your key can use and pick one. |
413
+ | **Command palette** `Ctrl+K` / `⌘K` | On every page: open any page or document by name, run the current document's actions (extract, compare, export), or search every document's text. The top bar itself has three sections: Documents (Workspaces, All files, Leaderboard), Search, Settings (Providers, Models). |
414
+ | **Leaderboard** `/leaderboard` | Every OCR engine, LLM run and PDF library ranked across the library or one workspace: CER/WER, misread / missed / added, numbers read exactly, pages scored, cost and time per page. Each page is scored against your corrected text where you reviewed it, otherwise the consensus of three or more sources; *Only pages every source has read* makes it like for like. |
413
415
  | **Help** `/help` | The full guide: concepts, metrics, workflows, troubleshooting. |
414
416
  | **API docs** `/docs` | Interactive OpenAPI docs for the JSON API. |
415
417
 
@@ -532,7 +534,9 @@ you ask otherwise.
532
534
  between two texts. **CER** = edits / reference characters; **WER** is the same count over words. For example,
533
535
  "the cat sat" → "the bat sat" has 1 edit, so CER = 1/11 = 9%. Whitespace is normalised first, because line
534
536
  breaks aren't reading errors. Disagreement between two engines is not proof of error: compare against a
535
- born-digital PDF's native text when you need ground truth.
537
+ born-digital PDF's native text when you need ground truth. **WER in any order** compares the texts as bags of
538
+ words, so an engine that reads a two-column page across the columns isn't punished for order alone; the gap
539
+ between it and WER is the cost of reading order.
536
540
 
537
541
  The Help page explains each of these in more depth.
538
542
 
@@ -137,14 +137,16 @@ Everything you upload and extract is stored in `./data` (change it with `DATA_DI
137
137
  | **Home** `/` | Drop files to upload; see setup status and recent documents. |
138
138
  | **Library** `/documents` | Document cards showing native / OCR / LLM coverage and how many pages still have no text. Filter by status, workspace or name; delete. |
139
139
  | **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. |
140
- | **Overview** `/documents/{id}` | Start background extraction (any OCR engine or 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. |
141
- | **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`. |
140
+ | **Overview** `/documents/{id}` | Every *source* (engine + model + prompt) with coverage and token usage; read or export it; running jobs; page thumbnails. The **Extract** button in the document header (or `x`) opens a side panel to start background extraction (any OCR engine or LLM) for all pages or a range such as `1-5,9`, typed or picked on a clickable page map; *More options* holds image preprocessing, pages per LLM request and re-running. |
141
+ | **Pages** (page inspector) `/documents/{id}/pages/{n}` | Page image next to native, OCR and LLM text; run OCR or an LLM on just this page; a *Diff* view; a *Columns* view 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`. |
142
142
  | **Full text** `/documents/{id}/text` | Read the whole document from one source, optionally beside the page images; find, copy, download. |
143
- | **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**. |
143
+ | **Compare** `/documents/{id}/compare` | Score source B against source A on every page: document-level CER/WER (plus WER in any order, which ignores reading order), word errors split into misread / missed / added, how many numbers (amounts, dates, IDs) were read exactly, a clickable CER-per-page chart, and an aligned side-by-side diff of the selected page with a breakdown of its errors by kind (opens on the worst page). **All sources** votes three or more sources into a word-by-word consensus and scores each against it, so you don't need to know which one is right; close calls are marked for review. **Review & correct** shows the page image next to the text, highlights each disputed word on it, and saves your choices as a *Corrected* source: ground truth to score every engine against. Works for OCR vs LLM, native vs LLM, or **model vs model**. |
144
144
  | **Search** `/search` | Search all documents at once. |
145
145
  | **Jobs** `/jobs` | All background extractions, with progress, errors and tokens. |
146
146
  | **Providers** `/providers` | Which settings are set or missing, a form to set keys/endpoints in the browser, plus a **Test connection** button per provider. |
147
147
  | **Models** `/models` | Search a catalog of vision models rated for transcription (excellent / good / fair / not suitable, with price and reason); list the models your key can use and pick one. |
148
+ | **Command palette** `Ctrl+K` / `⌘K` | On every page: open any page or document by name, run the current document's actions (extract, compare, export), or search every document's text. The top bar itself has three sections: Documents (Workspaces, All files, Leaderboard), Search, Settings (Providers, Models). |
149
+ | **Leaderboard** `/leaderboard` | Every OCR engine, LLM run and PDF library ranked across the library or one workspace: CER/WER, misread / missed / added, numbers read exactly, pages scored, cost and time per page. Each page is scored against your corrected text where you reviewed it, otherwise the consensus of three or more sources; *Only pages every source has read* makes it like for like. |
148
150
  | **Help** `/help` | The full guide: concepts, metrics, workflows, troubleshooting. |
149
151
  | **API docs** `/docs` | Interactive OpenAPI docs for the JSON API. |
150
152
 
@@ -267,7 +269,9 @@ you ask otherwise.
267
269
  between two texts. **CER** = edits / reference characters; **WER** is the same count over words. For example,
268
270
  "the cat sat" → "the bat sat" has 1 edit, so CER = 1/11 = 9%. Whitespace is normalised first, because line
269
271
  breaks aren't reading errors. Disagreement between two engines is not proof of error: compare against a
270
- born-digital PDF's native text when you need ground truth.
272
+ born-digital PDF's native text when you need ground truth. **WER in any order** compares the texts as bags of
273
+ words, so an engine that reads a two-column page across the columns isn't punished for order alone; the gap
274
+ between it and WER is the cost of reading order.
271
275
 
272
276
  The Help page explains each of these in more depth.
273
277
 
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "pyocr-toolkit"
3
- version = "0.6.0"
3
+ version = "0.7.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.6.0"
3
+ __version__ = "0.7.0"
@@ -74,7 +74,7 @@ class SchemaCheckBody(BaseModel):
74
74
 
75
75
 
76
76
  class TextRef(BaseModel):
77
- source: Literal["native", "ocr", "llm"]
77
+ source: Literal["native", "ocr", "llm", "corrected"]
78
78
  #: for ``llm``: cache key of a stored result (``None`` -> most recent one)
79
79
  key: str | None = None
80
80
  #: for ``ocr``: engine id (``None`` -> Tesseract)
@@ -91,6 +91,11 @@ class TextRef(BaseModel):
91
91
  return f"llm:{self.key}" if self.source == "llm" and self.key else self.source
92
92
 
93
93
 
94
+ class CorrectedBody(BaseModel):
95
+ text: str = Field(..., description="the page's text as a person confirmed it")
96
+ based_on: list[str] = Field(default_factory=list, description="source ids it was reviewed from")
97
+
98
+
94
99
  class CompareBody(BaseModel):
95
100
  reference: TextRef = Field(default_factory=lambda: TextRef(source="llm"))
96
101
  hypothesis: TextRef = Field(default_factory=lambda: TextRef(source="ocr"))
@@ -295,6 +300,7 @@ def build_api(settings: Settings, store: DocumentStore, services: Services, jobs
295
300
  if len(data) > settings.max_upload_mb * 1024 * 1024:
296
301
  raise HTTPException(413, f"file larger than {settings.max_upload_mb} MB")
297
302
  meta = await run_in_threadpool(store.add, file.filename or "upload.pdf", data)
303
+ store.warm_page_stats(meta.id) # build pages.json now, so the first Overview visit doesn't wait for it
298
304
  return meta.__dict__
299
305
 
300
306
  @api.post("/uploads", status_code=201, tags=["documents"])
@@ -311,6 +317,8 @@ def build_api(settings: Settings, store: DocumentStore, services: Services, jobs
311
317
  data = await f.read(max_bytes + 1)
312
318
  named.append((f.filename or "upload.pdf", data))
313
319
  result = await run_in_threadpool(ingest, store, named, max_bytes=max_bytes)
320
+ for meta in result.documents:
321
+ store.warm_page_stats(meta.id)
314
322
  body = result.to_json()
315
323
  if workspace_id and result.documents:
316
324
  ws = await run_in_threadpool(workspaces.add_documents, workspace_id, [m.id for m in result.documents])
@@ -337,7 +345,7 @@ def build_api(settings: Settings, store: DocumentStore, services: Services, jobs
337
345
  @api.get("/documents/{doc_id}/pages", tags=["pages"])
338
346
  def pages(doc_id: str):
339
347
  doc = get_doc(doc_id)
340
- return [doc.page_info(n) for n in doc.iter_pages()]
348
+ return doc.page_infos()
341
349
 
342
350
  @api.get("/documents/{doc_id}/pages/{page}/image", tags=["pages"])
343
351
  def page_image(doc_id: str, page: int, dpi: int = Query(None, ge=36, le=600),
@@ -570,6 +578,9 @@ def build_api(settings: Settings, store: DocumentStore, services: Services, jobs
570
578
  "reference": {"label": services.source_label(doc, body.reference.source_id), **body.reference.model_dump()},
571
579
  "hypothesis": {"label": services.source_label(doc, body.hypothesis.source_id), **body.hypothesis.model_dump()},
572
580
  "metrics": compare.score(ref_text, hyp_text, opts),
581
+ "errors": compare.error_breakdown(ref_text, hyp_text, opts),
582
+ "numbers": compare.check_numbers(ref_text, hyp_text),
583
+ "ladder": compare.cer_ladder(ref_text, hyp_text),
573
584
  "diff": compare.word_diff(ref_text, hyp_text, opts) if body.diff else None,
574
585
  }
575
586
 
@@ -581,10 +592,15 @@ def build_api(settings: Settings, store: DocumentStore, services: Services, jobs
581
592
 
582
593
  ``overall`` is micro-averaged (total edits / total reference chars), so
583
594
  long pages weigh more than short ones - the honest whole-document number.
595
+ Each scored page also carries ``errors`` (misread / missed / added word
596
+ counts) and ``numbers`` (digit-bearing tokens read exactly); ``overall``
597
+ sums both.
584
598
  """
585
599
  doc = get_doc(doc_id)
586
600
  opts = compare.NormalizeOptions(ignore_case, ignore_punctuation)
587
- rows, tot_cd, tot_rc, tot_wd, tot_rw = [], 0, 0, 0, 0
601
+ rows, tot_cd, tot_rc, tot_wd, tot_rw, tot_wf = [], 0, 0, 0, 0, 0
602
+ errors = {"misread": 0, "missed": 0, "added": 0}
603
+ numbers = {"total": 0, "correct": 0}
588
604
  for n in doc.iter_pages():
589
605
  ta, tb = services.page_text(doc, n, a), services.page_text(doc, n, b)
590
606
  if ta is None or tb is None:
@@ -593,7 +609,16 @@ def build_api(settings: Settings, store: DocumentStore, services: Services, jobs
593
609
  m = compare.score(ta, tb, opts)
594
610
  tot_cd += m["char_distance"]; tot_rc += m["reference_chars"]
595
611
  tot_wd += m["word_distance"]; tot_rw += m["reference_words"]
596
- rows.append({"page": n, "metrics": m, "missing": []})
612
+ tot_wf += m["word_distance_order_free"]
613
+ br = compare.error_breakdown(ta, tb, opts, max_examples=0, max_confusions=0)
614
+ err = {k: br[k] for k in errors}
615
+ nums = compare.check_numbers(ta, tb, max_wrong=0)
616
+ num = {"total": nums["total"], "correct": nums["correct"]}
617
+ for k in errors:
618
+ errors[k] += err[k]
619
+ for k in numbers:
620
+ numbers[k] += num[k]
621
+ rows.append({"page": n, "metrics": m, "missing": [], "errors": err, "numbers": num})
597
622
  scored = [r for r in rows if r["metrics"]]
598
623
  overall = None
599
624
  if scored:
@@ -601,13 +626,193 @@ def build_api(settings: Settings, store: DocumentStore, services: Services, jobs
601
626
  "pages_scored": len(scored),
602
627
  "cer": round(tot_cd / tot_rc, 4) if tot_rc else None,
603
628
  "wer": round(tot_wd / tot_rw, 4) if tot_rw else None,
629
+ "wer_order_free": round(tot_wf / tot_rw, 4) if tot_rw else None,
604
630
  "worst_page": max(scored, key=lambda r: r["metrics"]["cer"])["page"],
605
631
  "pages_over_10pct": sum(r["metrics"]["cer"] > 0.10 for r in scored),
632
+ "pages_under_2pct": sum(r["metrics"]["cer"] <= 0.02 for r in scored),
633
+ "errors": errors,
634
+ "numbers": numbers,
606
635
  }
607
636
  return {"a": {"id": a, "label": services.source_label(doc, a)},
608
637
  "b": {"id": b, "label": services.source_label(doc, b)},
609
638
  "overall": overall, "pages": rows}
610
639
 
640
+ MAX_CONSENSUS_SOURCES = 8
641
+
642
+ def _consensus_sources(sources: str) -> list[str]:
643
+ ids = list(dict.fromkeys(x.strip() for x in sources.split(",") if x.strip()))
644
+ if len(ids) < 2:
645
+ raise DocumentError("pick at least two sources (three or more for a meaningful vote)")
646
+ if len(ids) > MAX_CONSENSUS_SOURCES:
647
+ raise DocumentError(f"pick at most {MAX_CONSENSUS_SOURCES} sources")
648
+ return ids
649
+
650
+ def _page_texts(doc: OpenDocument, page: int, ids: list[str]) -> dict[str, str]:
651
+ """Texts of the chosen sources on one page; a source with no text there doesn't vote."""
652
+ out = {}
653
+ for sid in ids:
654
+ text = services.page_text(doc, page, sid)
655
+ if text and text.strip():
656
+ out[sid] = text
657
+ return out
658
+
659
+ @api.get("/documents/{doc_id}/pages/{page}/consensus", tags=["compare"])
660
+ def consensus_page(doc_id: str, page: int,
661
+ sources: str = Query(..., description="comma-separated source ids, 2-8"),
662
+ ignore_case: bool = True, ignore_punctuation: bool = False):
663
+ """Vote the chosen sources into a consensus for one page and score each against it.
664
+
665
+ Sources with no text on the page are listed in ``missing`` and don't vote.
666
+ ``columns`` is the word-by-word alignment (one token per voting source,
667
+ in ``sources`` order).
668
+ """
669
+ doc = get_doc(doc_id)
670
+ if not 0 <= page < doc.meta.page_count:
671
+ raise DocumentError(f"page {page + 1} is out of range")
672
+ ids = _consensus_sources(sources)
673
+ texts = _page_texts(doc, page, ids)
674
+ missing = [sid for sid in ids if sid not in texts]
675
+ if len(texts) < 2:
676
+ raise DocumentError(f"page {page + 1} has text from {len(texts)} of the chosen sources; "
677
+ "a consensus needs two or more. Extract the missing ones first.")
678
+ res = compare.consensus(texts, compare.NormalizeOptions(ignore_case, ignore_punctuation))
679
+ labels = {sid: services.source_label(doc, sid) for sid in ids}
680
+ _add_boxes(doc, page, res, texts)
681
+ info = doc.page_info(page)
682
+ corrected = doc.load_corrected(page)
683
+ return {"page": page, "labels": labels, "missing": missing,
684
+ "page_size": [info["width"], info["height"]],
685
+ "corrected": {"updated_at": corrected["updated_at"], "based_on": corrected.get("based_on", [])}
686
+ if corrected else None, **res}
687
+
688
+ def _add_boxes(doc: OpenDocument, page: int, res: dict, texts: dict[str, str]) -> None:
689
+ """Give each consensus column a word box (PDF points) to highlight on the page image.
690
+
691
+ Boxes come from the voting sources that have them (native text, OCR), preferring one
692
+ that voted for the winner. LLM text has no boxes; a word only an LLM read borrows the
693
+ box of the word before it (``box_approx``).
694
+ """
695
+ boxed: dict[str, list] = {}
696
+ for sid in res["sources"]:
697
+ layer = services.word_layer(doc, page, sid)
698
+ if layer and layer.words:
699
+ boxed[sid] = compare.map_word_boxes(texts[sid], [(w.text, w.rect) for w in layer.words])
700
+ prev = None
701
+ for col in res["columns"]:
702
+ order = [i for i in range(len(res["sources"])) if i not in col["dissent"]] + col["dissent"]
703
+ box = next((boxed[res["sources"][i]][col["pos"][i]] for i in order
704
+ if res["sources"][i] in boxed and col["pos"][i] >= 0
705
+ and boxed[res["sources"][i]][col["pos"][i]]), None)
706
+ col["box"], col["box_approx"] = (box, False) if box else (prev, prev is not None)
707
+ prev = box or prev
708
+
709
+ @api.get("/documents/{doc_id}/pages/{page}/corrected", tags=["compare"])
710
+ def get_corrected(doc_id: str, page: int):
711
+ """The page's corrected text (saved from the Review panel), with when and from which sources."""
712
+ record = get_doc(doc_id).load_corrected(page)
713
+ if not record:
714
+ raise HTTPException(404, f"page {page + 1} has no corrected text yet")
715
+ return record
716
+
717
+ @api.put("/documents/{doc_id}/pages/{page}/corrected", tags=["compare"])
718
+ def put_corrected(doc_id: str, page: int, body: CorrectedBody, request: Request):
719
+ """Save a person's verdict on what the page says. It becomes the ``corrected`` source."""
720
+ _require_same_origin(request)
721
+ doc = get_doc(doc_id)
722
+ if not 0 <= page < doc.meta.page_count:
723
+ raise DocumentError(f"page {page + 1} is out of range")
724
+ if not body.text.strip():
725
+ raise DocumentError("the corrected text is empty; to remove it, delete it instead")
726
+ return doc.save_corrected(page, body.text, body.based_on)
727
+
728
+ @api.delete("/documents/{doc_id}/pages/{page}/corrected", status_code=204, tags=["compare"])
729
+ def delete_corrected(doc_id: str, page: int):
730
+ if not get_doc(doc_id).delete_corrected(page):
731
+ raise HTTPException(404, f"page {page + 1} has no corrected text")
732
+
733
+ @api.get("/documents/{doc_id}/consensus", tags=["compare"])
734
+ def consensus_document(doc_id: str,
735
+ sources: str = Query(..., description="comma-separated source ids, 2-8"),
736
+ ignore_case: bool = True, ignore_punctuation: bool = False):
737
+ """Every page's consensus of the chosen sources, summed up per source.
738
+
739
+ ``overall[source]`` is micro-averaged over the pages that source voted on
740
+ (total edits / total consensus characters). ``matrix[a][b]`` is source
741
+ ``b`` scored against source ``a`` over pages where both have text.
742
+ Pages where fewer than two sources have text are not scored.
743
+ """
744
+ doc = get_doc(doc_id)
745
+ ids = _consensus_sources(sources)
746
+ opts = compare.NormalizeOptions(ignore_case, ignore_punctuation)
747
+ zero = {"char_distance": 0, "reference_chars": 0, "word_distance": 0, "reference_words": 0,
748
+ "word_distance_order_free": 0,
749
+ "misread": 0, "missed": 0, "added": 0, "numbers_total": 0, "numbers_correct": 0, "pages": 0}
750
+ tot = {sid: dict(zero) for sid in ids}
751
+ pair = {a: {b: [0, 0] for b in ids if b != a} for a in ids}
752
+ rows, counts = [], {"words": 0, "agree": 0, "majority": 0, "tie": 0}
753
+ for n in doc.iter_pages():
754
+ texts = _page_texts(doc, n, ids)
755
+ if len(texts) < 2:
756
+ rows.append({"page": n, "scored": False, "missing": [sid for sid in ids if sid not in texts]})
757
+ continue
758
+ res = compare.consensus(texts, opts)
759
+ for k in counts:
760
+ counts[k] += res["counts"][k]
761
+ cer = {}
762
+ for sid, v in res["per_source"].items():
763
+ t, sc = tot[sid], v["score"]
764
+ for k in ("char_distance", "reference_chars", "word_distance", "reference_words",
765
+ "word_distance_order_free"):
766
+ t[k] += sc[k]
767
+ for k in ("misread", "missed", "added"):
768
+ t[k] += v["errors"][k]
769
+ t["numbers_total"] += v["numbers"]["total"]
770
+ t["numbers_correct"] += v["numbers"]["correct"]
771
+ t["pages"] += 1
772
+ cer[sid] = sc["cer"]
773
+ for a, row in res["matrix"].items():
774
+ for b, m in row.items():
775
+ if m:
776
+ pair[a][b][0] += m["char_distance"]
777
+ pair[a][b][1] += m["reference_chars"]
778
+ rows.append({"page": n, "scored": True, "missing": [sid for sid in ids if sid not in texts],
779
+ "pivot": res["pivot"], "counts": res["counts"], "cer": cer})
780
+
781
+ def rate(num: int, den: int) -> float | None:
782
+ return round(num / den, 4) if den else None
783
+
784
+ overall = {sid: {"pages": t["pages"], "cer": rate(t["char_distance"], t["reference_chars"]),
785
+ "wer": rate(t["word_distance"], t["reference_words"]),
786
+ "wer_order_free": rate(t["word_distance_order_free"], t["reference_words"]),
787
+ "errors": {k: t[k] for k in ("misread", "missed", "added")},
788
+ "numbers": {"total": t["numbers_total"], "correct": t["numbers_correct"]}}
789
+ for sid, t in tot.items()}
790
+ matrix = {a: {b: (rate(*pair[a][b]) if b != a else None) for b in ids} for a in ids}
791
+ return {"sources": ids, "labels": {sid: services.source_label(doc, sid) for sid in ids},
792
+ "pages_scored": sum(r["scored"] for r in rows), "counts": counts,
793
+ "overall": overall, "matrix": matrix, "pages": rows}
794
+
795
+ @api.get("/leaderboard", tags=["compare"])
796
+ def leaderboard(workspace: str | None = Query(None, description="workspace id; empty = every document"),
797
+ reference: Literal["auto", "corrected", "consensus"] = "auto", shared: bool = False,
798
+ ignore_case: bool = True, ignore_punctuation: bool = False):
799
+ """Rank every source (OCR engines, LLM runs, PDF libraries) across documents.
800
+
801
+ Each page is scored against corrected text where a person reviewed it, else the
802
+ consensus of three or more independent sources (``reference`` picks). See
803
+ ``Services.leaderboard``.
804
+ """
805
+ ids = workspaces.get(workspace).doc_ids if workspace else [m.id for m in store.list()]
806
+ docs = []
807
+ for i in ids:
808
+ try:
809
+ docs.append(store.get(i))
810
+ except DocumentError: # deleted since it was added to the workspace
811
+ continue
812
+ opts = compare.NormalizeOptions(ignore_case, ignore_punctuation)
813
+ res = services.leaderboard(docs, reference, shared, opts)
814
+ return {"workspace": workspace, **res}
815
+
611
816
  @api.get("/documents/{doc_id}/report", tags=["compare"])
612
817
  def report(doc_id: str, ignore_case: bool = True, ignore_punctuation: bool = False):
613
818
  """Per-page overview against the most recent LLM transcription of each page."""
@@ -307,16 +307,20 @@ async def _compare(args: argparse.Namespace) -> int:
307
307
  if problem:
308
308
  print(f"OCR columns skipped: {problem}", file=sys.stderr)
309
309
  print(f"OCR engine: {engine.label}", file=sys.stderr)
310
- print(f"{'page':>5} {'OCR CER':>8} {'OCR WER':>8} {'native CER':>10}")
310
+ print(f"{'page':>5} {'OCR CER':>8} {'OCR WER':>8} {'OCR numbers':>11} {'native CER':>10}")
311
311
  for n, res in zip(pages, llm):
312
312
  native = doc.native_text(n).text
313
- ocr_cer = ocr_wer = "–"
313
+ ocr_cer = ocr_wer = ocr_num = "–"
314
314
  if not problem:
315
315
  layer = await asyncio.to_thread(services.run_ocr_page, doc, n, False, engine.id)
316
- s = compare.score(res["text"], layer.text, opts)
316
+ ocr_text = layer.text
317
+ s = compare.score(res["text"], ocr_text, opts)
317
318
  ocr_cer, ocr_wer = f"{s['cer']:.1%}", f"{s['wer']:.1%}"
319
+ num = compare.check_numbers(res["text"], ocr_text, max_wrong=0)
320
+ if num["total"]:
321
+ ocr_num = f"{num['correct']}/{num['total']}"
318
322
  nat = f"{compare.score(res['text'], native, opts)['cer']:.1%}" if native.strip() else "no text"
319
- print(f"{n + 1:>5} {ocr_cer:>8} {ocr_wer:>8} {nat:>10}")
323
+ print(f"{n + 1:>5} {ocr_cer:>8} {ocr_wer:>8} {ocr_num:>11} {nat:>10}")
320
324
  print(f"\ndocument {doc.meta.id}: open http://127.0.0.1:8000/documents/{doc.meta.id}/compare for diffs",
321
325
  file=sys.stderr)
322
326
  return 0