ketab-ocr 1.0.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.
- ketab_ocr-1.0.0/.github/workflows/publish.yml +19 -0
- ketab_ocr-1.0.0/.github/workflows/test.yml +20 -0
- ketab_ocr-1.0.0/.gitignore +6 -0
- ketab_ocr-1.0.0/LICENSE +202 -0
- ketab_ocr-1.0.0/PKG-INFO +134 -0
- ketab_ocr-1.0.0/README.md +110 -0
- ketab_ocr-1.0.0/assets/benchmarks.png +0 -0
- ketab_ocr-1.0.0/assets/example_1.png +0 -0
- ketab_ocr-1.0.0/assets/example_2.png +0 -0
- ketab_ocr-1.0.0/assets/example_3.png +0 -0
- ketab_ocr-1.0.0/pyproject.toml +39 -0
- ketab_ocr-1.0.0/src/ketab_ocr/__init__.py +5 -0
- ketab_ocr-1.0.0/src/ketab_ocr/bidi.py +213 -0
- ketab_ocr-1.0.0/src/ketab_ocr/cli.py +24 -0
- ketab_ocr-1.0.0/src/ketab_ocr/ocr.py +132 -0
- ketab_ocr-1.0.0/tests/data/line.png +0 -0
- ketab_ocr-1.0.0/tests/data/line_numbers.png +0 -0
- ketab_ocr-1.0.0/tests/test_bidi.py +18 -0
- ketab_ocr-1.0.0/tests/test_ocr.py +55 -0
- ketab_ocr-1.0.0/train/finetune.py +266 -0
- ketab_ocr-1.0.0/train/requirements.txt +5 -0
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
name: publish
|
|
2
|
+
|
|
3
|
+
on:
|
|
4
|
+
release:
|
|
5
|
+
types: [published]
|
|
6
|
+
|
|
7
|
+
jobs:
|
|
8
|
+
pypi:
|
|
9
|
+
runs-on: ubuntu-latest
|
|
10
|
+
environment: pypi
|
|
11
|
+
permissions:
|
|
12
|
+
id-token: write # trusted publishing: no PyPI token needed
|
|
13
|
+
steps:
|
|
14
|
+
- uses: actions/checkout@v4
|
|
15
|
+
- uses: actions/setup-python@v5
|
|
16
|
+
with:
|
|
17
|
+
python-version: "3.13"
|
|
18
|
+
- run: pip install build && python -m build
|
|
19
|
+
- uses: pypa/gh-action-pypi-publish@release/v1
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
name: test
|
|
2
|
+
|
|
3
|
+
on:
|
|
4
|
+
push:
|
|
5
|
+
branches: [main]
|
|
6
|
+
pull_request:
|
|
7
|
+
|
|
8
|
+
jobs:
|
|
9
|
+
test:
|
|
10
|
+
runs-on: ubuntu-latest
|
|
11
|
+
strategy:
|
|
12
|
+
matrix:
|
|
13
|
+
python-version: ["3.10", "3.13"]
|
|
14
|
+
steps:
|
|
15
|
+
- uses: actions/checkout@v4
|
|
16
|
+
- uses: actions/setup-python@v5
|
|
17
|
+
with:
|
|
18
|
+
python-version: ${{ matrix.python-version }}
|
|
19
|
+
- run: pip install -e ".[test]"
|
|
20
|
+
- run: pytest -v
|
ketab_ocr-1.0.0/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
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 2026 iw4p
|
|
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.
|
|
202
|
+
|
ketab_ocr-1.0.0/PKG-INFO
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: ketab-ocr
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: Fast, accurate OCR for printed Persian text lines (ONNX, CPU)
|
|
5
|
+
Project-URL: Homepage, https://github.com/iw4p/ketab-ocr
|
|
6
|
+
Project-URL: Models, https://huggingface.co/iw4p/ketab-ocr
|
|
7
|
+
Author: iw4p
|
|
8
|
+
License-Expression: Apache-2.0
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Keywords: farsi,ocr,onnx,persian,text-recognition
|
|
11
|
+
Classifier: Natural Language :: Persian
|
|
12
|
+
Classifier: Operating System :: OS Independent
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Topic :: Scientific/Engineering :: Image Recognition
|
|
15
|
+
Requires-Python: >=3.10
|
|
16
|
+
Requires-Dist: huggingface-hub
|
|
17
|
+
Requires-Dist: numpy
|
|
18
|
+
Requires-Dist: onnxruntime
|
|
19
|
+
Requires-Dist: opencv-python-headless
|
|
20
|
+
Requires-Dist: pillow
|
|
21
|
+
Provides-Extra: test
|
|
22
|
+
Requires-Dist: pytest; extra == 'test'
|
|
23
|
+
Description-Content-Type: text/markdown
|
|
24
|
+
|
|
25
|
+
# Ketab OCR – Persian OCR
|
|
26
|
+
|
|
27
|
+
Fast, accurate OCR for printed Persian text lines. Small (5.6 M parameters), runs on CPU with ONNX Runtime,
|
|
28
|
+
about 50 lines per second on a laptop.
|
|
29
|
+
|
|
30
|
+
```bash
|
|
31
|
+
pip install ketab-ocr
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
```python
|
|
35
|
+
from ketab_ocr import KetabOCR
|
|
36
|
+
|
|
37
|
+
ocr = KetabOCR.from_hub() # downloads the model once (v3, default)
|
|
38
|
+
print(ocr.read("line.png")) # a path, a PIL image or a numpy array
|
|
39
|
+
print(ocr.read_many(["line1.png", "line2.png"]))
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
Or from the command line:
|
|
43
|
+
|
|
44
|
+
```bash
|
|
45
|
+
ketab-ocr line.png
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
**Input:** an image of one text line, dark text on a light background. Oversized blank margins are cut off
|
|
49
|
+
automatically (`crop=False` turns that off). Full pages must be split into lines first; page layout is not
|
|
50
|
+
included yet.
|
|
51
|
+
|
|
52
|
+
## Examples
|
|
53
|
+
|
|
54
|
+
Each image below is read with the default model (`v3`):
|
|
55
|
+
|
|
56
|
+

|
|
57
|
+
|
|
58
|
+
```text
|
|
59
|
+
کتاب خواندن بهترین راه برای یادگیری است.
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+

