tinyocr-onnx 0.1.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.
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,2 @@
1
+ include LICENSE NOTICE README.md
2
+ recursive-include tests *.py *.png
@@ -0,0 +1,29 @@
1
+ TinyOCR
2
+ Copyright 2026 Maureese Williams
3
+
4
+ This product includes PaddleOCR / PP-OCRv6 model artifacts.
5
+ Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
6
+ https://github.com/PaddlePaddle/PaddleOCR
7
+ Licensed under the Apache License, Version 2.0 (see LICENSE).
8
+
9
+ PP-OCRv6_det_tiny.onnx is the unchanged pretrained detector.
10
+ PP-OCRv6_rec_tiny.onnx WAS MODIFIED by Maureese Williams in 2026:
11
+ selected float32 weight tensors were stored as per-channel int8 values with
12
+ constant decoding back to float32. Computation remains float32. No training
13
+ or calibration was performed. This modified file is not an official
14
+ PaddlePaddle release. SHA-256 hashes and origins are in assets/models.json.
15
+
16
+ Original ONNX artifacts were distributed through RapidAI/RapidOCR v3.10.0:
17
+ https://www.modelscope.cn/models/RapidAI/RapidOCR/resolve/v3.10.0/onnx/PP-OCRv6/det/PP-OCRv6_det_tiny.onnx
18
+ https://www.modelscope.cn/models/RapidAI/RapidOCR/resolve/v3.10.0/onnx/PP-OCRv6/rec/PP-OCRv6_rec_tiny.onnx
19
+ Official Apache-2.0 model cards:
20
+ https://huggingface.co/PaddlePaddle/PP-OCRv6_tiny_det_onnx
21
+ https://huggingface.co/PaddlePaddle/PP-OCRv6_tiny_rec_onnx
22
+
23
+ Runtime inference uses the separately installed RapidOCR project (Apache-2.0):
24
+ Copyright RapidAI contributors. https://github.com/RapidAI/RapidOCR
25
+ Other installed dependencies retain their own licenses.
26
+
27
+ Research repository only: the vendored Google HierText evaluator has its own
28
+ CC BY-SA 4.0 license and notices in third_party/hiertext. It and evaluation
29
+ datasets are not included in the TinyOCR runtime distribution.
@@ -0,0 +1,102 @@
1
+ Metadata-Version: 2.4
2
+ Name: tinyocr-onnx
3
+ Version: 0.1.0
4
+ Summary: Offline CPU OCR with 3.10 MB of bundled PaddleOCR-derived ONNX models
5
+ Author: Maureese Williams
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/MMWilliams/tinyocr
8
+ Project-URL: Repository, https://github.com/MMWilliams/tinyocr
9
+ Project-URL: Models, https://huggingface.co/maureesewilliams/tinyocr
10
+ Project-URL: Issues, https://github.com/MMWilliams/tinyocr/issues
11
+ Keywords: ocr,onnx,paddleocr,offline,cpu
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Programming Language :: Python :: 3.12
14
+ Classifier: Topic :: Scientific/Engineering :: Image Recognition
15
+ Requires-Python: <3.13,>=3.12
16
+ Description-Content-Type: text/markdown
17
+ License-File: LICENSE
18
+ License-File: NOTICE
19
+ Requires-Dist: rapidocr==3.10.0
20
+ Requires-Dist: onnxruntime==1.31.0
21
+ Requires-Dist: numpy==2.5.4
22
+ Requires-Dist: opencv-python-headless==5.0.0.93
23
+ Requires-Dist: pillow==12.3.0
24
+ Requires-Dist: omegaconf==2.4.0
25
+ Dynamic: license-file
26
+
27
+ # TinyOCR
28
+
29
+ Offline, English-first CPU OCR with **3.10 MB of bundled ONNX model files**.
30
+ TinyOCR packages a compressed pretrained PaddleOCR PP-OCRv6 recognizer and the
31
+ original tiny detector, using RapidOCR and ONNX Runtime. It is an alpha release,
32
+ not a newly trained model. The full installation and runtime memory are larger
33
+ than the model files.
34
+
35
+ ## Install and use
36
+
37
+ Python **3.12** is supported. Windows, Linux and macOS are tested in CI.
38
+
39
+ ```sh
40
+ python -m pip install tinyocr-onnx==0.1.0
41
+ tinyocr receipt.png
42
+ tinyocr receipt.png --json
43
+ python -m tinyocr receipt.png --no-words
44
+ ```
45
+
46
+ ```python
47
+ from tinyocr import TinyOCR
48
+
49
+ ocr = TinyOCR() # Load once and reuse. No model downloads.
50
+ result = ocr("receipt.png")
51
+ print(result.text)
52
+ print(result.lines) # text, polygon, and [x0, y0, x1, y1] bounds
53
+ print(result.words) # text and native word polygons
54
+ data = result.to_dict() # JSON-serializable
55
+ ```
56
+
57
+ Inputs are local image paths (PNG, JPEG, and other Pillow-supported images).
58
+ Coordinates are original-image pixels. Text uses a simple geometric row order,
59
+ not document-layout analysis. Blank images produce empty text and region lists.
60
+ `words=False` omits word geometry. Native word polygons can have zero area;
61
+ these are preserved to match the published benchmark.
62
+
63
+ The package name is **tinyocr-onnx**; the import and CLI are **tinyocr**. Do not
64
+ install the unrelated `tinyocr` distribution into the same environment. When
65
+ using this research checkout, run the installed package outside the repository
66
+ root so the research `tinyocr/` directory does not shadow it.
67
+
68
+ ## Measured tradeoffs
69
+
70
+ The frozen pair is 3,099,213 bytes versus the original 6,319,431 bytes (50.96%
71
+ smaller). The recognizer stores int8 weights but executes float32 math. This is
72
+ a model-storage reduction; it is not a general speed or RAM reduction.
73
+
74
+ | Dataset | Images | Original E2E F1 (%) | TinyOCR E2E F1 (%) |
75
+ | --- | ---: | ---: | ---: |
76
+ | SROIE | 341 | 41.036 | 40.779 |
77
+ | TextOCR | 3,027 | 43.412 | 43.334 |
78
+ | HierText | 1,721 | 40.330 | 40.204 |
79
+
80
+ In one timed pass, candidate p50 latency was 21.23% higher on SROIE, 16.16%
81
+ higher on HierText, and 6.91% lower on TextOCR. Peak process working set was
82
+ about 500 MiB for both models on the measured Windows machine. SROIE/TextOCR
83
+ use the shared HierText polygon protocol, not their native leaderboard scores.
84
+ Public pretraining overlap is unknown; these are comparative development results.
85
+ See the [full benchmark and limitations](https://github.com/MMWilliams/tinyocr/blob/master/BENCHMARK_RESULTS.md).
86
+
87
+ Inference uses one-thread CPU ONNX sessions, detector maximum side 960 px,
88
+ recognition batch size one, and no orientation classifier. Initialization also
89
+ sets OpenCV and common BLAS thread controls to one for the current process.
90
+ Rotated text, difficult scenes and complex layouts can fail. English-first
91
+ evaluation does not establish multilingual performance. No mobile performance
92
+ claim is made.
93
+
94
+ ## Source and license
95
+
96
+ [GitHub](https://github.com/MMWilliams/tinyocr) ·
97
+ [Hugging Face models](https://huggingface.co/maureesewilliams/tinyocr) ·
98
+ [PyPI](https://pypi.org/project/tinyocr-onnx/)
99
+
100
+ Apache-2.0. See LICENSE and NOTICE for PaddlePaddle and RapidAI attribution and
101
+ the recognizer modification notice. Bundled artifacts are verified by SHA-256
102
+ on initialization. No evaluation datasets are included.
@@ -0,0 +1,76 @@
1
+ # TinyOCR
2
+
3
+ Offline, English-first CPU OCR with **3.10 MB of bundled ONNX model files**.
4
+ TinyOCR packages a compressed pretrained PaddleOCR PP-OCRv6 recognizer and the
5
+ original tiny detector, using RapidOCR and ONNX Runtime. It is an alpha release,
6
+ not a newly trained model. The full installation and runtime memory are larger
7
+ than the model files.
8
+
9
+ ## Install and use
10
+
11
+ Python **3.12** is supported. Windows, Linux and macOS are tested in CI.
12
+
13
+ ```sh
14
+ python -m pip install tinyocr-onnx==0.1.0
15
+ tinyocr receipt.png
16
+ tinyocr receipt.png --json
17
+ python -m tinyocr receipt.png --no-words
18
+ ```
19
+
20
+ ```python
21
+ from tinyocr import TinyOCR
22
+
23
+ ocr = TinyOCR() # Load once and reuse. No model downloads.
24
+ result = ocr("receipt.png")
25
+ print(result.text)
26
+ print(result.lines) # text, polygon, and [x0, y0, x1, y1] bounds
27
+ print(result.words) # text and native word polygons
28
+ data = result.to_dict() # JSON-serializable
29
+ ```
30
+
31
+ Inputs are local image paths (PNG, JPEG, and other Pillow-supported images).
32
+ Coordinates are original-image pixels. Text uses a simple geometric row order,
33
+ not document-layout analysis. Blank images produce empty text and region lists.
34
+ `words=False` omits word geometry. Native word polygons can have zero area;
35
+ these are preserved to match the published benchmark.
36
+
37
+ The package name is **tinyocr-onnx**; the import and CLI are **tinyocr**. Do not
38
+ install the unrelated `tinyocr` distribution into the same environment. When
39
+ using this research checkout, run the installed package outside the repository
40
+ root so the research `tinyocr/` directory does not shadow it.
41
+
42
+ ## Measured tradeoffs
43
+
44
+ The frozen pair is 3,099,213 bytes versus the original 6,319,431 bytes (50.96%
45
+ smaller). The recognizer stores int8 weights but executes float32 math. This is
46
+ a model-storage reduction; it is not a general speed or RAM reduction.
47
+
48
+ | Dataset | Images | Original E2E F1 (%) | TinyOCR E2E F1 (%) |
49
+ | --- | ---: | ---: | ---: |
50
+ | SROIE | 341 | 41.036 | 40.779 |
51
+ | TextOCR | 3,027 | 43.412 | 43.334 |
52
+ | HierText | 1,721 | 40.330 | 40.204 |
53
+
54
+ In one timed pass, candidate p50 latency was 21.23% higher on SROIE, 16.16%
55
+ higher on HierText, and 6.91% lower on TextOCR. Peak process working set was
56
+ about 500 MiB for both models on the measured Windows machine. SROIE/TextOCR
57
+ use the shared HierText polygon protocol, not their native leaderboard scores.
58
+ Public pretraining overlap is unknown; these are comparative development results.
59
+ See the [full benchmark and limitations](https://github.com/MMWilliams/tinyocr/blob/master/BENCHMARK_RESULTS.md).
60
+
61
+ Inference uses one-thread CPU ONNX sessions, detector maximum side 960 px,
62
+ recognition batch size one, and no orientation classifier. Initialization also
63
+ sets OpenCV and common BLAS thread controls to one for the current process.
64
+ Rotated text, difficult scenes and complex layouts can fail. English-first
65
+ evaluation does not establish multilingual performance. No mobile performance
66
+ claim is made.
67
+
68
+ ## Source and license
69
+
70
+ [GitHub](https://github.com/MMWilliams/tinyocr) ·
71
+ [Hugging Face models](https://huggingface.co/maureesewilliams/tinyocr) ·
72
+ [PyPI](https://pypi.org/project/tinyocr-onnx/)
73
+
74
+ Apache-2.0. See LICENSE and NOTICE for PaddlePaddle and RapidAI attribution and
75
+ the recognizer modification notice. Bundled artifacts are verified by SHA-256
76
+ on initialization. No evaluation datasets are included.
@@ -0,0 +1,42 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77,<83"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "tinyocr-onnx"
7
+ version = "0.1.0"
8
+ description = "Offline CPU OCR with 3.10 MB of bundled PaddleOCR-derived ONNX models"
9
+ readme = "README.md"
10
+ requires-python = ">=3.12,<3.13"
11
+ license = "Apache-2.0"
12
+ license-files = ["LICENSE", "NOTICE"]
13
+ authors = [{name = "Maureese Williams"}]
14
+ keywords = ["ocr", "onnx", "paddleocr", "offline", "cpu"]
15
+ classifiers = [
16
+ "Development Status :: 3 - Alpha",
17
+ "Programming Language :: Python :: 3.12",
18
+ "Topic :: Scientific/Engineering :: Image Recognition",
19
+ ]
20
+ dependencies = [
21
+ "rapidocr==3.10.0",
22
+ "onnxruntime==1.31.0",
23
+ "numpy==2.5.4",
24
+ "opencv-python-headless==5.0.0.93",
25
+ "pillow==12.3.0",
26
+ "omegaconf==2.4.0",
27
+ ]
28
+
29
+ [project.urls]
30
+ Homepage = "https://github.com/MMWilliams/tinyocr"
31
+ Repository = "https://github.com/MMWilliams/tinyocr"
32
+ Models = "https://huggingface.co/maureesewilliams/tinyocr"
33
+ Issues = "https://github.com/MMWilliams/tinyocr/issues"
34
+
35
+ [project.scripts]
36
+ tinyocr = "tinyocr.cli:main"
37
+
38
+ [tool.setuptools.packages.find]
39
+ where = ["src"]
40
+
41
+ [tool.setuptools.package-data]
42
+ tinyocr = ["assets/*.onnx", "assets/*.json", "assets/NOTICE"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,6 @@
1
+ """TinyOCR: offline CPU OCR using bundled, compressed PaddleOCR weights."""
2
+
3
+ from .runtime import OCRResult, TinyOCR
4
+
5
+ __version__ = "0.1.0"
6
+ __all__ = ["OCRResult", "TinyOCR", "__version__"]
@@ -0,0 +1,3 @@
1
+ from .cli import main
2
+
3
+ raise SystemExit(main())
@@ -0,0 +1,29 @@
1
+ TinyOCR
2
+ Copyright 2026 Maureese Williams
3
+
4
+ This product includes PaddleOCR / PP-OCRv6 model artifacts.
5
+ Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
6
+ https://github.com/PaddlePaddle/PaddleOCR
7
+ Licensed under the Apache License, Version 2.0 (see LICENSE).
8
+
9
+ PP-OCRv6_det_tiny.onnx is the unchanged pretrained detector.
10
+ PP-OCRv6_rec_tiny.onnx WAS MODIFIED by Maureese Williams in 2026:
11
+ selected float32 weight tensors were stored as per-channel int8 values with
12
+ constant decoding back to float32. Computation remains float32. No training
13
+ or calibration was performed. This modified file is not an official
14
+ PaddlePaddle release. SHA-256 hashes and origins are in assets/models.json.
15
+
16
+ Original ONNX artifacts were distributed through RapidAI/RapidOCR v3.10.0:
17
+ https://www.modelscope.cn/models/RapidAI/RapidOCR/resolve/v3.10.0/onnx/PP-OCRv6/det/PP-OCRv6_det_tiny.onnx
18
+ https://www.modelscope.cn/models/RapidAI/RapidOCR/resolve/v3.10.0/onnx/PP-OCRv6/rec/PP-OCRv6_rec_tiny.onnx
19
+ Official Apache-2.0 model cards:
20
+ https://huggingface.co/PaddlePaddle/PP-OCRv6_tiny_det_onnx
21
+ https://huggingface.co/PaddlePaddle/PP-OCRv6_tiny_rec_onnx
22
+
23
+ Runtime inference uses the separately installed RapidOCR project (Apache-2.0):
24
+ Copyright RapidAI contributors. https://github.com/RapidAI/RapidOCR
25
+ Other installed dependencies retain their own licenses.
26
+
27
+ Research repository only: the vendored Google HierText evaluator has its own
28
+ CC BY-SA 4.0 license and notices in third_party/hiertext. It and evaluation
29
+ datasets are not included in the TinyOCR runtime distribution.
@@ -0,0 +1,15 @@
1
+ {
2
+ "model": "v6-w8-rec",
3
+ "artifacts": [
4
+ {
5
+ "filename": "PP-OCRv6_det_tiny.onnx",
6
+ "bytes": 1829618,
7
+ "sha256": "f42c0fbd294d95eac1a550e131b277dac97462c8025fa4b6c3cec1b7894bd3d5"
8
+ },
9
+ {
10
+ "filename": "PP-OCRv6_rec_tiny.onnx",
11
+ "bytes": 1269595,
12
+ "sha256": "38cd559cb4b24c5056592d981b13e086f9472db9b3c8968296f0d0c2b4a65531"
13
+ }
14
+ ]
15
+ }
@@ -0,0 +1,28 @@
1
+ """Command line interface for local image OCR."""
2
+
3
+ import argparse
4
+ import json
5
+ from pathlib import Path
6
+ import sys
7
+
8
+ from . import TinyOCR, __version__
9
+
10
+
11
+ def main(argv=None):
12
+ parser = argparse.ArgumentParser(description="Offline CPU OCR with bundled TinyOCR models")
13
+ parser.add_argument("image", type=Path, help="local image path")
14
+ parser.add_argument("--json", action="store_true", help="emit text, lines and words as JSON")
15
+ parser.add_argument("--no-words", action="store_true", help="omit word geometry")
16
+ parser.add_argument("--version", action="version", version=f"tinyocr-onnx {__version__}")
17
+ args = parser.parse_args(argv)
18
+ if not args.image.expanduser().is_file():
19
+ parser.error(f"Image does not exist or is not a file: {args.image}")
20
+ try:
21
+ result = TinyOCR()(args.image, words=not args.no_words)
22
+ except Exception as exc:
23
+ print(f"tinyocr: {exc}", file=sys.stderr)
24
+ return 1
25
+ if hasattr(sys.stdout, "reconfigure"):
26
+ sys.stdout.reconfigure(encoding="utf-8")
27
+ print(json.dumps(result.to_dict(), ensure_ascii=False) if args.json else result.text)
28
+ return 0
@@ -0,0 +1,125 @@
1
+ """Frozen v6-w8-rec pipeline, distributed independently of the research harness."""
2
+
3
+ from dataclasses import asdict, dataclass
4
+ import hashlib
5
+ import json
6
+ import os
7
+ from pathlib import Path
8
+ import threading
9
+
10
+
11
+ @dataclass
12
+ class OCRResult:
13
+ """Text in row order, line polygons/xyxy bounds, and native word polygons.
14
+
15
+ Coordinates are in pixels of the original image. Native word boxes can be
16
+ degenerate; these are retained to match the published benchmark adapter.
17
+ """
18
+
19
+ text: str
20
+ lines: list[dict]
21
+ words: list[dict]
22
+
23
+ def to_dict(self) -> dict:
24
+ return asdict(self)
25
+
26
+
27
+ def _reading_order(regions):
28
+ # Same half-smaller-height row tolerance as the frozen research adapter.
29
+ rows = []
30
+ for region in sorted(regions, key=lambda r: ((r["box"][1] + r["box"][3]) / 2, r["box"][0])):
31
+ x0, y0, x1, y1 = region["box"]
32
+ cy, h = (y0 + y1) / 2, y1 - y0
33
+ if rows and abs(cy - rows[-1][0]) <= 0.5 * min(h, rows[-1][1]):
34
+ rows[-1][2].append(region)
35
+ else:
36
+ rows.append([cy, h, [region]])
37
+ return [r for _, _, row in rows for r in sorted(row, key=lambda r: r["box"][0])]
38
+
39
+
40
+ class TinyOCR:
41
+ """Reusable, one-thread CPU OCR engine for local image paths.
42
+
43
+ Initialization verifies and loads both bundled models. No model download
44
+ or account is required. Sets OpenCV and common BLAS thread controls to one.
45
+ Calls on one instance are serialized because RapidOCR updates call options.
46
+ """
47
+
48
+ def __init__(self):
49
+ for key in ("OMP_NUM_THREADS", "OPENBLAS_NUM_THREADS", "MKL_NUM_THREADS", "NUMEXPR_NUM_THREADS"):
50
+ os.environ[key] = "1"
51
+
52
+ import cv2
53
+ from rapidocr import RapidOCR
54
+ from rapidocr.utils.typings import LangDet, LangRec, ModelType, OCRVersion
55
+
56
+ cv2.setNumThreads(1)
57
+ cv2.ocl.setUseOpenCL(False)
58
+ assets = Path(__file__).resolve().parent / "assets"
59
+ manifest = json.loads((assets / "models.json").read_text(encoding="utf-8"))
60
+ for item in manifest["artifacts"]:
61
+ path = assets / item["filename"]
62
+ if not path.is_file() or hashlib.sha256(path.read_bytes()).hexdigest() != item["sha256"]:
63
+ raise RuntimeError(f"Bundled model missing or damaged: {path.name}. Reinstall tinyocr-onnx.")
64
+ params = {
65
+ "Global.model_root_dir": str(assets),
66
+ "Global.use_cls": False,
67
+ "Global.log_level": "warning",
68
+ "EngineConfig.onnxruntime.intra_op_num_threads": 1,
69
+ "EngineConfig.onnxruntime.inter_op_num_threads": 1,
70
+ "EngineConfig.onnxruntime.use_cuda": False,
71
+ "EngineConfig.onnxruntime.use_dml": False,
72
+ "Det.ocr_version": OCRVersion.PPOCRV6,
73
+ "Rec.ocr_version": OCRVersion.PPOCRV6,
74
+ "Det.model_type": ModelType.TINY,
75
+ "Rec.model_type": ModelType.TINY,
76
+ "Det.lang_type": LangDet.CH,
77
+ "Rec.lang_type": LangRec.EN,
78
+ "Det.mean": [0.485, 0.456, 0.406],
79
+ "Det.std": [0.229, 0.224, 0.225],
80
+ "Det.limit_side_len": 960,
81
+ "Det.limit_type": "max",
82
+ "Det.thresh": 0.2,
83
+ "Det.box_thresh": 0.4,
84
+ "Det.unclip_ratio": 1.4,
85
+ "Det.max_candidates": 3000,
86
+ "Det.use_dilation": False,
87
+ "Rec.rec_batch_num": 1,
88
+ "Rec.rec_img_shape": [3, 48, 320],
89
+ "Det.model_path": str(assets / "PP-OCRv6_det_tiny.onnx"),
90
+ "Rec.model_path": str(assets / "PP-OCRv6_rec_tiny.onnx"),
91
+ }
92
+ self._engine = RapidOCR(params=params)
93
+ self._engine._load_det_model()
94
+ self._engine._load_rec_model()
95
+ for module in (self._engine.text_det, self._engine.text_rec):
96
+ session = module.session.session
97
+ opts = session.get_session_options()
98
+ if (session.get_providers() != ["CPUExecutionProvider"] or
99
+ opts.intra_op_num_threads != 1 or opts.inter_op_num_threads != 1):
100
+ raise RuntimeError("TinyOCR requires one-thread CPU sessions")
101
+ self._lock = threading.Lock()
102
+
103
+ def __call__(self, image: str | os.PathLike, *, words: bool = True) -> OCRResult:
104
+ """Read a local image. Set words=False to omit native word geometry."""
105
+ from rapidocr.main import flatten_word_results
106
+
107
+ path = Path(image).expanduser()
108
+ if not path.is_file():
109
+ raise FileNotFoundError(f"Image does not exist or is not a file: {path}")
110
+ with self._lock:
111
+ result = self._engine(str(path), use_det=True, use_cls=False, use_rec=True,
112
+ return_word_box=words, return_single_char_box=False)
113
+ lines = []
114
+ if result.boxes is not None:
115
+ for text, points in zip(result.txts, result.boxes):
116
+ polygon = [[float(x), float(y)] for x, y in points]
117
+ xs, ys = zip(*polygon)
118
+ lines.append({"text": text, "polygon": polygon,
119
+ "box": [min(xs), min(ys), max(xs), max(ys)]})
120
+ lines = _reading_order(lines)
121
+ word_regions = [
122
+ {"text": text, "polygon": [[float(x), float(y)] for x, y in points]}
123
+ for text, _, points in flatten_word_results(getattr(result, "word_results", None))
124
+ ] if words else []
125
+ return OCRResult("\n".join(r["text"] for r in lines), lines, word_regions)
@@ -0,0 +1,102 @@
1
+ Metadata-Version: 2.4
2
+ Name: tinyocr-onnx
3
+ Version: 0.1.0
4
+ Summary: Offline CPU OCR with 3.10 MB of bundled PaddleOCR-derived ONNX models
5
+ Author: Maureese Williams
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/MMWilliams/tinyocr
8
+ Project-URL: Repository, https://github.com/MMWilliams/tinyocr
9
+ Project-URL: Models, https://huggingface.co/maureesewilliams/tinyocr
10
+ Project-URL: Issues, https://github.com/MMWilliams/tinyocr/issues
11
+ Keywords: ocr,onnx,paddleocr,offline,cpu
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Programming Language :: Python :: 3.12
14
+ Classifier: Topic :: Scientific/Engineering :: Image Recognition
15
+ Requires-Python: <3.13,>=3.12
16
+ Description-Content-Type: text/markdown
17
+ License-File: LICENSE
18
+ License-File: NOTICE
19
+ Requires-Dist: rapidocr==3.10.0
20
+ Requires-Dist: onnxruntime==1.31.0
21
+ Requires-Dist: numpy==2.5.4
22
+ Requires-Dist: opencv-python-headless==5.0.0.93
23
+ Requires-Dist: pillow==12.3.0
24
+ Requires-Dist: omegaconf==2.4.0
25
+ Dynamic: license-file
26
+
27
+ # TinyOCR
28
+
29
+ Offline, English-first CPU OCR with **3.10 MB of bundled ONNX model files**.
30
+ TinyOCR packages a compressed pretrained PaddleOCR PP-OCRv6 recognizer and the
31
+ original tiny detector, using RapidOCR and ONNX Runtime. It is an alpha release,
32
+ not a newly trained model. The full installation and runtime memory are larger
33
+ than the model files.
34
+
35
+ ## Install and use
36
+
37
+ Python **3.12** is supported. Windows, Linux and macOS are tested in CI.
38
+
39
+ ```sh
40
+ python -m pip install tinyocr-onnx==0.1.0
41
+ tinyocr receipt.png
42
+ tinyocr receipt.png --json
43
+ python -m tinyocr receipt.png --no-words
44
+ ```
45
+
46
+ ```python
47
+ from tinyocr import TinyOCR
48
+
49
+ ocr = TinyOCR() # Load once and reuse. No model downloads.
50
+ result = ocr("receipt.png")
51
+ print(result.text)
52
+ print(result.lines) # text, polygon, and [x0, y0, x1, y1] bounds
53
+ print(result.words) # text and native word polygons
54
+ data = result.to_dict() # JSON-serializable
55
+ ```
56
+
57
+ Inputs are local image paths (PNG, JPEG, and other Pillow-supported images).
58
+ Coordinates are original-image pixels. Text uses a simple geometric row order,
59
+ not document-layout analysis. Blank images produce empty text and region lists.
60
+ `words=False` omits word geometry. Native word polygons can have zero area;
61
+ these are preserved to match the published benchmark.
62
+
63
+ The package name is **tinyocr-onnx**; the import and CLI are **tinyocr**. Do not
64
+ install the unrelated `tinyocr` distribution into the same environment. When
65
+ using this research checkout, run the installed package outside the repository
66
+ root so the research `tinyocr/` directory does not shadow it.
67
+
68
+ ## Measured tradeoffs
69
+
70
+ The frozen pair is 3,099,213 bytes versus the original 6,319,431 bytes (50.96%
71
+ smaller). The recognizer stores int8 weights but executes float32 math. This is
72
+ a model-storage reduction; it is not a general speed or RAM reduction.
73
+
74
+ | Dataset | Images | Original E2E F1 (%) | TinyOCR E2E F1 (%) |
75
+ | --- | ---: | ---: | ---: |
76
+ | SROIE | 341 | 41.036 | 40.779 |
77
+ | TextOCR | 3,027 | 43.412 | 43.334 |
78
+ | HierText | 1,721 | 40.330 | 40.204 |
79
+
80
+ In one timed pass, candidate p50 latency was 21.23% higher on SROIE, 16.16%
81
+ higher on HierText, and 6.91% lower on TextOCR. Peak process working set was
82
+ about 500 MiB for both models on the measured Windows machine. SROIE/TextOCR
83
+ use the shared HierText polygon protocol, not their native leaderboard scores.
84
+ Public pretraining overlap is unknown; these are comparative development results.
85
+ See the [full benchmark and limitations](https://github.com/MMWilliams/tinyocr/blob/master/BENCHMARK_RESULTS.md).
86
+
87
+ Inference uses one-thread CPU ONNX sessions, detector maximum side 960 px,
88
+ recognition batch size one, and no orientation classifier. Initialization also
89
+ sets OpenCV and common BLAS thread controls to one for the current process.
90
+ Rotated text, difficult scenes and complex layouts can fail. English-first
91
+ evaluation does not establish multilingual performance. No mobile performance
92
+ claim is made.
93
+
94
+ ## Source and license
95
+
96
+ [GitHub](https://github.com/MMWilliams/tinyocr) ·
97
+ [Hugging Face models](https://huggingface.co/maureesewilliams/tinyocr) ·
98
+ [PyPI](https://pypi.org/project/tinyocr-onnx/)
99
+
100
+ Apache-2.0. See LICENSE and NOTICE for PaddlePaddle and RapidAI attribution and
101
+ the recognizer modification notice. Bundled artifacts are verified by SHA-256
102
+ on initialization. No evaluation datasets are included.
@@ -0,0 +1,22 @@
1
+ LICENSE
2
+ MANIFEST.in
3
+ NOTICE
4
+ README.md
5
+ pyproject.toml
6
+ src/tinyocr/__init__.py
7
+ src/tinyocr/__main__.py
8
+ src/tinyocr/cli.py
9
+ src/tinyocr/runtime.py
10
+ src/tinyocr/assets/NOTICE
11
+ src/tinyocr/assets/PP-OCRv6_det_tiny.onnx
12
+ src/tinyocr/assets/PP-OCRv6_rec_tiny.onnx
13
+ src/tinyocr/assets/models.json
14
+ src/tinyocr_onnx.egg-info/PKG-INFO
15
+ src/tinyocr_onnx.egg-info/SOURCES.txt
16
+ src/tinyocr_onnx.egg-info/dependency_links.txt
17
+ src/tinyocr_onnx.egg-info/entry_points.txt
18
+ src/tinyocr_onnx.egg-info/requires.txt
19
+ src/tinyocr_onnx.egg-info/top_level.txt
20
+ tests/test_installed.py
21
+ tests/fixtures/blank.png
22
+ tests/fixtures/receipt.png
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ tinyocr = tinyocr.cli:main
@@ -0,0 +1,6 @@
1
+ rapidocr==3.10.0
2
+ onnxruntime==1.31.0
3
+ numpy==2.5.4
4
+ opencv-python-headless==5.0.0.93
5
+ pillow==12.3.0
6
+ omegaconf==2.4.0
@@ -0,0 +1,118 @@
1
+ """Public contracts exercised with actual bundled models and authored images."""
2
+
3
+ import hashlib
4
+ import importlib.metadata
5
+ import json
6
+ import math
7
+ from pathlib import Path
8
+ import shutil
9
+ import subprocess
10
+ import sys
11
+ import tempfile
12
+ import unittest
13
+ from unittest.mock import patch
14
+
15
+ import tinyocr
16
+ from tinyocr import TinyOCR
17
+
18
+ FIXTURES = Path(__file__).parent / "fixtures"
19
+
20
+
21
+ class InstalledOCRTests(unittest.TestCase):
22
+ @classmethod
23
+ def setUpClass(cls):
24
+ cls.network = patch("socket.socket.connect", side_effect=AssertionError("OCR attempted network access"))
25
+ cls.network.start()
26
+ cls.addClassCleanup(cls.network.stop)
27
+ cls.ocr = TinyOCR()
28
+
29
+ def test_installed_version_and_assets(self):
30
+ self.assertEqual(importlib.metadata.version("tinyocr-onnx"), "0.1.0")
31
+ self.assertEqual(tinyocr.__version__, "0.1.0")
32
+ assets = Path(tinyocr.__file__).parent / "assets"
33
+ expected = {
34
+ "PP-OCRv6_det_tiny.onnx": "f42c0fbd294d95eac1a550e131b277dac97462c8025fa4b6c3cec1b7894bd3d5",
35
+ "PP-OCRv6_rec_tiny.onnx": "38cd559cb4b24c5056592d981b13e086f9472db9b3c8968296f0d0c2b4a65531",
36
+ }
37
+ for filename, digest in expected.items():
38
+ self.assertEqual(hashlib.sha256((assets / filename).read_bytes()).hexdigest(), digest)
39
+ for module in (self.ocr._engine.text_det, self.ocr._engine.text_rec):
40
+ session = module.session.session
41
+ self.assertEqual(session.get_providers(), ["CPUExecutionProvider"])
42
+ self.assertEqual(session.get_session_options().intra_op_num_threads, 1)
43
+ self.assertEqual(session.get_session_options().inter_op_num_threads, 1)
44
+
45
+ def test_real_offline_ocr(self):
46
+ result = self.ocr(FIXTURES / "receipt.png")
47
+ self.assertEqual(result.text, "HELLO WORLD\nTOTAL 123.45")
48
+ self.assertEqual([r["text"] for r in result.lines], ["HELLO WORLD", "TOTAL 123.45"])
49
+ self.assertEqual([r["text"] for r in result.words], ["HELLO", "WORLD", "TOTAL", "123.45"])
50
+ for region in result.lines + result.words:
51
+ self.assertEqual(len(region["polygon"]), 4)
52
+ for x, y in region["polygon"]:
53
+ self.assertTrue(math.isfinite(x) and math.isfinite(y))
54
+ self.assertTrue(0 <= x <= 700 and 0 <= y <= 210)
55
+ self.assertEqual(json.loads(json.dumps(result.to_dict()))["text"], result.text)
56
+
57
+ def test_word_toggle_keeps_lines(self):
58
+ with_words = self.ocr(FIXTURES / "receipt.png")
59
+ without_words = self.ocr(FIXTURES / "receipt.png", words=False)
60
+ self.assertEqual(with_words.text, without_words.text)
61
+ self.assertEqual(with_words.lines, without_words.lines)
62
+ self.assertEqual(without_words.words, [])
63
+ self.assertEqual(self.ocr(FIXTURES / "receipt.png").words, with_words.words)
64
+
65
+ def test_blank(self):
66
+ self.assertEqual(self.ocr(FIXTURES / "blank.png").to_dict(), {"text": "", "lines": [], "words": []})
67
+
68
+ def test_missing_and_invalid_image(self):
69
+ with self.assertRaises(FileNotFoundError):
70
+ self.ocr(FIXTURES / "missing.png")
71
+ with tempfile.TemporaryDirectory() as directory:
72
+ path = Path(directory) / "invalid.png"
73
+ path.write_text("not an image", encoding="utf-8")
74
+ with self.assertRaises(Exception):
75
+ self.ocr(path)
76
+
77
+ def test_cli_text_json_version_and_errors(self):
78
+ # The audit hook also forbids network access inside the CLI subprocess.
79
+ bootstrap = (
80
+ "import sys,runpy; "
81
+ "sys.addaudithook(lambda event,args: "
82
+ "(_ for _ in ()).throw(RuntimeError('network forbidden')) "
83
+ "if event == 'socket.connect' else None); "
84
+ "runpy.run_module('tinyocr',run_name='__main__')"
85
+ )
86
+ def cli(*args):
87
+ return subprocess.run([sys.executable, "-c", bootstrap, *map(str, args)],
88
+ capture_output=True, text=True, encoding="utf-8", timeout=60)
89
+ result = cli(FIXTURES / "receipt.png")
90
+ self.assertEqual(result.returncode, 0, result.stderr)
91
+ self.assertEqual(result.stdout.strip(), "HELLO WORLD\nTOTAL 123.45")
92
+ result = cli(FIXTURES / "receipt.png", "--json", "--no-words")
93
+ self.assertEqual(result.returncode, 0, result.stderr)
94
+ data = json.loads(result.stdout)
95
+ self.assertEqual(data["text"], "HELLO WORLD\nTOTAL 123.45")
96
+ self.assertEqual(data["words"], [])
97
+ self.assertEqual(cli("--version").stdout.strip(), "tinyocr-onnx 0.1.0")
98
+ result = cli(FIXTURES / "missing.png")
99
+ self.assertEqual(result.returncode, 2)
100
+ self.assertIn("does not exist", result.stderr)
101
+ self.assertNotIn("Traceback", result.stderr)
102
+ with tempfile.TemporaryDirectory() as directory:
103
+ path = Path(directory) / "invalid.png"
104
+ path.write_text("not an image", encoding="utf-8")
105
+ result = cli(path)
106
+ self.assertEqual(result.returncode, 1)
107
+ self.assertNotIn("Traceback", result.stderr)
108
+
109
+ def test_console_entry_point(self):
110
+ executable = shutil.which("tinyocr")
111
+ self.assertIsNotNone(executable)
112
+ result = subprocess.run([executable, "--version"], capture_output=True, text=True, timeout=30)
113
+ self.assertEqual(result.returncode, 0, result.stderr)
114
+ self.assertEqual(result.stdout.strip(), "tinyocr-onnx 0.1.0")
115
+
116
+
117
+ if __name__ == "__main__":
118
+ unittest.main()