bikramdocsumo commited on
Commit ·
10469c8
0
Parent(s):
Initial release: SumoOCR tiny v0.1.0
Browse filesFiles changed (24)
- .gitattributesAdded+2
- .gitignoreAdded+12
- LICENSEAdded+202
- MANIFEST.inAdded+1
- NOTICEAdded+10
- README.mdAdded+229
- REPORT.mdAdded+175
- charts/accuracy_vs_speed.svgAdded
- charts/word_f1_by_benchmark.svgAdded
- examples/invoice.pngAdded
- examples/ocr_page.pyAdded+11
- pyproject.tomlAdded+43
- setup.pyAdded+25
- sumoocr/__init__.pyAdded+11
- sumoocr/backend.pyAdded+64
- sumoocr/cli.pyAdded+34
- sumoocr/det.pyAdded+132
- sumoocr/models/config.jsonAdded+7
- sumoocr/models/det.onnxAdded+3
- sumoocr/models/rec.classes.jsonAdded+1
- sumoocr/models/rec.onnxAdded+3
- sumoocr/ocr.pyAdded+240
- sumoocr/rec.pyAdded+135
- tests/test_sumoocr.pyAdded+62
12*.onnx filter=lfs diff=lfs merge=lfs -text*.png filter=lfs diff=lfs merge=lfs -text123456789101112__pycache__/*.py[cod]*.egg-info/build/dist/.venv/.pytest_cache/.DS_Store.env.env.**.pem*.key123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
Apache License Version 2.0, January 2004 http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
(a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
Copyright 2026 Docsumo
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.1recursive-include examples *.png *.py12345678910SumoOCR tinyCopyright 2026 Docsumo
This product includes models from PaddleOCR (https://github.com/PaddlePaddle/PaddleOCR),Copyright PaddlePaddle Authors, licensed under the Apache License, Version 2.0: - sumoocr/models/det.onnx: derived from the PP-OCRv6 tiny text detection model (converted to ONNX opset 20 with fused Gelu(tanh) and post-training INT8 QDQ quantization). - sumoocr/models/rec.onnx: SumoOCR tiny, fine-tuned by Docsumo from the PP-OCRv6 tiny text recognition model (its output layer reduced to 758 Latin-script characters, converted to ONNX opset 20 with fused Gelu(tanh) and post-training INT8 QDQ quantization).123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229---license: apache-2.0pipeline_tag: image-to-textlibrary_name: onnxbase_model: PaddlePaddle/PP-OCRv6_tiny_reclanguage:- en- de- fr- es- it- pt- nl- pl- sv- da- nb- cs- hu- tr- rotags:- ocr- text-recognition- documents- invoices- receipts- cpu- onnx- pp-ocrv6---
# SumoOCR tiny
**A 1M-parameter, 1.8 MB OCR pipeline for business documents in Latin-script languages, running on one CPU core.**

[Benchmark report](REPORT.md) · [SumoOCR](https://www.docsumo.com/blog/introducing-sumoocr) · [PP-OCRv6 tiny (base)](https://huggingface.co/PaddlePaddle/PP-OCRv6_tiny_rec) · [Citation](#citation)
```bashpip install sumoocr```
SumoOCR tiny is a text-line recognizer from Docsumo: Paddle's PP-OCRv6 tiny recognizer fine-tuned on public and business documents. Together with the PP-OCRv6 tiny text detector included in the package, it makes a complete OCR pipeline, and it is the first reader in SumoOCR, Docsumo's OCR engine.
| | SumoOCR tiny ||---|---|| **Size** | 1.04M parameters, 1.8 MB (0.43M detector + 0.61M recognizer) || **Speed** | 0.28 s a page (3.55 pages per second) on one CPU core, whole pipeline || **Accuracy** (word F1) | FUNSD 83.8 · SROIE 91.3 · XFUND 95.2 · OmniDocBench (English) 91.9 || **Languages** | English and European Latin-script languages (German, French, Spanish, Italian, Portuguese, Dutch, Polish, Czech, Hungarian, Turkish, Romanian, Nordic) || **Runtime** | ONNX Runtime (default) or OpenVINO, CPU only; no PyTorch or PaddlePaddle needed || **License** | Apache-2.0, the same as PP-OCRv6 |
Compared with the other engines tested, on the same pages and one CPU thread:
- **More accurate** than the same-size PP-OCRv6 tiny recognizer, PaddleOCR's own tiny setting, OCRia-nano-1 and Tesseract on all four benchmarks, and than Indra on SROIE, XFUND and OmniDocBench (FUNSD is a statistical tie).- **Faster** than every engine tested: 1.65x faster than OCRia-nano-1, 1.72x than Indra 1.2.0, 3.3x than Tesseract and 8.7x than PaddleOCR's tiny setting.
Full numbers are in [Benchmarks](#benchmarks) and the [benchmark report](REPORT.md).
> SumoOCR tiny reads **text lines**. For whole pages it runs after a text detector (see [How it works](#how-it-works)); it does not produce layout blocks, tables or reading order.

## Quickstart
```bashpip install sumoocr # models included (1.8 MB); `pip install "sumoocr[openvino]"` for OpenVINOsumoocr invoice.png # text, one line per linesumoocr invoice.png --format json # lines with boxes and confidences```
### Python
```pythonfrom sumoocr import SumoOCR
ocr = SumoOCR() # backend="openvino" for OpenVINO; threads=1 for one corefor line in ocr("invoice.png"): # a path, a BGR numpy array (cv2.imread) or a PIL image print(line.text, round(line.conf, 3), line.box)
print(ocr.read_text("invoice.png")) # the page as text, in reading ordertext, conf = ocr.read_line("line.png") # one text-line crop, no detection```
### ONNX only
The two models are plain ONNX files in [`sumoocr/models/`](sumoocr/models): read a line crop without the package:
```pythonimport json
import cv2import numpy as npimport onnxruntime as ort
sess = ort.InferenceSession("sumoocr/models/rec.onnx")chars = json.load(open("sumoocr/models/rec.classes.json")) # index 0 = CTC blank
def read_line(bgr): h, w = bgr.shape[:2] x = cv2.resize(bgr, (max(4, round(w * 40 / h)), 40)).astype(np.float32) x = ((x / 255.0 - 0.5) / 0.5).transpose(2, 0, 1)[None] # 1 x 3 x 40 x W, BGR probs = sess.run(None, {"x": x})[0][0] # W/4 x 758 ids = probs.argmax(1) keep = (ids != 0) & np.r_[True, ids[1:] != ids[:-1]] # greedy CTC return "".join(chars[i] for i in ids[keep])
print(read_line(cv2.imread("line.png")))```
### Input
- A page image (PNG, JPEG, TIFF, BMP, WebP; any size): the detector caps its long side at 1,280 px and automatically steps up to 2,400 px on dense small print such as newspapers (`adaptive=True`).- Printed text in Latin script; pages turned by 90°, 180° or 270° are detected and turned back.- Or one text-line crop (`read_line`).
### Output
| Field | What it is ||---|---|| `text` | the line's text || `conf` | mean character confidence, 0-1 (lines below 0.85 are dropped: `SumoOCR(text_score=...)`) || `box` | 4 [x, y] points, clockwise from the top-left, in pixels of the input image |
Lines come in reading order: top to bottom, left to right within a row.
## How it works
| Model | File | Role | Parameters ||---|---|---|---|| Text detector (PP-OCRv6 tiny, INT8 QDQ) | `sumoocr/models/det.onnx` | finds the text lines on the page | 0.43M || **SumoOCR tiny** (INT8 QDQ) | `sumoocr/models/rec.onnx` | reads each line: 40 px high, CTC over 758 characters (`rec.classes.json`) | 0.61M || **Total** | | | **1.04M** |
The page is scaled for the detector, its text boxes are cut out at full resolution and read one by one; a page whose lines read badly is tried upside down, and a page whose boxes stand on end is turned.
## Benchmarks
Word F1 (x 100) on whole pages, every engine on the same page images on CPU with one thread; bold = best in the column. Details, confidence intervals and the method: [benchmark report](REPORT.md).
| System (CPU) | FUNSD | SROIE | XFUND | OmniDocBench (EN) | Business Docs | pages/s | License ||---|---|---|---|---|---|---|---|| **SumoOCR tiny** | 83.8 | 91.3 | 95.2 | **91.9** | 98.9 | **3.55** | Apache-2.0 || SumoOCR \* | **85.6** | **94.5** | **96.0** | 90.9 | **99.0** | 0.91 | not released || Paddle tiny rec (our pipeline) | 79.0 | 89.3 | 94.5 | 90.4 | 97.5 | 1.31 | Apache-2.0 || PaddleOCR tiny ¹ | 77.0 | 86.5 | 94.5 | 91.0 | 97.1 | 0.41 | Apache-2.0 || OCRia-nano-1 | 80.9 | 87.0 | 92.7 | 82.2 | 98.0 | 2.15 | OCRia-nano-1 licence || Indra 1.2.0 | 83.4 | 89.2 | 93.6 | 90.0 | 98.2 | 2.07 | modified OpenRAIL-M || Tesseract 5 | 61.9 | 75.0 | 90.7 | 90.2 | 92.3 | 1.07 | Apache-2.0 |
FUNSD: 50 scanned forms. SROIE: 347 receipts. XFUND: 250 forms in German, Spanish, French, Italian and Portuguese. OmniDocBench: 755 English pages (papers, books, slides, magazines, newspapers). Business Docs: 41 public and synthetic business documents (invoices, statements, forms and US federal pages in 16 languages). "Paddle tiny rec (our pipeline)" is the PP-OCRv6 tiny recognizer SumoOCR tiny was fine-tuned from, run in the FP32 OpenVINO pipeline (see [Systems compared](REPORT.md#systems-compared)), not the shipped INT8 ONNX Runtime build with adaptive detection: its gap to SumoOCR tiny is the fine-tune plus those pipeline differences. The [line recognition table](#line-recognition-only) compares the two recognizers on the same crops. ¹ PaddleOCR 3.7 itself (Paddle's own package), its tiny setting: PP-OCRv6 tiny detector and recognizer. Timed natively: PaddlePaddle has no Linux arm64 build for the container.
\* SumoOCR is Docsumo's full OCR engine (not released). It also supports checkboxes, signatures and more complex documents.
### Line recognition only
The same ground-truth line crops for every recognizer (no detector): character error rate ↓, case and spaces ignored.
| Recognizer | SROIE CER ↓ | XFUND CER ↓ | FUNSD CER ↓ ||---|---|---|---|| SumoOCR tiny | 2.93 % | **1.77 %** | **4.26 %** || PP-OCRv6 tiny rec | **2.62 %** | 1.96 % | 5.38 % || Tesseract 5 (`--psm 7`) | 8.58 % | 9.86 % | 12.92 % |
## Speed
One process in a container limited to 1 vCPU (arm64), every engine on the same 100 pages (20 from each benchmark), taking turns page by page; whole pages, detection included.
| Configuration | mean word F1 (4 benchmarks) | pages/s | ms per page, 1 core (mean / P90) | License ||---|---|---|---|---|| **SumoOCR tiny** | 90.6 | 3.55 | 281 / 546 | Apache-2.0 || OCRia-nano-1 | 85.7 | 2.15 | 464 / 734 | OCRia-nano-1 licence || Indra 1.2.0 | 89.0 | 2.07 | 484 / 857 | modified OpenRAIL-M || Paddle tiny rec (our pipeline) | 88.3 | 1.31 | 764 / 1,456 | Apache-2.0 || Tesseract 5 | 79.4 | 1.07 | 931 / 2,074 | Apache-2.0 || SumoOCR | 91.7 | 0.91 | 1,103 / 1,976 | not released || PaddleOCR 3.7, tiny (PP-OCRv6 tiny det + rec) ¹ | 87.3 | 0.41 | 2,444 / 4,527 | Apache-2.0 |
¹ PaddlePaddle has no Linux arm64 build, so PaddleOCR could not run in the 1-vCPU container: it was timed natively on the same host, one thread (`cpu_threads=1`), 100 pages (8.7x the time of SumoOCR tiny run the same way on the same pages). Paddle's CPU kernels on ARM are much slower than its x86 path.
## Training
Fine-tuned from the PP-OCRv6 tiny recognizer (its output layer mapped to 758 Latin characters) on text-line crops (line heights 32-48 px) from business and public documents across diverse fonts and scan conditions, including:
- **Docsumo's internal benchmark documents** (their training split).- **Public government documents**: US federal publications (IRS, Federal Register, GovInfo, Census Bureau, CFPB, GSA, Federal Reserve) and EU documents from EUR-Lex.- **Synthetic rendered text lines**, with sentences from Tatoeba.
Only the model weights are released: no training document, crop or text is part of this repository. None of the four public benchmarks above (FUNSD, SROIE, XFUND, OmniDocBench) was used; 3 of the 41 Business Docs pages are public federal PDF pages that are also in the training set (see the [benchmark report](REPORT.md)).
Attribution. EUR-Lex documents: source EUR-Lex, © European Union, https://eur-lex.europa.eu. Synthetic sentences: Tatoeba (https://tatoeba.org), CC BY 2.0 FR.
## Limitations
- **Latin script only.** The 758 characters cover English and European Latin-script languages; Cyrillic, Greek, Arabic, Hebrew, Chinese, Japanese, Korean and Indic scripts are not recognized.- **Printed text.** Handwriting was not a training target and was not measured here.- **Lines, not documents.** It returns text lines with boxes and confidences: no layout blocks, tables, reading order or key-value structure (the benchmarks put every engine's lines in reading order with one shared routine).- **Receipts and low-resolution scans are its weakest pages.** SROIE 91.3 and FUNSD 83.8 word F1, 3.1 and 1.8 points behind SumoOCR. On receipt line crops the base PP-OCRv6 tiny reads slightly better (2.62 % vs 2.93 % character errors).- **Post-training INT8 quantization.** Both ONNX models use synthetic-calibrated INT8 QDQ quantization (keeping sensitive layers in FP32) for fast CPU inference at 1.8 MB total size; word F1 is within 0.2 points of FP32 on every benchmark (0.1 on the four-benchmark mean).
## Files
| File | What ||---|---|| `sumoocr/models/det.onnx` | text detector (PP-OCRv6 tiny, INT8 QDQ, opset-20 Gelu), 0.7 MB || `sumoocr/models/rec.onnx` | SumoOCR tiny recognizer (INT8 QDQ, opset-20 Gelu), 1.1 MB || `sumoocr/models/rec.classes.json` | the 758 output classes (0 = CTC blank, last = space) || `sumoocr/models/config.json` | input height and pre-processing of both models || `sumoocr/` | the Python package (`pip install sumoocr`) || `REPORT.md`, `charts/` | benchmark report || `LICENSE`, `NOTICE` | Apache-2.0; PaddleOCR attribution |
## License
Apache-2.0, the same licence as its base model, PP-OCRv6 tiny (PaddlePaddle); see `NOTICE`. The text detector is derived from the PP-OCRv6 tiny detector (Apache-2.0). ONNX Runtime (MIT) or OpenVINO (Apache-2.0) run the models.
## Citation
```bibtex@misc{sumoocrtiny2026, title = {SumoOCR tiny: a 0.6M-parameter text-line recognizer for business documents}, author = {Docsumo}, year = {2026}, url = {https://huggingface.co/docsumo/sumoOCR-tiny}}```123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175# SumoOCR tiny: benchmark report
[Model card](README.md) · [Systems compared](#systems-compared) · [Datasets](#datasets) · [Method](#method)
SumoOCR tiny against Paddle's PP-OCRv6 tiny recognizer, PaddleOCR, OCRia-nano-1, Indra and Tesseract on four public benchmarks (FUNSD, SROIE, XFUND, OmniDocBench) and a 41-page public and business document set (Business Docs). CPU, one thread, the same page images and the same scorer for every engine. Run 2026-12-01.
- **Accuracy**: SumoOCR tiny is ahead of PP-OCRv6 tiny, PaddleOCR tiny, OCRia-nano-1 and Tesseract on every set (outside the 95 % confidence interval), and ahead of Indra on SROIE (+2.2), XFUND (+1.5), OmniDocBench (+1.9) and Business Docs (+0.6); FUNSD (+0.4) is within the 95 % CI.- **Fine-tune vs base**: same architecture and size as PP-OCRv6 tiny, +4.9 on FUNSD, +2.0 on SROIE, +0.7 on XFUND; 21 % fewer character errors on FUNSD lines. The page-level gaps also include pipeline differences (see [Systems compared](#systems-compared)); the line-level table compares the two recognizers on the same crops.- **Speed**: 0.28 s a page (3.55 pages/s) on one core for the shipped INT8 QDQ build — the fastest engine tested: 1.65x faster than OCRia-nano-1 (0.46 s), 1.72x faster than Indra (0.48 s), 3.3x faster than Tesseract (0.93 s) and 8.7x faster than PaddleOCR tiny (2.44 s, native). The unquantized FP32 ONNX Runtime build also runs ahead of OCRia-nano-1 and Indra at 0.45 s (2.20 pages/s), with mean word F1 90.7 vs 90.6.- **Adaptive small-print detection**: the detector caps the long side at 1,280 px on normal pages and automatically steps up to 2,400 px on dense small print (~2 % of pages), reading OmniDocBench newspapers at 95.0 (Indra 94.9) at 344 ms mean on OmniDocBench.

## Benchmarks
Word F1 x 100: case-insensitive bag-of-words F1 against each benchmark's ground truth (the SumoOCR blog's scorer). Bold = best in the column. Both the shipped INT8 QDQ build (`SumoOCR tiny`, plotted in the charts) and the unquantized pure FP32 ONNX Runtime build (`SumoOCR tiny (FP32)`) are shown below.
| System (CPU) | FUNSD | SROIE | XFUND | OmniDocBench (EN) | OmniDocBench, no formulas | Business Docs | pages/s | License ||---|---|---|---|---|---|---|---|---|| **SumoOCR tiny** | 83.8 | 91.3 | 95.2 | **91.9** | **95.4** | 98.9 | **3.55** | Apache-2.0 || SumoOCR tiny (FP32) | 84.0 | 91.5 | 95.2 | **91.9** | **95.4** | 98.9 | 2.20 | Apache-2.0 || SumoOCR \* | **85.6** | **94.5** | **96.0** | 90.9 | 92.8 | **99.0** | 0.91 | not released || Paddle tiny rec (our pipeline) | 79.0 | 89.3 | 94.5 | 90.4 | 91.9 | 97.5 | 1.31 | Apache-2.0 || PaddleOCR tiny ¹ | 77.0 | 86.5 | 94.5 | 91.0 | 94.9 | 97.1 | 0.41 | Apache-2.0 || OCRia-nano-1 | 80.9 | 87.0 | 92.7 | 82.2 | 84.7 | 98.0 | 2.15 | OCRia-nano-1 licence || Indra 1.2.0 | 83.4 | 89.2 | 93.6 | 90.0 | 95.3 | 98.2 | 2.07 | modified OpenRAIL-M || Tesseract 5 | 61.9 | 75.0 | 90.7 | 90.2 | 93.1 | 92.3 | 1.07 | Apache-2.0 |
\* SumoOCR is Docsumo's full OCR engine (not released). It also supports checkboxes, signatures and more complex documents.
Change in word F1 against SumoOCR tiny, x 100, with a paired page bootstrap 95 % interval ("tie" = the interval contains 0):
| System | FUNSD | SROIE | XFUND | OmniDocBench (EN) | Business Docs ||---|---|---|---|---|---|| SumoOCR tiny (FP32) | +0.2 tie | +0.2 [+0.0, +0.3] | +0.1 tie | +0.0 tie | +0.1 [+0.0, +0.1] || SumoOCR | +1.8 [+1.3, +2.3] | +3.1 [+2.7, +3.6] | +0.8 [+0.5, +1.1] | -1.0 tie | +0.2 [+0.1, +0.3] || Paddle tiny rec (our pipeline) | -4.9 [-6.2, -3.6] | -2.0 [-2.4, -1.6] | -0.7 [-1.1, -0.3] | -1.5 [-3.4, -0.2] | -1.3 [-2.6, -0.5] || PaddleOCR tiny ¹ | -6.8 [-8.1, -5.8] | -4.8 [-5.3, -4.3] | -0.6 [-1.1, -0.1] | -0.9 [-1.6, -0.4] | -1.8 [-3.0, -1.1] || OCRia-nano-1 | -2.9 [-4.3, -1.8] | -4.3 [-5.0, -3.7] | -2.5 [-4.3, -1.5] | -9.6 [-12.3, -7.5] | -0.8 [-1.2, -0.5] || Indra 1.2.0 | -0.4 tie | -2.2 [-2.6, -1.7] | -1.5 [-2.1, -1.1] | -1.9 [-2.3, -1.4] | -0.6 [-1.1, -0.3] || Tesseract 5 | -21.9 [-26.1, -18.5] | -16.4 [-17.8, -15.2] | -4.4 [-5.3, -3.8] | -1.7 [-2.4, -1.1] | -6.5 [-10.8, -3.4] |

### Numbers and accented words
Numbers F1 = F1 over numeric tokens (amounts, dates, codes); FUNSD's are low for every engine (low-resolution digits, noisy ground truth). Accented words F1 = words with diacritics.
| System | numbers, FUNSD | numbers, SROIE | numbers, XFUND | numbers, OmniDocBench (EN) | numbers, Business Docs | accented, XFUND | accented, Business Docs ||---|---|---|---|---|---|---|---|| SumoOCR tiny | 58.8 | 89.7 | 84.8 | 79.9 | 99.0 | 95.2 | 98.9 || SumoOCR tiny (FP32) | 59.5 | 89.8 | 84.5 | **80.1** | **99.3** | 95.3 | 99.0 || SumoOCR | **60.5** | **92.6** | **85.4** | 79.2 | **99.3** | **97.0** | **99.7** || Paddle tiny rec (our pipeline) | 57.5 | 89.7 | 83.2 | 79.5 | 98.0 | 94.8 | 89.4 || PaddleOCR tiny ¹ | 54.9 | 88.5 | 82.6 | 79.6 | 96.6 | 95.6 | 90.7 || OCRia-nano-1 | 53.4 | 83.2 | 81.4 | 70.3 | 97.7 | 91.0 | 94.8 || Indra 1.2.0 | 57.3 | 86.2 | 81.4 | 79.4 | 98.6 | 93.4 | 97.0 || Tesseract 5 | 39.6 | 68.6 | 76.1 | 78.1 | 94.2 | 93.0 | 64.7 |
### XFUND by language
| System | German | Spanish | French | Italian | Portuguese ||---|---|---|---|---|---|| SumoOCR tiny | 97.3 | 97.3 | 91.6 | 94.0 | 96.1 || SumoOCR tiny (FP32) | **97.4** | 97.4 | 91.8 | 94.0 | 96.1 || SumoOCR | **97.4** | **97.9** | **93.7** | **94.6** | **96.8** || Paddle tiny rec (our pipeline) | 96.6 | 97.3 | 91.8 | 93.1 | 94.5 || PaddleOCR tiny ¹ | 96.5 | 96.8 | 92.6 | 92.9 | 94.7 || OCRia-nano-1 | 96.0 | 95.6 | 89.1 | 92.1 | 91.2 || Indra 1.2.0 | 96.4 | 96.2 | 89.2 | 92.6 | 94.4 || Tesseract 5 | 93.1 | 93.4 | 84.3 | 91.2 | 91.5 |
### OmniDocBench by page type
SumoOCR tiny runs the detector at 1,280 px by default and automatically steps up to 2,400 px when the median detected line height is below 13 detector pixels (mainly dense small-print newspapers).
| Page type (pages) | SumoOCR tiny | SumoOCR tiny (FP32) | SumoOCR | Paddle tiny rec (our pipeline) | PaddleOCR tiny ¹ | OCRia-nano-1 | Indra 1.2.0 | Tesseract 5 ||---|---|---|---|---|---|---|---|---|| academic papers (206) | 91.1 | 91.1 | **91.5** | 91.4 | 89.5 | 84.3 | 89.2 | 88.5 || books (131) | **89.5** | **89.5** | 89.4 | 89.1 | 88.5 | 81.4 | 85.4 | 88.1 || slides (120) | 95.1 | 94.9 | **95.3** | 94.8 | 94.3 | 87.3 | 93.5 | 91.2 || magazines (84) | 93.3 | 93.3 | **93.4** | 93.2 | 92.5 | 86.3 | 93.3 | 92.5 || exam papers (82) | **83.9** | **83.9** | 83.7 | 83.2 | 82.5 | 77.7 | 77.2 | 83.8 || newspapers (77) | **95.0** | **95.0** | 91.4 | 90.3 | 94.7 | 79.0 | 94.9 | 93.4 || textbooks (53) | 95.3 | 95.2 | 95.7 | 95.5 | **95.8** | 88.7 | 94.9 | 91.7 || **all (755)** | **91.9** | **91.9** | 90.9 | 90.4 | 91.0 | 82.2 | 90.0 | 90.2 || **no formulas (291)** | **95.4** | **95.4** | 92.8 | 91.9 | 94.9 | 84.7 | 95.3 | 93.1 |
### Line recognition only
Each ground-truth line cut from the page and read by each recognizer, no detector: 3,000 lines sampled from SROIE and from XFUND, every one-line entity in FUNSD. Character error rate (CER ↓) and exact lines ignore case and spaces. OCRia-nano and Indra only take whole pages.
| Recognizer | SROIE CER ↓ | SROIE exact | XFUND CER ↓ | XFUND exact | FUNSD CER ↓ | FUNSD exact ||---|---|---|---|---|---|---|| SumoOCR tiny | 2.93 % | 80.53 % | 1.77 % | 78.20 % | 4.26 % | 77.87 % || SumoOCR tiny (FP32) | 2.78 % | 81.27 % | 1.74 % | 78.60 % | 4.23 % | 77.67 % || SumoOCR | **1.55 %** | **88.43 %** | **1.52 %** | **80.43 %** | **3.49 %** | **80.52 %** || PP-OCRv6 tiny rec | 2.62 % | 81.83 % | 1.96 % | 78.37 % | 5.38 % | 71.91 % || Tesseract 5 (`--psm 7`) | 8.58 % | 63.70 % | 9.86 % | 65.33 % | 12.92 % | 50.47 % |
## Speed
One process inside a Docker container limited to 1 vCPU and 8 GB (arm64, M4 host). Every engine took turns page by page (order rotating), each warmed up first; 100 pages, 20 from each set; whole pages, detection included.
| Configuration | mean word F1 (4 benchmarks) | pages/s | ms per page, 1 core (mean / P90) | License ||---|---|---|---|---|| **SumoOCR tiny** | 90.6 | 3.55 | 281 / 546 | Apache-2.0 || SumoOCR tiny (FP32) | 90.7 | 2.20 | 455 / 901 | Apache-2.0 || OCRia-nano-1 | 85.7 | 2.15 | 464 / 734 | OCRia-nano-1 licence || Indra 1.2.0 | 89.0 | 2.07 | 484 / 857 | modified OpenRAIL-M || Paddle tiny rec (our pipeline) | 88.3 | 1.31 | 764 / 1,456 | Apache-2.0 || Tesseract 5 | 79.4 | 1.07 | 931 / 2,074 | Apache-2.0 || SumoOCR | 91.7 | 0.91 | 1,103 / 1,976 | not released || PaddleOCR 3.7, tiny (PP-OCRv6 tiny det + rec) ¹ | 87.3 | 0.41 | 2,444 / 4,527 | Apache-2.0 |
¹ PaddlePaddle has no Linux arm64 build, so PaddleOCR could not run in the 1-vCPU container: it was timed natively on the same host, one thread (`cpu_threads=1`), 100 pages (8.7x the time of SumoOCR tiny run the same way on the same pages). Paddle's CPU kernels on ARM are much slower than its x86 path.
Mean ms per page by set:
| Configuration | Business Docs | FUNSD | SROIE | XFUND | OmniDocBench ||---|---|---|---|---|---|| SumoOCR tiny | 441 | 176 | 151 | 294 | 344 || SumoOCR tiny (FP32) | 738 | 287 | 239 | 468 | 542 || OCRia-nano-1 | 602 | 318 | 328 | 416 | 656 || Indra 1.2.0 | 672 | 304 | 262 | 499 | 683 || Paddle tiny rec (our pipeline) | 1,206 | 457 | 473 | 794 | 890 || Tesseract 5 | 1,584 | 309 | 475 | 1,194 | 1,092 || SumoOCR | 1,421 | 914 | 737 | 1,041 | 1,402 |
SumoOCR tiny is the fastest engine on every benchmark set: synthetic-calibrated INT8 QDQ quantization, standard ONNX opset-20 `Gelu(tanh)` fusion, and adaptive 1,280 → 2,400 px detection bring one-core page time down to 281 ms (3.55 pages/s) on ONNX Runtime (455 ms / 2.20 pages/s in pure FP32).
## Limitations of SumoOCR tiny
- **Latin script only.** The 758 characters cover English and European Latin-script languages; Cyrillic, Greek, Arabic, Hebrew, Chinese, Japanese, Korean and Indic scripts are not recognized.- **Printed text.** Handwriting was not a training target and was not measured here.- **Lines, not documents.** It returns text lines with boxes and confidences: no layout blocks, tables, reading order or key-value structure (the benchmarks put every engine's lines in reading order with one shared routine).- **Receipts and low-resolution scans are its weakest pages.** SROIE 91.3 and FUNSD 83.8 word F1, 3.1 and 1.8 points behind SumoOCR. On receipt line crops the base PP-OCRv6 tiny reads slightly better (2.62 % vs 2.93 % character errors).- **Post-training INT8 quantization.** Both ONNX models use synthetic-calibrated INT8 QDQ quantization (keeping sensitive layers in FP32) for fast CPU inference at 1.8 MB total size; word F1 is within 0.2 points of FP32 on every benchmark (0.1 on the four-benchmark mean).
## Systems compared
| System | What ran | Model files | License ||---|---|---|---|| SumoOCR tiny | `sumoocr` package defaults: PP-OCRv6 tiny detector (INT8 QDQ, adaptive 1,280 → 2,400 px) + SumoOCR tiny recognizer (INT8 QDQ, opset-20 Gelu), ONNX Runtime | 0.7 MB + 1.1 MB (0.43M + 0.61M params) | Apache-2.0 || SumoOCR tiny (FP32) | same pipeline and adaptive 1,280 → 2,400 px detection with unquantized FP32 ONNX opset-20 `Gelu(tanh)` models, ONNX Runtime | 1.8 MB + 2.4 MB (0.43M + 0.61M params) | Apache-2.0 || Paddle tiny rec (our pipeline) | PP-OCRv6 tiny detector (1,600 px) + the stock PP-OCRv6 tiny recognizer (Latin head, its native height 48, space bias 3.0), FP32, OpenVINO: the base SumoOCR tiny was fine-tuned from | 1.8 + 2.4 MB | Apache-2.0 || PaddleOCR 3.7 | Paddle's own package (PaddlePaddle 3.3.1), `cpu_threads=1`: PP-OCRv6 tiny detector + recognizer, with its page orientation, unwarping and line orientation models off. Run natively: PaddlePaddle has no Linux arm64 build for the container. | 183 MB downloaded | Apache-2.0 || OCRia-nano-1 | LlamaIndex, through LiteParse 2.21.3 (`num_workers=1`, word boxes on) | 72 MB package (8.1M params + runtime) | OCRia-nano-1 licence (free under $2M revenue / funding) || Indra 1.2.0 | Datalab `indra-ocr`, OCR mode, `threads=1`, math on (its default; same text on business pages) | 109 MB | code Apache-2.0, weights modified OpenRAIL-M (free under $5M; no competing use) || Tesseract 5 | `--oem 1 --psm 3`, tessdata_fast, told the page's language | 1-4 MB per language | Apache-2.0 |
## Datasets
| Set | Pages | What | Ground truth ||---|---|---|---|| FUNSD, test | 50 | noisy 1990s scanned forms, English, low resolution | entity text || SROIE 2019, task 1 test | 347 | scanned receipts | line text, upper-cased (scoring ignores case) || XFUND, validation: de / es / fr / it / pt | 250 | forms in five languages | entity text || OmniDocBench v1.5, English | 755 (291 without formulas) | papers, books, slides, magazines, exams, newspapers, textbooks | text blocks, titles, headers, captions, table cells; formula, figure and masked regions left out (and every engine's lines inside them dropped) || Business Docs | 41 | Public and synthetic business documents: 24 synthetic invoices, statements, holdings, forms and letters in 16 languages (clean, scanned, faxed, photographed) + 17 public US federal pages (IRS, Federal Register, Federal Reserve) | exact text / PDF text layer; 3 public federal PDF pages also appear in the training set (without them: SumoOCR tiny 98.8, Indra 98.2, OCRia-nano 97.9) |
None of the four public benchmarks is in SumoOCR tiny's training data. PP-OCRv6's pretraining data is not published; it is the starting point of both PP-OCRv6 tiny and SumoOCR tiny.
## Method
- **Same input for every engine**: the benchmark's page images; CPU, one thread; each engine's published defaults.- **Scoring**: each engine's lines are put in reading order by one shared routine, then scored with the SumoOCR blog's scorer: word F1 is a case-insensitive bag-of-words F1, so it ignores reading order. Paired page bootstrap, 1,000 draws.- **Ground truth**: FUNSD's annotations are noisy and SROIE's are upper-cased (compare engines, not absolute values); OmniDocBench's inline formulas are removed from the ground truth.- **Tesseract** was told each page's language; the other engines read every page with one multilingual model.- **Speed** is one host (arm64, M4); x86 was not measured in this run.- **Licences**: the benchmark sets are for research use (report scores, don't redistribute pages).
## Reproduce
The datasets are public: FUNSD (guillaumejaume.github.io/FUNSD), SROIE 2019 task 1 test (rrc.cvc.uab.es, mirrored as huggingface.co/datasets/rth/sroie-2019-v2), XFUND (github.com/doc-analysis/XFUND, validation sets) and OmniDocBench v1.5 (huggingface.co/datasets/opendatalab/OmniDocBench). Each engine ran as listed under [Systems compared](#systems-compared); `sumoocr` with its defaults is SumoOCR tiny. The evaluation harness is not part of this repository.1234567891011"""Read a page and print its lines with confidence and box. python examples/ocr_page.py [image]"""import osimport sys
from sumoocr import SumoOCR
path = sys.argv[1] if len(sys.argv) > 1 else os.path.join(os.path.dirname(__file__), "invoice.png")ocr = SumoOCR()for line in ocr(path): x0, y0 = line.box[0] print(f"{line.conf:.2f} ({x0:6.0f}, {y0:6.0f}) {line.text}")12345678910111213141516171819202122232425262728293031323334353637383940414243[build-system]requires = ["setuptools>=68", "wheel"]build-backend = "setuptools.build_meta"
[project]name = "sumoocr"version = "0.1.0"description = "SumoOCR tiny: a 1M-parameter CPU OCR pipeline for business documents in Latin-script languages"dynamic = ["readme"] # built from README.md by setup.pylicense = "Apache-2.0"license-files = ["LICENSE", "NOTICE"]authors = [{ name = "Docsumo" }]requires-python = ">=3.9"dependencies = [ "numpy>=1.23", "opencv-python-headless>=4.8", "onnxruntime>=1.18",]keywords = ["ocr", "text-recognition", "documents", "invoices", "receipts", "onnx", "cpu"]classifiers = [ "Programming Language :: Python :: 3", "Operating System :: OS Independent", "Intended Audience :: Developers", "Topic :: Scientific/Engineering :: Image Recognition",]
[project.optional-dependencies]openvino = ["openvino>=2024.0"]pil = ["pillow"]test = ["pytest"]
[project.scripts]sumoocr = "sumoocr.cli:main"
[project.urls]Homepage = "https://huggingface.co/docsumo/sumoOCR-tiny""Benchmark report" = "https://huggingface.co/docsumo/sumoOCR-tiny/blob/main/REPORT.md"
[tool.setuptools]packages = ["sumoocr"]
[tool.setuptools.package-data]sumoocr = ["models/*.onnx", "models/*.json"]12345678910111213141516171819202122232425"""PyPI description = README.md without the Hugging Face model-card header, with repository links made absolute.Everything else is in pyproject.toml."""import refrom pathlib import Path
from setuptools import setup
REPO = "https://huggingface.co/docsumo/sumoOCR-tiny"
def _absolute(m: "re.Match") -> str: image, label, target = m.group(1), m.group(2), m.group(3) kind = "resolve" if image else ("blob" if "." in target.rsplit("/", 1)[-1] else "tree") return f"{image}[{label}]({REPO}/{kind}/main/{target})"
text = Path(__file__).with_name("README.md").read_text(encoding="utf-8")text = re.sub(r"\A---\n.*?\n---\n+", "", text, flags=re.S)text = re.sub(r"(!?)\[([^\]]*)\]\((?!https?://|#)([^)]+)\)", _absolute, text)
setup( long_description=text, long_description_content_type="text/markdown", options={"sdist": {"owner": "root", "group": "root"}}, # no local user name in the source archive)1234567891011"""SumoOCR tiny: fast CPU OCR for business documents in Latin-script languages.
from sumoocr import SumoOCR ocr = SumoOCR() for line in ocr("invoice.png"): print(line.text, line.conf, line.box)"""from .ocr import Line, SumoOCR
__all__ = ["SumoOCR", "Line"]__version__ = "0.1.0"12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364"""Model runtimes: ONNX Runtime (default) or OpenVINO (`pip install sumoocr[openvino]`), CPU."""from __future__ import annotations
import osfrom typing import Optional
import numpy as np
BACKENDS = ("onnxruntime", "openvino")
class ORTModel: def __init__(self, path: str, threads: Optional[int] = None, arena: bool = True): import onnxruntime as ort
so = ort.SessionOptions() so.execution_mode = ort.ExecutionMode.ORT_SEQUENTIAL if threads: so.intra_op_num_threads = int(threads) so.inter_op_num_threads = 1 if int(threads) == 1: so.add_session_config_entry("session.intra_op.allow_spinning", "0") so.enable_cpu_mem_arena = bool(arena) so.log_severity_level = 3 self.sess = ort.InferenceSession(path, so, providers=["CPUExecutionProvider"]) self._in = self.sess.get_inputs()[0].name
def __call__(self, x: np.ndarray) -> np.ndarray: return self.sess.run(None, {self._in: np.ascontiguousarray(x, dtype=np.float32)})[0]
class OVModel: def __init__(self, path: str, threads: Optional[int] = None, fix_height: int = 0): os.environ.setdefault("CI", "true") # openvino_telemetry: never prompt import platform import openvino as ov
core = ov.Core() model = core.read_model(path) if fix_height: # recognizer: fixed height, dynamic batch and width inp = model.inputs[0] ps = inp.get_partial_shape() if ps.rank.is_static and len(ps) == 4 and ps[2].is_dynamic: model.reshape({inp.get_any_name(): ov.PartialShape([-1, ps[1], int(fix_height), -1])}) props = {"NUM_STREAMS": 1, "PERFORMANCE_HINT": "LATENCY", "INFERENCE_PRECISION_HINT": "f32"} if any(op.get_type_name() == "FakeQuantize" for op in model.get_ops()) and \ platform.machine().lower() not in ("x86_64", "amd64"): props["LP_TRANSFORMS_MODE"] = False if threads: props["INFERENCE_NUM_THREADS"] = int(threads) self.req = core.compile_model(model, "CPU", props).create_infer_request()
def __call__(self, x: np.ndarray) -> np.ndarray: self.req.infer({0: np.ascontiguousarray(x, dtype=np.float32)}, share_inputs=True) return self.req.get_output_tensor(0).data.copy()
def load_model(path: str, backend: str = "onnxruntime", threads: Optional[int] = None, fix_height: int = 0, arena: bool = True): if backend == "onnxruntime": return ORTModel(path, threads, arena=arena) if backend == "openvino": return OVModel(path, threads, fix_height) raise ValueError(f"backend must be one of {BACKENDS}, not {backend!r}")12345678910111213141516171819202122232425262728293031323334"""sumoocr IMAGE... [--format text|json] [--backend onnxruntime|openvino] [--threads N] [--max-side PX]"""from __future__ import annotations
import argparseimport jsonimport sys
def main(argv=None) -> int: ap = argparse.ArgumentParser(prog="sumoocr", description="SumoOCR tiny: text lines of page images, on CPU.") ap.add_argument("images", nargs="+", help="page images (PNG, JPEG, TIFF, BMP, WebP)") ap.add_argument("--format", choices=("text", "json"), default="text", help="text: one line per text line; json: one object per image with lines, boxes, confidences") ap.add_argument("--backend", choices=("onnxruntime", "openvino"), default="onnxruntime") ap.add_argument("--threads", type=int, default=None, help="CPU threads per model (default: the runtime's)") ap.add_argument("--max-side", type=int, default=1280, help="detector's long-side cap in px (dense small print auto-scales to 2400)") a = ap.parse_args(argv) from . import SumoOCR
ocr = SumoOCR(backend=a.backend, threads=a.threads, max_side=a.max_side) for path in a.images: lines = ocr(path) if a.format == "json": print(json.dumps({"image": path, "lines": [ln.to_dict() for ln in lines]}, ensure_ascii=False)) else: if len(a.images) > 1: print(f"==> {path} <==") print("\n".join(ln.text for ln in lines)) return 0
if __name__ == "__main__": sys.exit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132"""Text detection: input scaling, DB post-processing, reading order, box levelling (PP-OCRv6 tiny detector)."""from __future__ import annotations
import mathfrom typing import List, Tuple
import cv2import numpy as np
MEAN = STD = np.array([0.5, 0.5, 0.5], np.float32) # detector input: (x / 255 - 0.5) / 0.5, BGR
def det_input_size(h: int, w: int, scale: float, max_pixels: float) -> Tuple[int, int]: """(nh, nw): multiples of 32 near (h * scale, w * scale), capped at max_pixels.""" if max_pixels and h * w * scale * scale > max_pixels: scale = math.sqrt(max_pixels / float(h * w)) return max(32, int(round(h * scale / 32.0)) * 32), max(32, int(round(w * scale / 32.0)) * 32)
def preprocess(img: np.ndarray, nh: int, nw: int, rgb: bool = False) -> np.ndarray: """Page (BGR, or RGB when rgb=True) -> 1 x 3 x nh x nw float32 in the detector's BGR order.""" return cv2.dnn.blobFromImage(img, scalefactor=2.0 / 255.0, size=(nw, nh), mean=(127.5, 127.5, 127.5), swapRB=rgb, crop=False)
def _order_quad(pts: np.ndarray) -> np.ndarray: """4 points -> top-left, top-right, bottom-right, bottom-left.""" pts = pts[np.argsort(pts[:, 0], kind="stable")] left, right = pts[:2], pts[2:] tl, bl = (left[0], left[1]) if left[0][1] <= left[1][1] else (left[1], left[0]) tr, br = (right[0], right[1]) if right[0][1] <= right[1][1] else (right[1], right[0]) return np.array([tl, tr, br, bl], dtype=np.float32)
def db_postprocess(prob: np.ndarray, thresh: float = 0.3, box_thresh: float = 0.5, unclip_ratio: float = 1.6, max_candidates: int = 5000, min_size: float = 3.0) -> Tuple[List[np.ndarray], List[float]]: """DB probability map (H x W) -> quads (map pixels) and box scores: binarize, 2 x 2 dilation, contours, minAreaRect, mean probability inside the box, unclip. Unclipping a w x h rectangle by d = area * ratio / perimeter is done analytically (the (w + 2d) x (h + 2d) rectangle, same centre and angle).""" bitmap = cv2.dilate((prob > thresh).astype(np.uint8), np.ones((2, 2), np.uint8)) contours, _ = cv2.findContours(bitmap, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE) H, W = prob.shape quads: List[np.ndarray] = [] scores: List[float] = [] for cnt in contours[:max_candidates]: (cx, cy), (rw, rh), ang = cv2.minAreaRect(cnt) if min(rw, rh) < min_size: continue pts = cv2.boxPoints(((cx, cy), (rw, rh), ang)) xmin = int(np.clip(np.floor(pts[:, 0].min()), 0, W - 1)) xmax = int(np.clip(np.ceil(pts[:, 0].max()), 0, W - 1)) ymin = int(np.clip(np.floor(pts[:, 1].min()), 0, H - 1)) ymax = int(np.clip(np.ceil(pts[:, 1].max()), 0, H - 1)) mask = np.zeros((ymax - ymin + 1, xmax - xmin + 1), np.uint8) q = pts.copy() q[:, 0] -= xmin q[:, 1] -= ymin cv2.fillPoly(mask, [q.astype(np.int32)], 1) score = cv2.mean(prob[ymin:ymax + 1, xmin:xmax + 1], mask)[0] if score < box_thresh: continue d = rw * rh * unclip_ratio / (2.0 * (rw + rh)) nw_, nh_ = rw + 2 * d, rh + 2 * d if min(nw_, nh_) < min_size + 2: continue quads.append(_order_quad(cv2.boxPoints(((cx, cy), (nw_, nh_), ang)))) scores.append(float(score)) return quads, scores
def sort_reading_order(quads: List[np.ndarray], y_tol: float = 0.5) -> List[int]: """Indices top to bottom, then left to right within a line (a box joins the current line when its centre is within y_tol x the line's height of the line's).""" if not quads: return [] cy = [float(q[:, 1].mean()) for q in quads] hh = [max(1.0, float(q[:, 1].max() - q[:, 1].min())) for q in quads] cx = [float(q[:, 0].min()) for q in quads] lines: List[List[int]] = [] ref = None for i in sorted(range(len(quads)), key=lambda i: (cy[i], cx[i])): if lines and abs(cy[i] - ref[0]) <= y_tol * ref[1]: lines[-1].append(i) else: lines.append([i]) ref = (cy[i], hh[i]) return [i for ln in lines for i in sorted(ln, key=lambda j: cx[j])]
def _mod90(a: float) -> float: return (a + 45.0) % 90.0 - 45.0
def level_quads(quads: List[np.ndarray], max_growth: float, min_deg: float = 1.0, ref_lines: int = 3, neighbours: int = 10, square: float = 1.5) -> List[np.ndarray]: """Returned boxes with the odd tilted ones levelled (output only: lines are read from the original boxes). A box more than min_deg off both the page angle and the length-weighted median angle of its nearest line-like neighbours is replaced by its bounding rectangle along that angle, when the rectangle is at most max_growth x its area (mixed-size glyphs, e.g. a small field number before a large letter, tilt minAreaRect boxes).""" if max_growth <= 0 or len(quads) < ref_lines: return list(quads) q = np.array(quads, np.float64) e1, e2 = q[:, 1] - q[:, 0], q[:, 3] - q[:, 0] l1, l2 = np.hypot(e1[:, 0], e1[:, 1]), np.hypot(e2[:, 0], e2[:, 1]) ang = np.array([_mod90(math.degrees(math.atan2(y, x))) for x, y in e1]) cen = q.mean(axis=1) lines = np.flatnonzero(np.maximum(l1, l2) >= 3.0 * np.minimum(l1, l2)) if len(lines) < ref_lines: return list(quads) page = float(np.median(ang[lines])) out = list(quads) for i in np.flatnonzero([abs(_mod90(a - page)) > min_deg for a in ang]): near = lines[np.argsort(((cen[lines] - cen[i]) ** 2).sum(axis=1))] near = near[near != i][:neighbours] off = np.array([_mod90(a - page) for a in ang[near]]) o = np.argsort(off) cum = np.cumsum(np.maximum(l1, l2)[near][o]) ref = page + float(off[o][np.searchsorted(cum, cum[-1] / 2.0)]) if abs(_mod90(ang[i] - ref)) <= min_deg: continue t = math.radians(ref) u, v = np.array([math.cos(t), math.sin(t)]), np.array([-math.sin(t), math.cos(t)]) s, r = q[i] @ u, q[i] @ v if max(l1[i], l2[i]) < square * min(l1[i], l2[i]): # one glyph: no text direction, level it in place cs, cr = cen[i] @ u, cen[i] @ v s, r = np.array([cs - l1[i] / 2, cs + l1[i] / 2]), np.array([cr - l2[i] / 2, cr + l2[i] / 2]) elif (s.max() - s.min()) * (r.max() - r.min()) > max_growth * l1[i] * l2[i]: continue out[i] = _order_quad(np.array([s0 * u + r0 * v for s0, r0 in ((s.min(), r.min()), (s.max(), r.min()), (s.max(), r.max()), (s.min(), r.max()))], np.float32)) return out1234567{ "H": 40, "time_stride": 4, "classes": 758, "rec_input": "BGR line crop resized to height H (aspect kept), (x / 255 - 0.5) / 0.5, N x 3 x H x W; output softmax N x W/4 x classes, class 0 = CTC blank", "det_input": "BGR page resized to multiples of 32, (x / 255 - 0.5) / 0.5, 1 x 3 x h x w; output text probability map 1 x 1 x h x w"}123version https://git-lfs.github.com/spec/v1oid sha256:78bed24595282cb897e1cd51e09fb620b85a0f8a7551d81cd640c49e933bf86esize 7526171["blank", "!", "\"", "#", "$", "%", "&", "'", "(", ")", "*", "+", ",", "-", ".", "/", ":", ";", "<", "=", ">", "?", "@", "[", "\\", "]", "^", "_", "`", "{", "|", "}", "~", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "¢", "£", "¤", "¥", "¦", "§", "¨", "©", "ª", "«", "¬", "®", "¯", "°", "±", "²", "³", "´", "µ", "¶", "·", "¸", "¹", "º", "»", "¼", "½", "¾", "¿", "À", "Á", "Â", "Ã", "Ä", "Å", "Æ", "Ç", "È", "É", "Ê", "Ë", "Ì", "Í", "Î", "Ï", "Ð", "Ñ", "Ò", "Ó", "Ô", "Õ", "Ö", "×", "Ø", "Ù", "Ú", "Û", "Ü", "Ý", "Þ", "ß", "à", "á", "â", "ã", "ä", "å", "æ", "ç", "è", "é", "ê", "ë", "ì", "í", "î", "ï", "ð", "ñ", "ò", "ó", "ô", "õ", "ö", "÷", "ø", "ù", "ú", "û", "ü", "ý", "þ", "ÿ", "Ā", "ā", "Ă", "ă", "Ą", "ą", "Ć", "ć", "Ĉ", "ĉ", "Ċ", "ċ", "Č", "č", "Ď", "ď", "Đ", "đ", "Ē", "ē", "Ĕ", "ĕ", "Ė", "ė", "Ę", "ę", "Ě", "ě", "Ĝ", "ĝ", "Ğ", "ğ", "Ġ", "ġ", "Ģ", "ģ", "Ĥ", "ĥ", "Ħ", "ħ", "Ĩ", "ĩ", "Ī", "ī", "Ĭ", "ĭ", "Į", "į", "İ", "ı", "IJ", "ij", "Ĵ", "ĵ", "Ķ", "ķ", "ĸ", "Ĺ", "ĺ", "Ļ", "ļ", "Ľ", "ľ", "Ŀ", "ŀ", "Ł", "ł", "Ń", "ń", "Ņ", "ņ", "Ň", "ň", "ʼn", "Ŋ", "ŋ", "Ō", "ō", "Ŏ", "ŏ", "Ő", "ő", "Œ", "œ", "Ŕ", "ŕ", "Ŗ", "ŗ", "Ř", "ř", "Ś", "ś", "Ŝ", "ŝ", "Ş", "ş", "Š", "š", "Ţ", "ţ", "Ť", "ť", "Ŧ", "ŧ", "Ũ", "ũ", "Ū", "ū", "Ŭ", "ŭ", "Ů", "ů", "Ű", "ű", "Ų", "ų", "Ŵ", "ŵ", "Ŷ", "ŷ", "Ÿ", "Ź", "ź", "Ż", "ż", "Ž", "ž", "ſ", "ƀ", "Ɓ", "Ƃ", "ƃ", "Ƅ", "ƅ", "Ɔ", "Ƈ", "ƈ", "Ɖ", "Ɗ", "Ƌ", "ƌ", "ƍ", "Ǝ", "Ə", "Ɛ", "Ƒ", "ƒ", "Ɠ", "Ɣ", "ƕ", "Ɩ", "Ɨ", "Ƙ", "ƙ", "ƚ", "ƛ", "Ɯ", "Ɲ", "ƞ", "Ɵ", "Ơ", "ơ", "Ƣ", "ƣ", "Ƥ", "ƥ", "Ʀ", "Ƨ", "ƨ", "Ʃ", "ƪ", "ƫ", "Ƭ", "ƭ", "Ʈ", "Ư", "ư", "Ʊ", "Ʋ", "Ƴ", "ƴ", "Ƶ", "ƶ", "Ʒ", "Ƹ", "ƹ", "ƺ", "ƻ", "Ƽ", "ƽ", "ƾ", "ƿ", "ǀ", "ǁ", "ǂ", "ǃ", "DŽ", "Dž", "dž", "LJ", "Lj", "lj", "NJ", "Nj", "nj", "Ǎ", "ǎ", "Ǐ", "ǐ", "Ǒ", "ǒ", "Ǔ", "ǔ", "Ǖ", "ǖ", "Ǘ", "ǘ", "Ǚ", "ǚ", "Ǜ", "ǜ", "ǝ", "Ǟ", "ǟ", "Ǡ", "ǡ", "Ǣ", "ǣ", "Ǥ", "ǥ", "Ǧ", "ǧ", "Ǩ", "ǩ", "Ǫ", "ǫ", "Ǭ", "ǭ", "Ǯ", "ǯ", "ǰ", "DZ", "Dz", "dz", "Ǵ", "ǵ", "Ƕ", "Ƿ", "Ǹ", "ǹ", "Ǻ", "ǻ", "Ǽ", "ǽ", "Ǿ", "ǿ", "Ȁ", "ȁ", "Ȃ", "ȃ", "Ȅ", "ȅ", "Ȇ", "ȇ", "Ȉ", "ȉ", "Ȋ", "ȋ", "Ȍ", "ȍ", "Ȏ", "ȏ", "Ȑ", "ȑ", "Ȓ", "ȓ", "Ȕ", "ȕ", "Ȗ", "ȗ", "Ș", "ș", "Ț", "ț", "Ȝ", "ȝ", "Ȟ", "ȟ", "Ƞ", "ȡ", "Ȣ", "ȣ", "Ȥ", "ȥ", "Ȧ", "ȧ", "Ȩ", "ȩ", "Ȫ", "ȫ", "Ȭ", "ȭ", "Ȯ", "ȯ", "Ȱ", "ȱ", "Ȳ", "ȳ", "ȴ", "ȵ", "ȶ", "ȷ", "ȸ", "ȹ", "Ⱥ", "Ȼ", "ȼ", "Ƚ", "Ⱦ", "ȿ", "ɀ", "Ɂ", "ɂ", "Ƀ", "Ʉ", "Ʌ", "Ɇ", "ɇ", "Ɉ", "ɉ", "Ɋ", "ɋ", "Ɍ", "ɍ", "Ɏ", "ɏ", "Ạ", "ồ", "–", "—", "―", "‖", "‘", "’", "“", "”", "†", "‡", "•", "‥", "…", "‰", "′", "″", "※", "⁎", "₠", "₡", "₢", "₣", "₤", "₥", "₦", "₧", "₨", "₩", "₪", "₫", "€", "₭", "₮", "₯", "₰", "₱", "₲", "₳", "₴", "₵", "₶", "₷", "₸", "₹", "₺", "₻", "₼", "₽", "₾", "₿", "℃", "℉", "ℎ", "ℏ", "ℑ", "℘", "ℜ", "™", "℧", "Å", "ℵ", "ℶ", "ℷ", "ℸ", "ℹ", "⅀", "Ⅰ", "Ⅱ", "Ⅲ", "Ⅳ", "Ⅴ", "Ⅵ", "Ⅶ", "Ⅷ", "Ⅸ", "Ⅹ", "Ⅺ", "Ⅻ", "ⅰ", "ⅱ", "ⅲ", "ⅳ", "ⅴ", "ⅵ", "ⅶ", "ⅷ", "ⅸ", "ⅹ", "ⅺ", "ⅻ", "ⅼ", "ↀ", "ↁ", "ↂ", "←", "↑", "→", "↓", "↔", "↕", "↖", "↗", "↘", "↙", "↚", "↛", "↜", "↝", "↞", "↟", "↠", "↡", "↢", "↣", "↤", "↥", "↦", "↧", "↨", "↩", "↪", "↫", "↬", "↭", "↮", "↯", "↰", "↱", "↲", "↳", "↴", "↵", "↶", "↷", "↸", "↹", "↺", "↻", "↼", "↽", "↾", "↿", "⇀", "⇁", "⇂", "⇃", "⇄", "⇅", "⇆", "⇇", "⇈", "⇉", "⇊", "⇋", "⇌", "⇍", "⇎", "⇏", "⇐", "⇑", "⇒", "⇓", "⇔", "⇕", "⇖", "⇗", "⇘", "⇙", "⇚", "⇛", "⇜", "⇝", "⇞", "⇟", "⇠", "⇡", "⇢", "⇣", "⇤", "⇥", "⇦", "⇧", "⇨", "⇩", "⇪", "⇫", "⇬", "⇭", "⇮", "⇯", "⇰", "⇱", "⇲", "⇳", "⇴", "⇵", "⇶", "⇷", "⇸", "⇹", "⇺", "⇻", "⇼", "⇽", "⇾", "⇿", "∆", "∑", "−", "√", "∞", "≈", "≠", "≤", "≥", "☐", "☑", "☒", "□", "■", "●", "○", "◆", "◇", "✓", "✔", "✘", "„", "‚", "‹", "›", " "]123version https://git-lfs.github.com/spec/v1oid sha256:8db35a6113fab67651cda4f146899ca8fc4a0475d95f324b03964ec6519d2d2dsize 1148133123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240"""SumoOCR tiny: a page -> its text lines (detector + recognizer), or one line crop -> its text."""from __future__ import annotations
import jsonimport osfrom dataclasses import asdict, dataclassfrom typing import Any, List, Optional, Sequence, Tuple, Union
import cv2import numpy as np
from .backend import load_modelfrom .det import db_postprocess, det_input_size, level_quads, preprocess, sort_reading_orderfrom .rec import CTCDecoder, crop_line, recognize
MODEL_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "models")
@dataclassclass Line: """One text line: its text, mean character confidence (0-1) and box (4 [x, y] points, clockwise from the top-left, in pixels of the input image).""" text: str conf: float box: List[List[float]]
def to_dict(self) -> dict: return asdict(self)
def _rotate(img: np.ndarray, deg: int) -> np.ndarray: """Turn the image clockwise by deg (90 / 180 / 270).""" if deg == 90: return cv2.rotate(img, cv2.ROTATE_90_CLOCKWISE) if deg == 180: return cv2.rotate(img, cv2.ROTATE_180) if deg == 270: return cv2.rotate(img, cv2.ROTATE_90_COUNTERCLOCKWISE) return img
def _rotate_pts(q: np.ndarray, deg: int, h: int, w: int) -> np.ndarray: """Point coordinates after turning an h x w image clockwise by deg (same point order).""" x, y = q[:, 0], q[:, 1] if deg == 180: return np.stack([w - x, h - y], 1).astype(np.float32) if deg == 90: return np.stack([h - y, x], 1).astype(np.float32) if deg == 270: return np.stack([y, w - x], 1).astype(np.float32) return q
# after a turn by deg, the new tl, tr, br, bl are these points of _rotate_pts_QUAD_ORDER = {180: [2, 3, 0, 1], 90: [3, 0, 1, 2], 270: [1, 2, 3, 0]}
def _rotate_quad(q: np.ndarray, deg: int, h: int, w: int) -> np.ndarray: """Box coordinates after turning an h x w image clockwise by deg (re-ordered tl, tr, br, bl).""" if deg in _QUAD_ORDER: return _rotate_pts(q, deg, h, w)[_QUAD_ORDER[deg]] return q
class SumoOCR: """Page OCR with SumoOCR tiny.
ocr = SumoOCR() # ONNX Runtime on CPU; backend="openvino" needs `pip install sumoocr[openvino]` lines = ocr("invoice.png") # a path, an H x W x 3 uint8 array (BGR, as cv2.imread) or a PIL image text, conf = ocr.read_line(crop) # one line crop (any height)
The defaults are the settings the benchmarks were run with. max_side caps the long side of the page the detector sees (1,280 px by default, automatically stepping up to 2,400 px on dense small print such as newspapers when adaptive=True). text_score drops lines whose mean character confidence is below it. threads: CPU threads per model (None = the runtime's default)."""
def __init__(self, backend: str = "onnxruntime", threads: Optional[int] = None, model_dir: str = MODEL_DIR, det_model: Optional[str] = None, rec_model: Optional[str] = None, max_side: int = 1280, min_side: int = 0, max_det_pixels: float = 6.0e6, det_thresh: float = 0.3, box_thresh: float = 0.4, unclip_ratio: float = 1.6, text_score: float = 0.85, space_bias: float = 2.0, box_level: float = 1.5, orient: bool = True, orient_conf: float = 0.92, orient_sample: int = 10, adaptive: bool = True, adaptive_med_h: float = 13.0, adaptive_max_side: int = 2400, batch: int = 1): if threads: cv2.setNumThreads(int(threads)) cfg = json.load(open(os.path.join(model_dir, "config.json"), encoding="utf-8")) self.height = int(cfg["H"]) det_path = det_model or os.path.join(model_dir, "det.onnx") rec_path = rec_model or os.path.join(model_dir, "rec.onnx") self.det = load_model(det_path, backend, threads, arena=True) self.rec = load_model(rec_path, backend, threads, fix_height=self.height, arena=False) with open(os.path.join(model_dir, "rec.classes.json"), encoding="utf-8") as fh: self.decoder = CTCDecoder(json.load(fh), space_bias, case_conf=True, space_conf=True) self.max_side, self.min_side, self.max_det_pixels = max_side, min_side, max_det_pixels self.det_thresh, self.box_thresh, self.unclip_ratio = det_thresh, box_thresh, unclip_ratio self.text_score, self.box_level, self.batch = text_score, box_level, batch self.orient, self.orient_conf, self.orient_sample = orient, orient_conf, orient_sample self.adaptive, self.adaptive_med_h, self.adaptive_max_side = adaptive, adaptive_med_h, adaptive_max_side self._rgb = False
# ------------------------------------------------------------------ input @staticmethod def _load(image: Union[str, os.PathLike, np.ndarray, Any]) -> Tuple[np.ndarray, bool]: """-> (H x W x 3 uint8, is_rgb)""" if isinstance(image, (str, os.PathLike)): img = cv2.imdecode(np.fromfile(str(image), np.uint8), cv2.IMREAD_COLOR) if img is None: raise ValueError(f"cannot read image {image!s}") return img, False if not isinstance(image, np.ndarray): # PIL image return np.asarray(image.convert("RGB")), True if image.ndim == 2: return cv2.cvtColor(image, cv2.COLOR_GRAY2BGR), False if image.shape[2] == 4: return cv2.cvtColor(image, cv2.COLOR_BGRA2BGR), False return image, False
# -------------------------------------------------------------- detection def _det_scale(self, h: int, w: int) -> float: long_, short = max(h, w), min(h, w) s = min(1.0, self.max_side / float(long_)) if self.max_side else 1.0 if self.min_side and short * s < self.min_side: s = self.min_side / float(short) if self.max_side and long_ * s > self.max_side * 1.5: s = self.max_side * 1.5 / float(long_) return s
def _detect_at(self, img: np.ndarray, scale: float) -> Tuple[List[np.ndarray], int, int]: h, w = img.shape[:2] nh, nw = det_input_size(h, w, scale, self.max_det_pixels) prob = self.det(preprocess(img, nh, nw, self._rgb))[0, 0] quads, _ = db_postprocess(prob, self.det_thresh, self.box_thresh, self.unclip_ratio) out = [] sx, sy = w / float(nw), h / float(nh) for q in quads: q = q * np.array([sx, sy], np.float32) q[:, 0] = np.clip(q[:, 0], 0, w - 1) q[:, 1] = np.clip(q[:, 1], 0, h - 1) if np.linalg.norm(q[0] - q[1]) > 3 and np.linalg.norm(q[0] - q[3]) > 3: out.append(q) return out, nh, nw
def _detect(self, img: np.ndarray) -> List[np.ndarray]: h, w = img.shape[:2] scale = self._det_scale(h, w) out, nh, nw = self._detect_at(img, scale) if self.adaptive and self.adaptive_med_h > 0 and len(out) >= 10 and self.max_side and \ self.adaptive_max_side > self.max_side and max(h, w) > self.max_side * 1.25: s1 = nh / float(h) hs = [min(float(np.linalg.norm(q[0] - q[1])), float(np.linalg.norm(q[0] - q[3]))) * s1 for q in out] hs = [v for v in hs if v >= 3.0] if len(hs) >= 10 and float(np.median(hs)) < self.adaptive_med_h: s2 = min(1.0, self.adaptive_max_side / float(max(h, w))) if s2 > scale * 1.15: out, _, _ = self._detect_at(img, s2) return out
# ------------------------------------------------------------ recognition def _crops(self, img: np.ndarray, quads: Sequence[np.ndarray]) -> Tuple[List[np.ndarray], List[int]]: crops, keep = [], [] for i, q in enumerate(quads): cr = crop_line(img, q, self.height) if cr is not None and cr.shape[1] >= 2: crops.append(cr) keep.append(i) return crops, keep
def _read(self, crops: List[np.ndarray]) -> List[Tuple[str, float, float]]: return recognize(self.rec, self.decoder, crops, batch=self.batch, rgb=self._rgb)
# ------------------------------------------------------------ orientation @staticmethod def _sideways(quads: Sequence[np.ndarray]) -> bool: ratios = [] for q in quads: w_q, h_q = np.linalg.norm(q[0] - q[1]), np.linalg.norm(q[0] - q[3]) if h_q > 0 and (w_q / h_q >= 1.5 or w_q / h_q <= 1 / 1.5): ratios.append(w_q / h_q) return len(ratios) >= 8 and sum(r < 1 for r in ratios) / len(ratios) > 0.5
def _sample(self, quads: Sequence[np.ndarray]) -> List[int]: areas = [float(np.linalg.norm(q[0] - q[1]) * np.linalg.norm(q[0] - q[3])) for q in quads] return sorted(range(len(quads)), key=lambda i: -areas[i])[: self.orient_sample]
def _flip_better(self, crops: List[np.ndarray]) -> bool: """True when the crops read better turned by 180 degrees.""" if not crops: return False a = self._read(crops) b = self._read([np.ascontiguousarray(c[::-1, ::-1]) for c in crops]) wins = sum(rb[1] > ra[1] + 0.05 for ra, rb in zip(a, b)) return wins > len(crops) / 2 and np.mean([r[1] for r in b]) > np.mean([r[1] for r in a]) + 0.05
# -------------------------------------------------------------------- run def __call__(self, image: Union[str, os.PathLike, np.ndarray, Any]) -> List[Line]: """The page's text lines in reading order.""" img, self._rgb = self._load(image) h, w = img.shape[:2] quads = self._detect(img) rot = 0 if self.orient and self._sideways(quads): # text runs vertically: turn the page 90 or 270 degrees crops, _ = self._crops(img, [quads[i] for i in self._sample(quads)]) rot = 90 if self._flip_better(crops) else 270 img = _rotate(img, rot) h, w = img.shape[:2] quads = self._detect(img) crops, keep = self._crops(img, quads) res = self._read(crops) if self.orient and rot == 0 and res and float(np.median([r[1] for r in res])) < self.orient_conf: idx = self._sample([quads[i] for i in keep]) if self._flip_better([crops[i] for i in idx]): # upside down rot = 180 img = _rotate(img, 180) quads = [_rotate_quad(q, 180, h, w) for q in quads] crops, keep = self._crops(img, quads) res = self._read(crops) boxes = level_quads(quads, self.box_level) if self.box_level else quads lines, upright = [], [] for k, i in enumerate(keep): text, conf = res[k][0].strip(), res[k][1] if not text or conf < self.text_score: continue q = boxes[i] upright.append(q) if rot: # boxes back in the input image's pixels q = _rotate_quad(q, (360 - rot) % 360, h, w) lines.append(Line(text, conf, [[float(x), float(y)] for x, y in q])) return [lines[i] for i in sort_reading_order(upright)] # reading order on the upright page
def read_text(self, image: Union[str, os.PathLike, np.ndarray, Any]) -> str: """The page's text, one line per detected line, in reading order.""" return "\n".join(ln.text for ln in self(image))
def read_line(self, crop: Union[str, os.PathLike, np.ndarray, Any]) -> Tuple[str, float]: """One text-line crop (any size) -> (text, mean character confidence). No detection, no text_score filter.""" img, self._rgb = self._load(crop) h, w = img.shape[:2] line = cv2.resize(img, (max(1, int(round(w * self.height / float(h)))), self.height), interpolation=cv2.INTER_AREA if h > self.height else cv2.INTER_CUBIC) text, conf, _ = self._read([line])[0] return text.strip(), conf123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135"""Text-line recognition: crop from the full-resolution page, resize to the recognizer height, greedy CTC decode."""from __future__ import annotations
import mathfrom typing import List, Optional, Sequence, Tuple
import cv2import numpy as np
def crop_line(img: np.ndarray, quad: np.ndarray, height: int) -> Optional[np.ndarray]: """Perspective-rectify `quad` (tl, tr, br, bl in page pixels) to a `height`-px uint8 crop (same channel order as img). Shrinking first resizes the region with INTER_AREA, then warps at the reduced scale. Tall crops (h / w >= 1.5) are turned 90 degrees counter-clockwise.""" q = quad.astype(np.float32) w_q = max(np.linalg.norm(q[0] - q[1]), np.linalg.norm(q[2] - q[3])) h_q = max(np.linalg.norm(q[0] - q[3]), np.linalg.norm(q[1] - q[2])) if w_q < 2 or h_q < 2: return None vertical = h_q / w_q >= 1.5 H, W = img.shape[:2] x0 = max(0, int(math.floor(q[:, 0].min())) - 1) y0 = max(0, int(math.floor(q[:, 1].min())) - 1) x1 = min(W, int(math.ceil(q[:, 0].max())) + 2) y1 = min(H, int(math.ceil(q[:, 1].max())) + 2) if x1 - x0 < 2 or y1 - y0 < 2: return None region = img[y0:y1, x0:x1] q = q - np.array([x0, y0], np.float32) f = height / (w_q if vertical else h_q) out_w, out_h = max(1, int(round(w_q * f))), max(1, int(round(h_q * f))) if f < 0.75: rw, rh = max(1, int(round(region.shape[1] * f))), max(1, int(round(region.shape[0] * f))) region = cv2.resize(region, (rw, rh), interpolation=cv2.INTER_AREA) q = q * np.array([rw / (x1 - x0), rh / (y1 - y0)], np.float32) interp = cv2.INTER_LINEAR else: interp = cv2.INTER_CUBIC dst = np.array([[0, 0], [out_w, 0], [out_w, out_h], [0, out_h]], np.float32) crop = cv2.warpPerspective(region, cv2.getPerspectiveTransform(q, dst), (out_w, out_h), flags=interp, borderMode=cv2.BORDER_REPLICATE) if vertical: crop = np.ascontiguousarray(np.rot90(crop)) if crop.shape[0] != height: crop = cv2.resize(crop, (max(1, int(round(crop.shape[1] * height / crop.shape[0]))), height), interpolation=cv2.INTER_LINEAR) return crop
class CTCDecoder: """Greedy CTC decoding. space_bias > 1 multiplies the space class's probability before the argmax (the recognizer drops spaces more often than it invents them); confidences stay the unbiased probabilities. case_conf: a letter's confidence also counts its other case (C / c, O / o, S / s look alike). space_conf: a space's confidence also counts the blank (a biased space starts on a frame where it is at most 0.5)."""
def __init__(self, classes: Sequence[str], space_bias: float = 2.0, case_conf: bool = True, space_conf: bool = True): self.classes = list(classes) self.lut = np.array(self.classes, dtype=object) self.space_bias = float(space_bias) self.space_idx = len(self.classes) - 1 if self.classes[-1] == " " else ( self.classes.index(" ") if " " in self.classes else -1) pos = {ch: i for i, ch in enumerate(self.classes) if i} self.case_pair = np.array([pos.get(ch.swapcase(), -1) if i and len(ch) == 1 and ch.swapcase() != ch else -1 for i, ch in enumerate(self.classes)], np.int64) if case_conf else None self.space_conf = bool(space_conf) and self.space_idx > 0
def __call__(self, probs: np.ndarray, valid: Optional[Sequence[int]] = None) -> List[Tuple[str, float, float]]: """probs: N x T x C softmax; valid[i] = time steps of sample i inside the real crop. -> (text, mean character confidence, min character confidence) per sample.""" if self.space_bias != 1.0 and self.space_idx >= 0: idx = probs.argmax(axis=2) pmax = np.take_along_axis(probs, idx[:, :, None], axis=2)[:, :, 0] sp = probs[:, :, self.space_idx] pick_sp = (sp * self.space_bias) > pmax idx = np.where(pick_sp, self.space_idx, idx) pmax = np.where(pick_sp, sp, pmax) else: idx = probs.argmax(axis=2) pmax = probs.max(axis=2) if self.case_pair is not None: pair = self.case_pair[idx] pmax = np.minimum(1.0, pmax + np.where( pair >= 0, np.take_along_axis(probs, np.maximum(pair, 0)[:, :, None], axis=2)[:, :, 0], 0.0)) if self.space_conf: pmax = np.where(idx == self.space_idx, np.minimum(1.0, pmax + probs[:, :, 0]), pmax) out = [] for i in range(probs.shape[0]): t, p = idx[i], pmax[i] if valid is not None: t, p = t[: valid[i]], p[: valid[i]] sel = np.ones(len(t), dtype=bool) sel[1:] = t[1:] != t[:-1] sel &= t != 0 if not sel.any(): out.append(("", 0.0, 0.0)) continue ps = p[sel] out.append(("".join(self.lut[t[sel]]), float(ps.mean()), float(ps.min()))) return out
def recognize(model, decoder: CTCDecoder, crops: List[np.ndarray], batch: int = 1, stride: int = 8, rgb: bool = False) -> List[Tuple[str, float, float]]: """Read crops (all the same height). Sorted by width and batched with mid-grey right padding to the batch's widest crop (rounded up to `stride`); time steps in the padding are ignored. batch=1 reads every line alone (the recognizer attends over the whole line, so padding moves its outputs a little).""" n = len(crops) res: List[Tuple[str, float, float]] = [("", 0.0, 0.0)] * n if n == 0: return res order = sorted(range(n), key=lambda i: (crops[i].shape[1], i)) h = crops[0].shape[0] src = (2, 1, 0) if rgb else (0, 1, 2) for s in range(0, n, max(1, int(batch))): ids = order[s:s + max(1, int(batch))] wpad = int(math.ceil(max(crops[i].shape[1] for i in ids) / stride) * stride) xb = np.zeros((len(ids), 3, h, wpad), np.float32) valid = [] for k, i in enumerate(ids): c = crops[i] for ch in range(3): xb[k, ch, :, :c.shape[1]] = c[:, :, src[ch]] valid.append(int(math.ceil(c.shape[1] / stride))) xb *= 2.0 / 255.0 xb -= 1.0 for k, i in enumerate(ids): xb[k, :, :, crops[i].shape[1]:] = 0.0 probs = model(xb) T = probs.shape[1] scale = T / float(wpad) valid = [min(T, int(math.ceil(v * stride * scale))) for v in valid] for k, r in zip(ids, decoder(probs, valid)): res[k] = r return res1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162import osfrom collections import Counter
import cv2import numpy as npimport pytest
from sumoocr import Line, SumoOCRfrom sumoocr.cli import main
HERE = os.path.dirname(os.path.abspath(__file__))PAGE = os.path.join(HERE, "..", "examples", "invoice.png")
@pytest.fixture(scope="module")def ocr(): return SumoOCR(threads=1)
def test_page(ocr): lines = ocr(PAGE) assert lines and all(isinstance(ln, Line) for ln in lines) text = "\n".join(ln.text for ln in lines) for s in ("Brightwater Analytics LLP", "INVOICE", "GB179116235", "15/05/2026"): assert s in text ln = lines[0] assert 0.85 <= ln.conf <= 1.0 and len(ln.box) == 4
def test_inputs_agree(ocr): bgr = cv2.imread(PAGE) a = [ln.text for ln in ocr(PAGE)] assert [ln.text for ln in ocr(bgr)] == a assert [ln.text for ln in ocr(cv2.cvtColor(bgr, cv2.COLOR_BGR2GRAY))] # grayscale works
@pytest.mark.parametrize("turn", [cv2.ROTATE_90_CLOCKWISE, cv2.ROTATE_180, cv2.ROTATE_90_COUNTERCLOCKWISE])def test_turned_pages(ocr, turn): bgr = cv2.imread(PAGE) upright = [ln.text for ln in ocr(bgr)] img = cv2.rotate(bgr, turn) turned = ocr(img) assert [ln.text for ln in turned[:2]] == upright[:2] # read upright, in the upright page's reading order common = sum((Counter(upright) & Counter(ln.text for ln in turned)).values()) assert common >= 0.9 * len(upright) h, w = img.shape[:2] # boxes in the turned image's pixels assert all(-1 <= x <= w + 1 and -1 <= y <= h + 1 for ln in turned for x, y in ln.box)
def test_read_line(ocr): bgr = cv2.imread(PAGE) line = next(ln for ln in ocr(bgr) if ln.text == "VAT Reg. No.: GB179116235") q = np.array(line.box) x0, y0 = q.min(0).astype(int) x1, y1 = q.max(0).astype(int) text, conf = ocr.read_line(bgr[y0:y1 + 1, x0:x1 + 1]) assert text == line.text and conf > 0.9
def test_cli(capsys): assert main([PAGE, "--threads", "1"]) == 0 assert "Brightwater Analytics LLP" in capsys.readouterr().out.gitattributesAdded+2
.gitignoreAdded+12
LICENSEAdded+202
MANIFEST.inAdded+1
NOTICEAdded+10
README.mdAdded+229
REPORT.mdAdded+175
charts/accuracy_vs_speed.svgAdded
charts/word_f1_by_benchmark.svgAdded
examples/invoice.pngAdded

Large File Pointer Details
- SHA256: 95f1b8680c6d521fb4c64d2549111764cd2176c0cdf218f8605a7a87d8a56b5f
- Pointer size: 131 Bytes
- Size of remote file: 206 kB
examples/ocr_page.pyAdded+11
pyproject.tomlAdded+43
setup.pyAdded+25
sumoocr/__init__.pyAdded+11
sumoocr/backend.pyAdded+64
sumoocr/cli.pyAdded+34
sumoocr/det.pyAdded+132
sumoocr/models/config.jsonAdded+7
sumoocr/models/det.onnxAdded+3
sumoocr/models/rec.classes.jsonAdded+1
sumoocr/models/rec.onnxAdded+3
sumoocr/ocr.pyAdded+240
sumoocr/rec.pyAdded+135
tests/test_sumoocr.pyAdded+62