|
|
63
|
+
|
|
64
|
+
```text
|
|
65
|
+
این کتاب در سال ۱۴۰۲ با قیمت ۲۵۰٬۰۰۰ تومان چاپ شد.
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+

|
|
69
|
+
|
|
70
|
+
```text
|
|
71
|
+
نسخهٔ جدید Python 3.13 را نصب کنید (رایگان است).
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
Mixed Persian and English text, numbers and brackets come out in reading order.
|
|
75
|
+
|
|
76
|
+
## Models
|
|
77
|
+
|
|
78
|
+
Models live on Hugging Face: [iw4p/ketab-ocr](https://huggingface.co/iw4p/ketab-ocr). Every version stays
|
|
79
|
+
available, so you can pin one. A new version can be used as soon as it is on Hugging Face, without
|
|
80
|
+
updating the library:
|
|
81
|
+
|
|
82
|
+
```python
|
|
83
|
+
ocr = KetabOCR.from_hub("v4")
|
|
84
|
+
ocr = KetabOCR("path/to/v3.onnx") # or a local file
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
| version | note |
|
|
88
|
+
|---|---|
|
|
89
|
+
| `v3` | default; best on modern print and numbers |
|
|
90
|
+
| `v4` | best on mixed fonts and old books; a zero drawn as a small circle can be read as ۵ |
|
|
91
|
+
|
|
92
|
+
## Train on your own data
|
|
93
|
+
|
|
94
|
+
Fine-tune a released model on your own line images (a laptop is enough for a few thousand lines):
|
|
95
|
+
|
|
96
|
+
```bash
|
|
97
|
+
git clone https://github.com/iw4p/ketab-ocr && cd ketab-ocr
|
|
98
|
+
pip install -r train/requirements.txt
|
|
99
|
+
python train/finetune.py --data my_lines --out my-model.onnx
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
`my_lines/labels.tsv` lists one image per line: `<file name><TAB><text>`. The script starts from `v3`
|
|
103
|
+
(`--base v4` or a `.safetensors` file from an earlier run also work), keeps the best epoch and writes
|
|
104
|
+
`my-model.onnx` for the library plus `my-model.safetensors` to fine-tune further.
|
|
105
|
+
|
|
106
|
+
```python
|
|
107
|
+
ocr = KetabOCR("my-model.onnx")
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
You can share it on Hugging Face as `models/v1.onnx` in your own repo, and others load it with
|
|
111
|
+
`KetabOCR.from_hub("v1", repo_id="you/your-repo")`.
|
|
112
|
+
|
|
113
|
+
## Benchmarks
|
|
114
|
+
|
|
115
|
+
Character error rate on public test sets (lower is better). Details and the full table are on the
|
|
116
|
+
[model page](https://huggingface.co/iw4p/ketab-ocr#benchmarks).
|
|
117
|
+
|
|
118
|
+

|
|
119
|
+
|
|
120
|
+
## Limits
|
|
121
|
+
|
|
122
|
+
- Printed text only, one line at a time (no handwriting, no page layout yet).
|
|
123
|
+
- A long run of the same digit (۰۰۰) can now and then lose one digit.
|
|
124
|
+
|
|
125
|
+
## Development
|
|
126
|
+
|
|
127
|
+
```bash
|
|
128
|
+
pip install -e ".[test]"
|
|
129
|
+
pytest
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
## License
|
|
133
|
+
|
|
134
|
+
Apache-2.0, code and models.
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
# Ketab OCR – Persian OCR
|
|
2
|
+
|
|
3
|
+
Fast, accurate OCR for printed Persian text lines. Small (5.6 M parameters), runs on CPU with ONNX Runtime,
|
|
4
|
+
about 50 lines per second on a laptop.
|
|
5
|
+
|
|
6
|
+
```bash
|
|
7
|
+
pip install ketab-ocr
|
|
8
|
+
```
|
|
9
|
+
|
|
10
|
+
```python
|
|
11
|
+
from ketab_ocr import KetabOCR
|
|
12
|
+
|
|
13
|
+
ocr = KetabOCR.from_hub() # downloads the model once (v3, default)
|
|
14
|
+
print(ocr.read("line.png")) # a path, a PIL image or a numpy array
|
|
15
|
+
print(ocr.read_many(["line1.png", "line2.png"]))
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
Or from the command line:
|
|
19
|
+
|
|
20
|
+
```bash
|
|
21
|
+
ketab-ocr line.png
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
**Input:** an image of one text line, dark text on a light background. Oversized blank margins are cut off
|
|
25
|
+
automatically (`crop=False` turns that off). Full pages must be split into lines first; page layout is not
|
|
26
|
+
included yet.
|
|
27
|
+
|
|
28
|
+
## Examples
|
|
29
|
+
|
|
30
|
+
Each image below is read with the default model (`v3`):
|
|
31
|
+
|
|
32
|
+

|
|
33
|
+
|
|
34
|
+
```text
|
|
35
|
+
کتاب خواندن بهترین راه برای یادگیری است.
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+

|
|
39
|
+
|
|
40
|
+
```text
|
|
41
|
+
این کتاب در سال ۱۴۰۲ با قیمت ۲۵۰٬۰۰۰ تومان چاپ شد.
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+

|
|
45
|
+
|
|
46
|
+
```text
|
|
47
|
+
نسخهٔ جدید Python 3.13 را نصب کنید (رایگان است).
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
Mixed Persian and English text, numbers and brackets come out in reading order.
|
|
51
|
+
|
|
52
|
+
## Models
|
|
53
|
+
|
|
54
|
+
Models live on Hugging Face: [iw4p/ketab-ocr](https://huggingface.co/iw4p/ketab-ocr). Every version stays
|
|
55
|
+
available, so you can pin one. A new version can be used as soon as it is on Hugging Face, without
|
|
56
|
+
updating the library:
|
|
57
|
+
|
|
58
|
+
```python
|
|
59
|
+
ocr = KetabOCR.from_hub("v4")
|
|
60
|
+
ocr = KetabOCR("path/to/v3.onnx") # or a local file
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
| version | note |
|
|
64
|
+
|---|---|
|
|
65
|
+
| `v3` | default; best on modern print and numbers |
|
|
66
|
+
| `v4` | best on mixed fonts and old books; a zero drawn as a small circle can be read as ۵ |
|
|
67
|
+
|
|
68
|
+
## Train on your own data
|
|
69
|
+
|
|
70
|
+
Fine-tune a released model on your own line images (a laptop is enough for a few thousand lines):
|
|
71
|
+
|
|
72
|
+
```bash
|
|
73
|
+
git clone https://github.com/iw4p/ketab-ocr && cd ketab-ocr
|
|
74
|
+
pip install -r train/requirements.txt
|
|
75
|
+
python train/finetune.py --data my_lines --out my-model.onnx
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
`my_lines/labels.tsv` lists one image per line: `<file name><TAB><text>`. The script starts from `v3`
|
|
79
|
+
(`--base v4` or a `.safetensors` file from an earlier run also work), keeps the best epoch and writes
|
|
80
|
+
`my-model.onnx` for the library plus `my-model.safetensors` to fine-tune further.
|
|
81
|
+
|
|
82
|
+
```python
|
|
83
|
+
ocr = KetabOCR("my-model.onnx")
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
You can share it on Hugging Face as `models/v1.onnx` in your own repo, and others load it with
|
|
87
|
+
`KetabOCR.from_hub("v1", repo_id="you/your-repo")`.
|
|
88
|
+
|
|
89
|
+
## Benchmarks
|
|
90
|
+
|
|
91
|
+
Character error rate on public test sets (lower is better). Details and the full table are on the
|
|
92
|
+
[model page](https://huggingface.co/iw4p/ketab-ocr#benchmarks).
|
|
93
|
+
|
|
94
|
+

|
|
95
|
+
|
|
96
|
+
## Limits
|
|
97
|
+
|
|
98
|
+
- Printed text only, one line at a time (no handwriting, no page layout yet).
|
|
99
|
+
- A long run of the same digit (۰۰۰) can now and then lose one digit.
|
|
100
|
+
|
|
101
|
+
## Development
|
|
102
|
+
|
|
103
|
+
```bash
|
|
104
|
+
pip install -e ".[test]"
|
|
105
|
+
pytest
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
## License
|
|
109
|
+
|
|
110
|
+
Apache-2.0, code and models.
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "ketab-ocr"
|
|
7
|
+
dynamic = ["version"]
|
|
8
|
+
description = "Fast, accurate OCR for printed Persian text lines (ONNX, CPU)"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = "Apache-2.0"
|
|
11
|
+
requires-python = ">=3.10"
|
|
12
|
+
authors = [{ name = "iw4p" }]
|
|
13
|
+
keywords = ["ocr", "persian", "farsi", "text-recognition", "onnx"]
|
|
14
|
+
classifiers = [
|
|
15
|
+
"Programming Language :: Python :: 3",
|
|
16
|
+
"Operating System :: OS Independent",
|
|
17
|
+
"Natural Language :: Persian",
|
|
18
|
+
"Topic :: Scientific/Engineering :: Image Recognition",
|
|
19
|
+
]
|
|
20
|
+
dependencies = [
|
|
21
|
+
"huggingface_hub",
|
|
22
|
+
"numpy",
|
|
23
|
+
"onnxruntime",
|
|
24
|
+
"opencv-python-headless",
|
|
25
|
+
"pillow",
|
|
26
|
+
]
|
|
27
|
+
|
|
28
|
+
[project.optional-dependencies]
|
|
29
|
+
test = ["pytest"]
|
|
30
|
+
|
|
31
|
+
[project.scripts]
|
|
32
|
+
ketab-ocr = "ketab_ocr.cli:main"
|
|
33
|
+
|
|
34
|
+
[project.urls]
|
|
35
|
+
Homepage = "https://github.com/iw4p/ketab-ocr"
|
|
36
|
+
Models = "https://huggingface.co/iw4p/ketab-ocr"
|
|
37
|
+
|
|
38
|
+
[tool.hatch.version]
|
|
39
|
+
path = "src/ketab_ocr/__init__.py"
|
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
"""Reading order for mixed right-to-left / left-to-right text.
|
|
2
|
+
|
|
3
|
+
The model reads a line left to right, so its output is in visual order. `logical_from_visual`
|
|
4
|
+
turns that back into the order the text is read and stored in (Unicode bidi, UAX #9).
|
|
5
|
+
`visual_label` does the opposite and is used to check candidates.
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import unicodedata
|
|
10
|
+
|
|
11
|
+
MIRROR = {"(": ")", ")": "(", "[": "]", "]": "[", "{": "}", "}": "{", "<": ">", ">": "<",
|
|
12
|
+
"«": "»", "»": "«", "‹": "›", "›": "‹"}
|
|
13
|
+
BRACKETS = {"(": ")", "[": "]", "{": "}"}
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def logical_from_visual(visual: str) -> str:
|
|
17
|
+
"""Visual (left-to-right) string -> logical reading order."""
|
|
18
|
+
if not _has_rtl(visual):
|
|
19
|
+
return visual
|
|
20
|
+
candidates = [_islands(visual, digits_join=True), _reverse_runs(visual), _islands(visual, digits_join=False)]
|
|
21
|
+
for base in (1, 0): # right-to-left paragraph first, then left-to-right
|
|
22
|
+
for candidate in candidates:
|
|
23
|
+
if visual_label(candidate, base) == visual:
|
|
24
|
+
return candidate
|
|
25
|
+
return candidates[0]
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def visual_label(text: str, base: int = 1) -> str:
|
|
29
|
+
"""Logical text -> the left-to-right order it is displayed in (base 1 = right-to-left paragraph)."""
|
|
30
|
+
levels = bidi_levels(text, base)
|
|
31
|
+
return "".join(MIRROR.get(text[i], text[i]) if levels[i] % 2 else text[i] for i in visual_order(levels))
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def bidi_levels(text: str, base: int = 1) -> list[int]:
|
|
35
|
+
"""Embedding level per character, following the UAX #9 rules named in the comments."""
|
|
36
|
+
n = len(text)
|
|
37
|
+
types = [unicodedata.bidirectional(c) or "ON" for c in text]
|
|
38
|
+
real = [i for i in range(n) if types[i] != "BN"] # X9: boundary neutrals (e.g. ZWNJ) are skipped
|
|
39
|
+
t = [types[i] for i in real]
|
|
40
|
+
sos = "R" if base % 2 else "L"
|
|
41
|
+
embedding = sos
|
|
42
|
+
|
|
43
|
+
for k, x in enumerate(t): # W1
|
|
44
|
+
if x == "NSM":
|
|
45
|
+
t[k] = t[k - 1] if k else sos
|
|
46
|
+
last = sos
|
|
47
|
+
for k, x in enumerate(t): # W2
|
|
48
|
+
if x in ("R", "L", "AL"):
|
|
49
|
+
last = x
|
|
50
|
+
elif x == "EN" and last == "AL":
|
|
51
|
+
t[k] = "AN"
|
|
52
|
+
t = ["R" if x == "AL" else x for x in t] # W3
|
|
53
|
+
for k in range(1, len(t) - 1): # W4
|
|
54
|
+
if t[k] == "ES" and t[k - 1] == "EN" and t[k + 1] == "EN":
|
|
55
|
+
t[k] = "EN"
|
|
56
|
+
elif t[k] == "CS" and t[k - 1] == t[k + 1] and t[k - 1] in ("EN", "AN"):
|
|
57
|
+
t[k] = t[k - 1]
|
|
58
|
+
for start, end in _runs(t, lambda x: x == "ET"): # W5
|
|
59
|
+
if (start > 0 and t[start - 1] == "EN") or (end < len(t) and t[end] == "EN"):
|
|
60
|
+
t[start:end] = ["EN"] * (end - start)
|
|
61
|
+
t = ["ON" if x in ("ES", "ET", "CS") else x for x in t] # W6
|
|
62
|
+
last = sos
|
|
63
|
+
for k, x in enumerate(t): # W7
|
|
64
|
+
if x in ("R", "L"):
|
|
65
|
+
last = x
|
|
66
|
+
elif x == "EN" and last == "L":
|
|
67
|
+
t[k] = "L"
|
|
68
|
+
|
|
69
|
+
# N0: a bracket pair takes the direction of the text inside it
|
|
70
|
+
chars = [text[i] for i in real]
|
|
71
|
+
for open_, close in sorted(_bracket_pairs(chars, t)):
|
|
72
|
+
inside = {_strong(x) for x in t[open_ + 1 : close]} - {None}
|
|
73
|
+
if not inside:
|
|
74
|
+
continue
|
|
75
|
+
if embedding in inside:
|
|
76
|
+
direction = embedding
|
|
77
|
+
else:
|
|
78
|
+
before = next((_strong(t[q]) for q in range(open_ - 1, -1, -1) if _strong(t[q])), sos)
|
|
79
|
+
direction = before
|
|
80
|
+
t[open_] = t[close] = direction
|
|
81
|
+
|
|
82
|
+
neutral = ("B", "S", "WS", "ON") # N1, N2
|
|
83
|
+
for start, end in _runs(t, lambda x: x in neutral):
|
|
84
|
+
before = _as_strong(t[start - 1]) if start > 0 else sos
|
|
85
|
+
after = _as_strong(t[end]) if end < len(t) else sos
|
|
86
|
+
t[start:end] = [before if before == after else embedding] * (end - start)
|
|
87
|
+
|
|
88
|
+
resolved = []
|
|
89
|
+
for x in t: # I1, I2
|
|
90
|
+
if base % 2 == 0:
|
|
91
|
+
resolved.append(base + (1 if x == "R" else 2 if x in ("AN", "EN") else 0))
|
|
92
|
+
else:
|
|
93
|
+
resolved.append(base + (1 if x in ("L", "EN", "AN") else 0))
|
|
94
|
+
levels = [base] * n
|
|
95
|
+
for i, level in zip(real, resolved):
|
|
96
|
+
levels[i] = level
|
|
97
|
+
for i in range(n): # boundary neutrals take their neighbour's level
|
|
98
|
+
if types[i] == "BN":
|
|
99
|
+
levels[i] = levels[i - 1] if i else (levels[i + 1] if i + 1 < n else base)
|
|
100
|
+
i = n - 1
|
|
101
|
+
while i >= 0 and types[i] in ("WS", "BN"): # L1: trailing white space goes to the base level
|
|
102
|
+
levels[i] = base
|
|
103
|
+
i -= 1
|
|
104
|
+
return levels
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def visual_order(levels: list[int]) -> list[int]:
|
|
108
|
+
"""L2: character indices in left-to-right display order."""
|
|
109
|
+
order = list(range(len(levels)))
|
|
110
|
+
odd = [level for level in levels if level % 2]
|
|
111
|
+
if not odd:
|
|
112
|
+
return order
|
|
113
|
+
for level in range(max(levels), min(odd) - 1, -1):
|
|
114
|
+
for start, end in _runs(order, lambda i: levels[i] >= level):
|
|
115
|
+
order[start:end] = order[start:end][::-1]
|
|
116
|
+
return order
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def _strong(x: str) -> str | None:
|
|
120
|
+
return "R" if x in ("R", "EN", "AN") else "L" if x == "L" else None
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def _as_strong(x: str) -> str:
|
|
124
|
+
"""N1: numbers count as right-to-left."""
|
|
125
|
+
return "R" if x in ("R", "EN", "AN") else x
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def _runs(items: list, test) -> list[tuple[int, int]]:
|
|
129
|
+
"""(start, end) of each maximal stretch of items passing `test`."""
|
|
130
|
+
runs, start = [], None
|
|
131
|
+
for k, item in enumerate(items):
|
|
132
|
+
if test(item):
|
|
133
|
+
start = k if start is None else start
|
|
134
|
+
elif start is not None:
|
|
135
|
+
runs.append((start, k))
|
|
136
|
+
start = None
|
|
137
|
+
if start is not None:
|
|
138
|
+
runs.append((start, len(items)))
|
|
139
|
+
return runs
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def _bracket_pairs(chars: list[str], types: list[str]) -> list[tuple[int, int]]:
|
|
143
|
+
stack, pairs = [], []
|
|
144
|
+
for k, ch in enumerate(chars):
|
|
145
|
+
if types[k] != "ON":
|
|
146
|
+
continue
|
|
147
|
+
if ch in BRACKETS:
|
|
148
|
+
if len(stack) < 63:
|
|
149
|
+
stack.append((BRACKETS[ch], k))
|
|
150
|
+
elif ch in BRACKETS.values():
|
|
151
|
+
for depth in range(len(stack) - 1, -1, -1):
|
|
152
|
+
if stack[depth][0] == ch:
|
|
153
|
+
pairs.append((stack[depth][1], k))
|
|
154
|
+
del stack[depth:]
|
|
155
|
+
break
|
|
156
|
+
return pairs
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def _has_rtl(s: str) -> bool:
|
|
160
|
+
return any(unicodedata.bidirectional(c) in ("R", "AL") for c in s)
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def _reverse_runs(visual: str) -> str:
|
|
164
|
+
"""Candidate: reverse the whole line, then restore the order of its left-to-right runs."""
|
|
165
|
+
reversed_ = [MIRROR.get(c, c) for c in visual[::-1]]
|
|
166
|
+
levels = bidi_levels("".join(reversed_), 1)
|
|
167
|
+
out, i = [], 0
|
|
168
|
+
while i < len(reversed_):
|
|
169
|
+
if levels[i] % 2 == 0:
|
|
170
|
+
j = i
|
|
171
|
+
while j < len(reversed_) and levels[j] % 2 == 0:
|
|
172
|
+
j += 1
|
|
173
|
+
out += [MIRROR.get(c, c) for c in reversed_[i:j][::-1]]
|
|
174
|
+
i = j
|
|
175
|
+
else:
|
|
176
|
+
out.append(reversed_[i])
|
|
177
|
+
i += 1
|
|
178
|
+
return "".join(out)
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def _islands(visual: str, digits_join: bool = True) -> str:
|
|
182
|
+
"""Candidate: reverse the line but keep each left-to-right stretch (Latin words, numbers and
|
|
183
|
+
the punctuation between them) together and in its own order."""
|
|
184
|
+
def kind(c: str) -> str:
|
|
185
|
+
b = unicodedata.bidirectional(c)
|
|
186
|
+
if b == "L" or (digits_join and b in ("EN", "AN")):
|
|
187
|
+
return "ltr"
|
|
188
|
+
if b in ("R", "AL"):
|
|
189
|
+
return "rtl"
|
|
190
|
+
return "digit" if b in ("EN", "AN") else "neutral"
|
|
191
|
+
|
|
192
|
+
kinds = [kind(c) for c in visual]
|
|
193
|
+
tokens, i = [], 0
|
|
194
|
+
while i < len(visual):
|
|
195
|
+
if kinds[i] in ("ltr", "digit"):
|
|
196
|
+
k, j, last = kinds[i], i, i
|
|
197
|
+
while j < len(visual) and kinds[j] != "rtl" and not (kinds[j] in ("ltr", "digit") and kinds[j] != k):
|
|
198
|
+
if kinds[j] == k:
|
|
199
|
+
last = j
|
|
200
|
+
j += 1
|
|
201
|
+
# a stretch that opens a bracket also takes its closing bracket
|
|
202
|
+
while last + 1 < len(visual) and visual[last + 1] in ")]}" and _open_brackets(visual[i : last + 1]) > 0:
|
|
203
|
+
last += 1
|
|
204
|
+
tokens.append(visual[i : last + 1])
|
|
205
|
+
i = last + 1
|
|
206
|
+
else:
|
|
207
|
+
tokens.append(MIRROR.get(visual[i], visual[i]))
|
|
208
|
+
i += 1
|
|
209
|
+
return "".join(reversed(tokens))
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def _open_brackets(s: str) -> int:
|
|
213
|
+
return sum(s.count(o) - s.count(c) for o, c in ("()", "[]", "{}"))
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
"""Command line: ketab-ocr line1.png line2.png"""
|
|
2
|
+
import argparse
|
|
3
|
+
|
|
4
|
+
from . import __version__
|
|
5
|
+
from .ocr import DEFAULT_VERSION, KetabOCR
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def main(argv=None):
|
|
9
|
+
parser = argparse.ArgumentParser(prog="ketab-ocr", description="Read printed Persian text line images.")
|
|
10
|
+
parser.add_argument("images", nargs="+", help="images of single text lines")
|
|
11
|
+
parser.add_argument("--version", default=DEFAULT_VERSION, help=f"model version (default: {DEFAULT_VERSION})")
|
|
12
|
+
parser.add_argument("--model", help="path to a local .onnx model instead of downloading one")
|
|
13
|
+
parser.add_argument("--no-crop", action="store_true", help="do not cut oversized blank margins")
|
|
14
|
+
parser.add_argument("-V", action="version", version=f"ketab-ocr {__version__}")
|
|
15
|
+
args = parser.parse_args(argv)
|
|
16
|
+
|
|
17
|
+
ocr = KetabOCR(args.model) if args.model else KetabOCR.from_hub(args.version)
|
|
18
|
+
texts = ocr.read_many(args.images, crop=not args.no_crop)
|
|
19
|
+
for path, text in zip(args.images, texts):
|
|
20
|
+
print(text if len(args.images) == 1 else f"{path}\t{text}")
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
if __name__ == "__main__":
|
|
24
|
+
main()
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
"""Line recognizer: image of one printed text line in, Persian text out."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import json
|
|
5
|
+
import os
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import Iterable, Union
|
|
8
|
+
|
|
9
|
+
import cv2
|
|
10
|
+
import numpy as np
|
|
11
|
+
import onnxruntime as ort
|
|
12
|
+
from PIL import Image
|
|
13
|
+
|
|
14
|
+
from .bidi import logical_from_visual
|
|
15
|
+
|
|
16
|
+
HUB_REPO = "iw4p/ketab-ocr"
|
|
17
|
+
DEFAULT_VERSION = "v3"
|
|
18
|
+
LINE_HEIGHT = 48 # used when a model does not say which line height it reads
|
|
19
|
+
MAX_WIDTH = 1600 # longer lines are squeezed to this width
|
|
20
|
+
BATCH_PIXELS = 64 * 1024
|
|
21
|
+
PAD_RIGHT = 16 # blank columns after each line, as the model saw in training
|
|
22
|
+
|
|
23
|
+
ImageLike = Union[str, Path, Image.Image, np.ndarray]
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class KetabOCR:
|
|
27
|
+
"""Persian OCR for printed text lines.
|
|
28
|
+
|
|
29
|
+
>>> ocr = KetabOCR.from_hub() # downloads the default model once, then uses the cache
|
|
30
|
+
>>> ocr.read("line.png")
|
|
31
|
+
"""
|
|
32
|
+
|
|
33
|
+
def __init__(self, model_path: str | Path, threads: int | None = None):
|
|
34
|
+
options = ort.SessionOptions()
|
|
35
|
+
if threads:
|
|
36
|
+
options.intra_op_num_threads = threads
|
|
37
|
+
self.session = ort.InferenceSession(str(model_path), options, providers=["CPUExecutionProvider"])
|
|
38
|
+
meta = self.session.get_modelmeta().custom_metadata_map
|
|
39
|
+
self.alphabet = json.loads(meta["alphabet"])
|
|
40
|
+
self.version = meta.get("version", "unknown")
|
|
41
|
+
self.line_height = int(meta.get("line_height", LINE_HEIGHT))
|
|
42
|
+
|
|
43
|
+
@classmethod
|
|
44
|
+
def from_hub(cls, version: str = DEFAULT_VERSION, repo_id: str = HUB_REPO, **kwargs) -> "KetabOCR":
|
|
45
|
+
"""Load a model version (e.g. "v3", "v4") from the Hugging Face Hub."""
|
|
46
|
+
from huggingface_hub import hf_hub_download
|
|
47
|
+
|
|
48
|
+
return cls(hf_hub_download(repo_id, f"models/{version}.onnx"), **kwargs)
|
|
49
|
+
|
|
50
|
+
def read(self, image: ImageLike, crop: bool = True) -> str:
|
|
51
|
+
"""Read one text line. `image` is a path, a PIL image or a numpy array."""
|
|
52
|
+
return self.read_many([image], crop=crop)[0]
|
|
53
|
+
|
|
54
|
+
def read_many(self, images: Iterable[ImageLike], crop: bool = True) -> list[str]:
|
|
55
|
+
"""Read many text lines; lines of similar width are batched together."""
|
|
56
|
+
inputs = [preprocess(image, crop, self.line_height) for image in images]
|
|
57
|
+
results = [""] * len(inputs)
|
|
58
|
+
for batch in _batches(inputs):
|
|
59
|
+
width = _round_up(max(inputs[i].shape[1] for i in batch) + PAD_RIGHT, 4)
|
|
60
|
+
x = np.zeros((len(batch), 1, self.line_height, width), np.float32)
|
|
61
|
+
for row, i in enumerate(batch):
|
|
62
|
+
x[row, 0, :, : inputs[i].shape[1]] = inputs[i]
|
|
63
|
+
widths = np.array([inputs[i].shape[1] for i in batch], np.int64)
|
|
64
|
+
logprobs, lengths = self.session.run(None, {"image": x, "widths": widths})
|
|
65
|
+
for row, i in enumerate(batch):
|
|
66
|
+
visual = self._decode(logprobs[row, : lengths[row]])
|
|
67
|
+
results[i] = logical_from_visual(visual).strip()
|
|
68
|
+
return results
|
|
69
|
+
|
|
70
|
+
def _decode(self, logprobs: np.ndarray) -> str:
|
|
71
|
+
"""Greedy CTC decoding (class 0 is the blank). The result is in left-to-right visual order."""
|
|
72
|
+
chars, previous = [], 0
|
|
73
|
+
for k in logprobs.argmax(-1):
|
|
74
|
+
if k != previous and k != 0:
|
|
75
|
+
chars.append(self.alphabet[k - 1])
|
|
76
|
+
previous = k
|
|
77
|
+
return "".join(chars)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def preprocess(image: ImageLike, crop: bool = True, line_height: int = LINE_HEIGHT) -> np.ndarray:
|
|
81
|
+
"""Grayscale, cut oversized margins, scale to `line_height`; ink is 1, paper is 0."""
|
|
82
|
+
gray = to_gray(image)
|
|
83
|
+
if crop:
|
|
84
|
+
gray = trim_margins(gray)
|
|
85
|
+
h, w = gray.shape
|
|
86
|
+
new_width = max(8, min(MAX_WIDTH, round(w * line_height / h)))
|
|
87
|
+
resized = cv2.resize(gray, (new_width, line_height), interpolation=cv2.INTER_AREA)
|
|
88
|
+
return 1.0 - resized.astype(np.float32) / 255.0
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def to_gray(image: ImageLike) -> np.ndarray:
|
|
92
|
+
if isinstance(image, (str, os.PathLike)):
|
|
93
|
+
image = Image.open(image)
|
|
94
|
+
if isinstance(image, np.ndarray):
|
|
95
|
+
if image.ndim == 2:
|
|
96
|
+
return image.astype(np.uint8)
|
|
97
|
+
image = Image.fromarray(image[..., :3].astype(np.uint8))
|
|
98
|
+
return np.asarray(image.convert("L"))
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def trim_margins(gray: np.ndarray, vertical: float = 0.6, horizontal: float = 1.5) -> np.ndarray:
|
|
102
|
+
"""Cut blank margins larger than `vertical` / `horizontal` times the text height.
|
|
103
|
+
|
|
104
|
+
The model was trained on lines cropped close to the text; very wide margins hurt it,
|
|
105
|
+
normal ones do not, so normal margins are left as they are.
|
|
106
|
+
"""
|
|
107
|
+
lo, hi = int(gray.min()), int(gray.max())
|
|
108
|
+
if hi - lo < 40: # blank or no contrast
|
|
109
|
+
return gray
|
|
110
|
+
ink = gray < (lo + hi) / 2
|
|
111
|
+
rows, cols = np.flatnonzero(ink.any(axis=1)), np.flatnonzero(ink.any(axis=0))
|
|
112
|
+
top, bottom, left, right = rows[0], rows[-1] + 1, cols[0], cols[-1] + 1
|
|
113
|
+
text_height = bottom - top
|
|
114
|
+
pad_v = max(2, int(round(vertical * text_height)))
|
|
115
|
+
pad_h = max(2, int(round(horizontal * text_height)))
|
|
116
|
+
return gray[max(0, top - pad_v) : bottom + pad_v, max(0, left - pad_h) : right + pad_h]
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def _batches(inputs: list[np.ndarray]) -> Iterable[list[int]]:
|
|
120
|
+
"""Indices grouped by similar width, each group at most BATCH_PIXELS wide in total."""
|
|
121
|
+
order = sorted(range(len(inputs)), key=lambda i: inputs[i].shape[1])
|
|
122
|
+
start = 0
|
|
123
|
+
while start < len(order):
|
|
124
|
+
end = start + 1
|
|
125
|
+
while end < len(order) and (end - start + 1) * inputs[order[end]].shape[1] <= BATCH_PIXELS:
|
|
126
|
+
end += 1
|
|
127
|
+
yield order[start:end]
|
|
128
|
+
start = end
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def _round_up(n: int, multiple: int) -> int:
|
|
132
|
+
return -(-n // multiple) * multiple
|
|
Binary file
|
|
Binary file
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import pytest
|
|
2
|
+
|
|
3
|
+
from ketab_ocr.bidi import logical_from_visual, visual_label
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
@pytest.mark.parametrize("text", [
|
|
7
|
+
"کتاب خواندن بهترین راه برای یادگیری است.",
|
|
8
|
+
"این کتاب در سال ۱۴۰۲ چاپ شد.",
|
|
9
|
+
"قیمت: 250,000 تومان",
|
|
10
|
+
"نسخهٔ Python 3.12 (جدید) آمد.",
|
|
11
|
+
"میخواهم «کتاب» را بخوانم",
|
|
12
|
+
])
|
|
13
|
+
def test_round_trip(text):
|
|
14
|
+
assert logical_from_visual(visual_label(text)) == text
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def test_left_to_right_text_is_unchanged():
|
|
18
|
+
assert logical_from_visual("Hello 123") == "Hello 123"
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
from pathlib import Path
|
|
2
|
+
|
|
3
|
+
import numpy as np
|
|
4
|
+
import pytest
|
|
5
|
+
|
|
6
|
+
from ketab_ocr import KetabOCR
|
|
7
|
+
from ketab_ocr.ocr import LINE_HEIGHT, preprocess, trim_margins
|
|
8
|
+
|
|
9
|
+
DATA = Path(__file__).parent / "data"
|
|
10
|
+
ASSETS = Path(__file__).parent.parent / "assets"
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def test_trim_cuts_only_oversized_margins():
|
|
14
|
+
page = np.full((300, 600), 255, np.uint8)
|
|
15
|
+
page[100:120, 200:400] = 0 # 20 px high "text"
|
|
16
|
+
trimmed = trim_margins(page)
|
|
17
|
+
assert trimmed.shape == (20 + 2 * 12, 200 + 2 * 30)
|
|
18
|
+
assert trim_margins(trimmed).shape == trimmed.shape # normal margins are kept
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def test_blank_image_is_left_alone():
|
|
22
|
+
blank = np.full((40, 100), 255, np.uint8)
|
|
23
|
+
assert trim_margins(blank) is blank
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def test_preprocess_shape_and_range():
|
|
27
|
+
x = preprocess(DATA / "line.png")
|
|
28
|
+
assert x.shape[0] == LINE_HEIGHT and x.dtype == np.float32
|
|
29
|
+
assert 0.0 <= x.min() and x.max() <= 1.0
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
@pytest.fixture(scope="module")
|
|
33
|
+
def ocr():
|
|
34
|
+
try:
|
|
35
|
+
return KetabOCR.from_hub()
|
|
36
|
+
except Exception as e: # no network or no access to the model repo
|
|
37
|
+
pytest.skip(f"model not available: {e}")
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def test_read(ocr):
|
|
41
|
+
assert ocr.read(DATA / "line.png") == "کتاب خواندن بهترین راه برای یادگیری است."
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def test_read_many_keeps_order(ocr):
|
|
45
|
+
texts = ocr.read_many([DATA / "line_numbers.png", DATA / "line.png"])
|
|
46
|
+
assert texts == ["این کتاب در سال ۱۴۰۲ با قیمت ۲۵۰٬۰۰۰ تومان چاپ شد.", "کتاب خواندن بهترین راه برای یادگیری است."]
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
@pytest.mark.parametrize("name, text", [
|
|
50
|
+
("example_1.png", "کتاب خواندن بهترین راه برای یادگیری است."),
|
|
51
|
+
("example_2.png", "این کتاب در سال ۱۴۰۲ با قیمت ۲۵۰٬۰۰۰ تومان چاپ شد."),
|
|
52
|
+
("example_3.png", "نسخهٔ جدید Python 3.13 را نصب کنید (رایگان است)."),
|
|
53
|
+
])
|
|
54
|
+
def test_readme_examples(ocr, name, text):
|
|
55
|
+
assert ocr.read(ASSETS / name) == text
|
|
@@ -0,0 +1,266 @@
|
|
|
1
|
+
"""Fine-tune Ketab OCR on your own text lines and export an ONNX model the library can load.
|
|
2
|
+
|
|
3
|
+
pip install -r train/requirements.txt
|
|
4
|
+
python train/finetune.py --data my_lines --out my-model.onnx
|
|
5
|
+
|
|
6
|
+
`my_lines/labels.tsv` has one line per image: `<image file name><TAB><text>`.
|
|
7
|
+
Images are single printed text lines, like the ones the library reads.
|
|
8
|
+
|
|
9
|
+
from ketab_ocr import KetabOCR
|
|
10
|
+
ocr = KetabOCR("my-model.onnx")
|
|
11
|
+
"""
|
|
12
|
+
import argparse
|
|
13
|
+
import json
|
|
14
|
+
import random
|
|
15
|
+
import unicodedata
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
|
|
18
|
+
import numpy as np
|
|
19
|
+
import onnx
|
|
20
|
+
import torch
|
|
21
|
+
import torch.nn as nn
|
|
22
|
+
import torch.nn.functional as F
|
|
23
|
+
from huggingface_hub import hf_hub_download
|
|
24
|
+
from safetensors import safe_open
|
|
25
|
+
from safetensors.torch import load_file, save_file
|
|
26
|
+
|
|
27
|
+
from ketab_ocr.bidi import logical_from_visual, visual_label
|
|
28
|
+
from ketab_ocr.ocr import HUB_REPO, MAX_WIDTH, PAD_RIGHT, preprocess
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
# ---- model (same layout as the released weights)
|
|
32
|
+
|
|
33
|
+
class Res(nn.Module):
|
|
34
|
+
def __init__(self, c):
|
|
35
|
+
super().__init__()
|
|
36
|
+
self.a = nn.Sequential(nn.Conv2d(c, c, 3, 1, 1, bias=False), nn.BatchNorm2d(c), nn.GELU(),
|
|
37
|
+
nn.Conv2d(c, c, 3, 1, 1, bias=False), nn.BatchNorm2d(c))
|
|
38
|
+
self.act = nn.GELU()
|
|
39
|
+
|
|
40
|
+
def forward(self, x):
|
|
41
|
+
return self.act(x + self.a(x))
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class Reader(nn.Module):
|
|
45
|
+
"""CNN over the line image -> Transformer over its columns -> one character (or blank) per 4 px, left to right."""
|
|
46
|
+
|
|
47
|
+
def __init__(self, n_classes, d=256, layers=6, heads=4, dropout=0.1):
|
|
48
|
+
super().__init__()
|
|
49
|
+
self.config = dict(n_classes=n_classes, d=d, layers=layers, heads=heads, dropout=dropout)
|
|
50
|
+
self.stem = nn.Sequential(
|
|
51
|
+
nn.Conv2d(1, 32, 3, 2, 1, bias=False), nn.BatchNorm2d(32), nn.GELU(),
|
|
52
|
+
nn.Conv2d(32, 64, 3, 1, 1, bias=False), nn.BatchNorm2d(64), nn.GELU(),
|
|
53
|
+
nn.Conv2d(64, 96, 3, 2, 1, bias=False), nn.BatchNorm2d(96), nn.GELU(),
|
|
54
|
+
Res(96),
|
|
55
|
+
nn.Conv2d(96, 128, 3, (2, 1), 1, bias=False), nn.BatchNorm2d(128), nn.GELU(),
|
|
56
|
+
Res(128),
|
|
57
|
+
)
|
|
58
|
+
self.proj = nn.Linear(128 * 6, d)
|
|
59
|
+
self.pos = nn.Conv1d(d, d, 9, padding=4, groups=d)
|
|
60
|
+
layer = nn.TransformerEncoderLayer(d, heads, 4 * d, dropout=dropout, activation="gelu",
|
|
61
|
+
batch_first=True, norm_first=True)
|
|
62
|
+
self.enc = nn.TransformerEncoder(layer, layers, enable_nested_tensor=False)
|
|
63
|
+
self.norm = nn.LayerNorm(d)
|
|
64
|
+
self.head = nn.Linear(d, n_classes)
|
|
65
|
+
|
|
66
|
+
def forward(self, x, widths):
|
|
67
|
+
"""x: (B, 1, 48, W), ink = 1; widths: (B,). Returns log-probs (B, T, C) and valid lengths (B,)."""
|
|
68
|
+
f = self.stem(x)
|
|
69
|
+
b, c, h, t = f.shape
|
|
70
|
+
z = self.proj(f.permute(0, 3, 1, 2).reshape(b, t, c * h))
|
|
71
|
+
z = z + self.pos(z.transpose(1, 2)).transpose(1, 2)
|
|
72
|
+
lengths = ((widths + 3) // 4).clamp(max=t)
|
|
73
|
+
mask = torch.arange(t, device=x.device)[None] >= lengths.to(x.device)[:, None]
|
|
74
|
+
z = self.enc(z, src_key_padding_mask=mask)
|
|
75
|
+
return self.head(self.norm(z)).log_softmax(-1), lengths
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def load_base(base, repo_id):
|
|
79
|
+
"""A released version ("v3") from the Hub, or a local .safetensors file from an earlier fine-tune."""
|
|
80
|
+
path = base if base.endswith(".safetensors") else hf_hub_download(repo_id, f"pytorch/{base}.safetensors")
|
|
81
|
+
with safe_open(path, "pt") as f:
|
|
82
|
+
meta = f.metadata()
|
|
83
|
+
config, alphabet = json.loads(meta["config"]), json.loads(meta["alphabet"])
|
|
84
|
+
model = Reader(**config)
|
|
85
|
+
model.load_state_dict(load_file(path))
|
|
86
|
+
return model, alphabet, int(meta.get("line_height", 48))
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
# ---- data
|
|
90
|
+
|
|
91
|
+
def load_lines(folder, alphabet, line_height):
|
|
92
|
+
"""labels.tsv -> [(image array, target indices, text)]; lines with unknown characters are skipped."""
|
|
93
|
+
folder = Path(folder)
|
|
94
|
+
index = {ch: i + 1 for i, ch in enumerate(alphabet)} # 0 is the CTC blank
|
|
95
|
+
lines, unknown = [], {}
|
|
96
|
+
for row in (folder / "labels.tsv").read_text(encoding="utf-8").splitlines():
|
|
97
|
+
if not row.strip():
|
|
98
|
+
continue
|
|
99
|
+
name, text = row.split("\t", 1)
|
|
100
|
+
text = unicodedata.normalize("NFC", text.strip())
|
|
101
|
+
visual = visual_label(text, base=0 if _starts_ltr(text) else 1)
|
|
102
|
+
missing = {ch for ch in visual if ch not in index}
|
|
103
|
+
if missing:
|
|
104
|
+
for ch in missing:
|
|
105
|
+
unknown[ch] = unknown.get(ch, 0) + 1
|
|
106
|
+
continue
|
|
107
|
+
image = preprocess(folder / name, line_height=line_height)
|
|
108
|
+
if (image.shape[1] + 3) // 4 < len(visual) + 1: # too narrow to spell the text out
|
|
109
|
+
continue
|
|
110
|
+
lines.append((image, [index[ch] for ch in visual], text))
|
|
111
|
+
if unknown:
|
|
112
|
+
print(f"skipped lines with characters the model does not know: {''.join(sorted(unknown))}")
|
|
113
|
+
return lines
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def _starts_ltr(text):
|
|
117
|
+
for ch in text:
|
|
118
|
+
kind = unicodedata.bidirectional(ch)
|
|
119
|
+
if kind in ("R", "AL"):
|
|
120
|
+
return False
|
|
121
|
+
if kind == "L":
|
|
122
|
+
return True
|
|
123
|
+
return False
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def batches(lines, max_pixels, shuffle):
|
|
127
|
+
"""Lines of similar width together, each batch at most `max_pixels` (lines x width)."""
|
|
128
|
+
order = sorted(range(len(lines)), key=lambda i: lines[i][0].shape[1])
|
|
129
|
+
groups, current = [], []
|
|
130
|
+
for i in order:
|
|
131
|
+
width = lines[i][0].shape[1]
|
|
132
|
+
if current and (len(current) + 1) * width > max_pixels:
|
|
133
|
+
groups.append(current)
|
|
134
|
+
current = []
|
|
135
|
+
current.append(i)
|
|
136
|
+
if current:
|
|
137
|
+
groups.append(current)
|
|
138
|
+
if shuffle:
|
|
139
|
+
random.shuffle(groups)
|
|
140
|
+
return groups
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def collate(lines, ids, line_height):
|
|
144
|
+
width = -(-(max(lines[i][0].shape[1] for i in ids) + PAD_RIGHT) // 4) * 4
|
|
145
|
+
x = np.zeros((len(ids), 1, line_height, width), np.float32)
|
|
146
|
+
for row, i in enumerate(ids):
|
|
147
|
+
x[row, 0, :, : lines[i][0].shape[1]] = lines[i][0]
|
|
148
|
+
widths = torch.tensor([lines[i][0].shape[1] for i in ids])
|
|
149
|
+
targets = torch.tensor([c for i in ids for c in lines[i][1]])
|
|
150
|
+
target_lengths = torch.tensor([len(lines[i][1]) for i in ids])
|
|
151
|
+
return torch.from_numpy(x), widths, targets, target_lengths
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
# ---- training
|
|
155
|
+
|
|
156
|
+
def decode(logprobs, lengths, alphabet):
|
|
157
|
+
texts = []
|
|
158
|
+
for best, n in zip(logprobs.argmax(-1).cpu().numpy(), lengths.tolist()):
|
|
159
|
+
chars, previous = [], 0
|
|
160
|
+
for k in best[:n]:
|
|
161
|
+
if k != previous and k != 0:
|
|
162
|
+
chars.append(alphabet[k - 1])
|
|
163
|
+
previous = k
|
|
164
|
+
texts.append(logical_from_visual("".join(chars)).strip())
|
|
165
|
+
return texts
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def edit_distance(a, b):
|
|
169
|
+
row = list(range(len(b) + 1))
|
|
170
|
+
for i, ca in enumerate(a, 1):
|
|
171
|
+
previous, row[0] = row[0], i
|
|
172
|
+
for j, cb in enumerate(b, 1):
|
|
173
|
+
previous, row[j] = row[j], min(row[j] + 1, row[j - 1] + 1, previous + (ca != cb))
|
|
174
|
+
return row[-1]
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
@torch.no_grad()
|
|
178
|
+
def char_error_rate(model, lines, alphabet, line_height, device, max_pixels):
|
|
179
|
+
model.eval()
|
|
180
|
+
errors = total = 0
|
|
181
|
+
for ids in batches(lines, max_pixels, shuffle=False):
|
|
182
|
+
x, widths, _, _ = collate(lines, ids, line_height)
|
|
183
|
+
logprobs, lengths = model(x.to(device), widths.to(device))
|
|
184
|
+
for i, text in zip(ids, decode(logprobs, lengths, alphabet)):
|
|
185
|
+
errors += edit_distance(text, lines[i][2])
|
|
186
|
+
total += len(lines[i][2])
|
|
187
|
+
model.train()
|
|
188
|
+
return errors / max(total, 1)
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def save(model, alphabet, line_height, path, name):
|
|
192
|
+
"""Write the .onnx model for the library and a .safetensors copy to fine-tune further."""
|
|
193
|
+
meta = {"alphabet": json.dumps(alphabet, ensure_ascii=False), "version": name, "line_height": str(line_height)}
|
|
194
|
+
model = model.cpu().eval()
|
|
195
|
+
weights = {k: v.contiguous() for k, v in model.state_dict().items()}
|
|
196
|
+
save_file(weights, str(Path(path).with_suffix(".safetensors")), metadata={**meta, "config": json.dumps(model.config)})
|
|
197
|
+
|
|
198
|
+
x, widths = torch.zeros(2, 1, line_height, 512), torch.tensor([512, 300])
|
|
199
|
+
batch = torch.export.Dim("batch", min=1, max=1024)
|
|
200
|
+
width4 = torch.export.Dim("width4", min=2, max=MAX_WIDTH // 4)
|
|
201
|
+
program = torch.onnx.export(model, (x, widths), input_names=["image", "widths"], output_names=["logprobs", "lengths"],
|
|
202
|
+
dynamic_shapes={"x": {0: batch, 3: 4 * width4}, "widths": {0: batch}},
|
|
203
|
+
opset_version=18, dynamo=True, external_data=False)
|
|
204
|
+
program.save(path)
|
|
205
|
+
proto = onnx.load(path)
|
|
206
|
+
for key, value in meta.items():
|
|
207
|
+
prop = proto.metadata_props.add()
|
|
208
|
+
prop.key, prop.value = key, value
|
|
209
|
+
onnx.save(proto, path)
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def main():
|
|
213
|
+
parser = argparse.ArgumentParser(description="Fine-tune Ketab OCR on your own text lines.")
|
|
214
|
+
parser.add_argument("--data", required=True, help="folder with labels.tsv and the line images")
|
|
215
|
+
parser.add_argument("--out", required=True, help="where to write the fine-tuned .onnx model")
|
|
216
|
+
parser.add_argument("--base", default="v3", help="version to start from (default: v3) or a .safetensors file")
|
|
217
|
+
parser.add_argument("--repo", default=HUB_REPO)
|
|
218
|
+
parser.add_argument("--epochs", type=int, default=10)
|
|
219
|
+
parser.add_argument("--lr", type=float, default=3e-4)
|
|
220
|
+
parser.add_argument("--val", type=float, default=0.1, help="share of lines held out to measure progress")
|
|
221
|
+
parser.add_argument("--max-pixels", type=int, default=32 * 1024, help="lines x width per batch")
|
|
222
|
+
parser.add_argument("--seed", type=int, default=0)
|
|
223
|
+
args = parser.parse_args()
|
|
224
|
+
|
|
225
|
+
random.seed(args.seed)
|
|
226
|
+
torch.manual_seed(args.seed)
|
|
227
|
+
device = "cuda" if torch.cuda.is_available() else "mps" if torch.backends.mps.is_available() else "cpu"
|
|
228
|
+
|
|
229
|
+
model, alphabet, line_height = load_base(args.base, args.repo)
|
|
230
|
+
model.to(device).train()
|
|
231
|
+
lines = load_lines(args.data, alphabet, line_height)
|
|
232
|
+
random.shuffle(lines)
|
|
233
|
+
n_val = max(1, int(len(lines) * args.val))
|
|
234
|
+
val, train = lines[:n_val], lines[n_val:]
|
|
235
|
+
print(f"{len(train)} training lines, {len(val)} held out, device {device}")
|
|
236
|
+
|
|
237
|
+
best = char_error_rate(model, val, alphabet, line_height, device, args.max_pixels)
|
|
238
|
+
print(f"before: {100 * best:.2f}% character errors on the held-out lines")
|
|
239
|
+
best_state = {k: v.detach().clone() for k, v in model.state_dict().items()}
|
|
240
|
+
optimizer = torch.optim.AdamW(model.parameters(), lr=args.lr, weight_decay=0.01)
|
|
241
|
+
for epoch in range(1, args.epochs + 1):
|
|
242
|
+
total = 0.0
|
|
243
|
+
groups = batches(train, args.max_pixels, shuffle=True)
|
|
244
|
+
for ids in groups:
|
|
245
|
+
x, widths, targets, target_lengths = collate(train, ids, line_height)
|
|
246
|
+
logprobs, lengths = model(x.to(device), widths.to(device))
|
|
247
|
+
# CTC runs on the CPU: not every GPU backend supports it
|
|
248
|
+
loss = F.ctc_loss(logprobs.transpose(0, 1).float().cpu(), targets, lengths.cpu(), target_lengths,
|
|
249
|
+
blank=0, zero_infinity=True)
|
|
250
|
+
optimizer.zero_grad()
|
|
251
|
+
loss.backward()
|
|
252
|
+
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
|
|
253
|
+
optimizer.step()
|
|
254
|
+
total += loss.item()
|
|
255
|
+
cer = char_error_rate(model, val, alphabet, line_height, device, args.max_pixels)
|
|
256
|
+
print(f"epoch {epoch}: loss {total / max(len(groups), 1):.3f}, {100 * cer:.2f}% character errors")
|
|
257
|
+
if cer < best:
|
|
258
|
+
best, best_state = cer, {k: v.detach().clone() for k, v in model.state_dict().items()}
|
|
259
|
+
|
|
260
|
+
model.load_state_dict(best_state)
|
|
261
|
+
save(model, alphabet, line_height, args.out, name=f"{Path(args.base).stem}-finetuned")
|
|
262
|
+
print(f"saved {args.out} ({100 * best:.2f}% character errors on the held-out lines)")
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
if __name__ == "__main__":
|
|
266
|
+
main()
|