Reza2kn commited on
Commit
2af6ae7
·
verified ·
1 Parent(s): feef108

Complete self-contained Bina 0.2 Rizeh release and quick start

Browse files
LICENSE ADDED
@@ -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.
MODEL_CARD_METRICS.json CHANGED
@@ -1,7 +1,9 @@
1
  {
2
  "model": "Bina 0.2 Rizeh",
3
  "repo": "Reza2kn/Bina-0.2-Rizeh",
 
4
  "benchmark": "Reza2kn/persian-ocr-double-benchmark",
 
5
  "rows_per_split": 6669,
6
  "missing_predictions": 0,
7
  "splits": {
@@ -26,5 +28,10 @@
26
  "s3": 11.7764,
27
  "essential_error": 13.4171,
28
  "triple_threat": 11.4661
 
 
 
 
 
29
  }
30
  }
 
1
  {
2
  "model": "Bina 0.2 Rizeh",
3
  "repo": "Reza2kn/Bina-0.2-Rizeh",
4
+ "parameters": 35578883,
5
  "benchmark": "Reza2kn/persian-ocr-double-benchmark",
6
+ "dataset_revision": "fefe25215114da8ac0ea21ff5e8f97204b2762d5",
7
  "rows_per_split": 6669,
8
  "missing_predictions": 0,
9
  "splits": {
 
28
  "s3": 11.7764,
29
  "essential_error": 13.4171,
30
  "triple_threat": 11.4661
31
+ },
32
+ "triple_threat_weights": {
33
+ "wer": 0.2,
34
+ "cer": 0.2,
35
+ "s3": 0.6
36
  }
37
  }
MODEL_PROVENANCE.json ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema": "bina02.ppocrv6.public-release.v2",
3
+ "model_id": "Reza2kn/Bina-0.2-Rizeh",
4
+ "public_name": "Bina 0.2 Rizeh",
5
+ "family_role": "Medium",
6
+ "architecture": "PP-OCRv6_medium_rec",
7
+ "parameters": 35578883,
8
+ "teacher": null,
9
+ "source_release": "stage8-gate42-20260726",
10
+ "training": {
11
+ "stage8_mix_rows": 2198483,
12
+ "hard_label_loss": "CTC",
13
+ "teacher_logit_distillation": false,
14
+ "eval_linked_checkpoint_selection": true,
15
+ "early_stop_triggered": false,
16
+ "best_handwriting_norm_edit_dis": 0.9671727329321572,
17
+ "best_printed_norm_edit_dis": 0.9071053593763533
18
+ },
19
+ "benchmark": {
20
+ "model": "Bina 0.2 Rizeh",
21
+ "repo": "Reza2kn/Bina-0.2-Rizeh",
22
+ "parameters": 35578883,
23
+ "benchmark": "Reza2kn/persian-ocr-double-benchmark",
24
+ "dataset_revision": "fefe25215114da8ac0ea21ff5e8f97204b2762d5",
25
+ "rows_per_split": 6669,
26
+ "missing_predictions": 0,
27
+ "splits": {
28
+ "handwriting": {
29
+ "wer": 19.0833,
30
+ "cer": 13.6399,
31
+ "s3": 13.7015,
32
+ "essential_error": 14.7567,
33
+ "triple_threat": 14.7656
34
+ },
35
+ "printed": {
36
+ "wer": 8.9257,
37
+ "cer": 2.3535,
38
+ "s3": 9.8512,
39
+ "essential_error": 12.0774,
40
+ "triple_threat": 8.1666
41
+ }
42
+ },
43
+ "macro_equal_split": {
44
+ "wer": 14.0045,
45
+ "cer": 7.9967,
46
+ "s3": 11.7764,
47
+ "essential_error": 13.4171,
48
+ "triple_threat": 11.4661
49
+ },
50
+ "triple_threat_weights": {
51
+ "wer": 0.2,
52
+ "cer": 0.2,
53
+ "s3": 0.6
54
+ }
55
+ },
56
+ "bundled_detector": {
57
+ "repo": "PaddlePaddle/PP-OCRv6_medium_det",
58
+ "revision": "8e0f56fb2ef86b461d99cfc7ac5c137738985f61",
59
+ "license": "Apache-2.0"
60
+ }
61
+ }
QUICKSTART.md ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Bina 0.2 Rizeh: quick start / راه‌اندازی سریع
2
+
3
+ This repository includes both the Persian recognizer and the PP-OCRv6 Medium detector, so the commands below do not download model weights at runtime.
4
+
5
+ این مخزن هم مدل تشخیص متن فارسی و هم آشکارساز PP-OCRv6 Medium را دارد؛ بنابراین هنگام اجرا وزن دیگری دانلود نمی‌شود.
6
+
7
+ ## Install / نصب
8
+
9
+ ```bash
10
+ git lfs install
11
+ git clone https://huggingface.co/Reza2kn/Bina-0.2-Rizeh
12
+ cd Bina-0.2-Rizeh
13
+ python -m pip install "paddlepaddle>=3.2,<4" "paddleocr>=3.3,<4"
14
+ ```
15
+
16
+ The command above installs CPU PaddlePaddle. For NVIDIA GPUs, install the PaddlePaddle GPU wheel matching your CUDA version first, then install `paddleocr>=3.3,<4`.
17
+
18
+ دستور بالا نسخه CPU را نصب می‌کند. برای کارت NVIDIA ابتدا نسخه GPU سازگار با CUDA خود را نصب کنید و سپس PaddleOCR را نصب کنید.
19
+
20
+ ## Full page / صفحه کامل
21
+
22
+ ```bash
23
+ python bina_page_ocr.py page.jpg --device cpu --output result.json
24
+ # NVIDIA example:
25
+ python bina_page_ocr.py page.jpg --device gpu:0 --output result.json
26
+ ```
27
+
28
+ Images and PDFs are accepted. Output is UTF-8 JSON containing page text, logical-order Persian lines, confidence scores, and boxes.
29
+
30
+ ## Line crops / برش خط
31
+
32
+ ```bash
33
+ python bina_text_recognition.py line.jpg --device cpu
34
+ ```
35
+
36
+ Python:
37
+
38
+ ```python
39
+ from bina_text_recognition import BinaTextRecognition
40
+ model = BinaTextRecognition(device="cpu")
41
+ for row in model.predict("line.jpg"):
42
+ print(row["text"], row["score"])
43
+ ```
44
+
45
+ ## Paths / مسیرها
46
+
47
+ - Recognizer: `inference/`
48
+ - Bundled detector: `detector/`
49
+ - Best training checkpoint: `checkpoint/`
50
+ - Exact benchmark evidence: `benchmark/`
README.md CHANGED
@@ -8,6 +8,7 @@ tags:
8
  - ocr
9
  - persian
10
  - handwriting
 
11
  - paddleocr
12
  - pp-ocrv6
13
  - ctc
@@ -18,25 +19,43 @@ datasets:
18
 
19
  # Bina 0.2 Rizeh
20
 
21
- Bina 0.2 Rizeh is a compact Persian printed and handwriting recognizer fine-tuned from the
22
- `PP-OCRv6_medium_rec` architecture. It uses PaddleOCR's CTC recognition head and ships both the
23
- exported inference model and the resumable training checkpoint from the Stage-8 release.
24
 
25
- ## Important model boundary
26
 
27
- The neural checkpoint recognizes **text-line or text-region crops**. It is not, by itself, a
28
- standalone full-page detector. The full-page benchmark below used the included adaptive75
29
- **two-layer pipeline**: page-region detection and template isolation, CTC recognition of the
30
- remaining regions, then reading-order assembly. The scripts used for that exact run are preserved
31
- under `pipeline/` and the benchmark records are under `benchmark/`.
32
 
33
- ## Persian OCR Triple Threat results
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34
 
35
- All 13,338 frozen benchmark rows were scored, with zero missing predictions. Lower is better.
36
- Triple Threat is `20% WER + 20% CER + 60% S3`; Overall is a 50/50 macro-average of the printed and
37
- handwriting splits.
 
 
38
 
39
- | Split | Pages | WER | CER | S3 | Essential error | Triple Threat |
 
 
 
 
 
 
40
  |---|---:|---:|---:|---:|---:|---:|
41
  | Handwriting | 6,669 | 19.0833 | 13.6399 | 13.7015 | 14.7567 | 14.7656 |
42
  | Printed | 6,669 | 8.9257 | 2.3535 | 9.8512 | 12.0774 | 8.1666 |
@@ -44,58 +63,45 @@ handwriting splits.
44
 
45
  Leaderboard: [Persian OCR Triple Threat](https://huggingface.co/spaces/Reza2kn/PersianOCR-TripleThreat)
46
 
47
- The release did **not** reach the single-digit handwriting gate. Printed Triple Threat is already
48
- single digit; handwriting remains the principal limitation.
49
 
50
- ## Training snapshot
 
 
 
 
 
 
 
 
51
 
52
- - Stage-8 training mix: 2,198,483 recognition crops.
53
- - Mix composition: 1,000,000 clean handwriting, 1,000,000 printed, and 198,483 native/form crops.
54
- - Best handwriting validation normalized edit distance: 0.9671727.
55
- - Best printed validation normalized edit distance: 0.9071054.
56
- - Optimizer state was preserved from Stage 4.
57
- - The planned Stage-8 schedule completed without an overfitting stop signal.
58
 
59
- The source pages came from
60
- [`Reza2kn/persian-handwriting-pages-3.69m`](https://huggingface.co/datasets/Reza2kn/persian-handwriting-pages-3.69m)
61
- and
62
- [`Reza2kn/persian-printed-ocr-3.5m`](https://huggingface.co/datasets/Reza2kn/persian-printed-ocr-3.5m),
63
- with line/region preparation and native form replay described by `data/MIX_MANIFEST.json`.
64
 
65
- ## Inference artifacts
66
 
67
- The exported Paddle model is available both at repository root and under `inference/`:
68
 
69
- - `inference.json`
70
- - `inference.pdiparams`
71
- - `inference.yml`
 
 
72
 
73
- With PaddleOCR 3.x, a recognition crop can be run with the custom model directory:
74
 
75
- ```python
76
- from paddleocr import TextRecognition
77
 
78
- recognizer = TextRecognition(model_dir="./inference")
79
- for result in recognizer.predict(input="persian-line.png", batch_size=1):
80
- result.print()
81
- ```
82
-
83
- For page OCR, use a detector/layout stage first and pass its ordered text crops to this recognizer.
84
- The bundled `pipeline/` scripts record the exact full-page benchmark workflow; their original
85
- absolute cluster paths must be adapted to a new machine.
86
 
87
- ## Repository layout
 
 
 
88
 
89
- - `inference/`: exported Paddle inference graph, parameters, and configuration.
90
- - `checkpoint/`: resumable best checkpoint, optimizer state, configs, and eval-gate state.
91
- - `pipeline/`: detection, recognition, assembly, benchmark, and launch scripts.
92
- - `benchmark/`: exact split metrics, logs, and run summaries.
93
- - `data/MIX_MANIFEST.json`: exact Stage-8 train/eval composition.
94
- - `RELEASE.json`: immutable release identity and headline metrics.
95
- - `SHA256SUMS`: checksums for the verified packaged release.
96
 
97
- ## Release identity
98
 
99
- This public model name is **Bina 0.2 Rizeh**. The immutable packaging metadata retains the internal
100
- release name `Bina-0.2-RizehPizeh` and release ID `stage8-gate42-20260726` so it remains traceable to
101
- the exact trained artifact.
 
8
  - ocr
9
  - persian
10
  - handwriting
11
+ - printed-text
12
  - paddleocr
13
  - pp-ocrv6
14
  - ctc
 
19
 
20
  # Bina 0.2 Rizeh
21
 
22
+ Bina 0.2 Rizeh is the **Medium** member of the Bina 0.2 Persian OCR family. It uses the `PP-OCRv6_medium_rec` CTC recognition architecture and contains **35,578,883 parameters (35.579M)**. The model targets Persian handwriting and printed text; preserving unrelated-language quality was not a training goal.
 
 
23
 
24
+ This is a complete recognizer release, not a loose checkpoint: exported inference graph and weights, preprocessing/postprocessing configuration with the embedded Persian character dictionary, best training checkpoint, benchmark provenance, portable logical-order inference wrappers, and an offline full-page detector are included.
25
 
26
+ ## Quick run
 
 
 
 
27
 
28
+ ```bash
29
+ git lfs install
30
+ git clone https://huggingface.co/Reza2kn/Bina-0.2-Rizeh
31
+ cd Bina-0.2-Rizeh
32
+ python -m pip install "paddlepaddle>=3.2,<4" "paddleocr>=3.3,<4"
33
+ python bina_page_ocr.py page.jpg --device cpu --output result.json
34
+ ```
35
+
36
+ For a pre-cropped text line:
37
+
38
+ ```bash
39
+ python bina_text_recognition.py line.jpg --device cpu
40
+ ```
41
+
42
+ See [`QUICKSTART.md`](./QUICKSTART.md) for CPU, NVIDIA, Python, image, and PDF examples in English and Persian.
43
+
44
+ ## What is self-contained?
45
 
46
+ - `inference/` is the exported Bina text recognizer.
47
+ - `detector/` is the pinned official `PaddlePaddle/PP-OCRv6_medium_det` release used for portable full-page OCR.
48
+ - `bina_text_recognition.py` performs logical-order Persian line recognition.
49
+ - `bina_page_ocr.py` detects, recognizes, orders, and emits full-page JSON without downloading model weights.
50
+ - `checkpoint/`, `benchmark/`, `MODEL_PROVENANCE.json`, and `SHA256SUMS` make the release auditable and reusable for continued fine-tuning.
51
 
52
+ The frozen benchmark used a more specialized `adaptive75` two-layer form/template pipeline. The portable full-page CLI is designed for general pages and is not claimed to reproduce that specialized layout isolation exactly.
53
+
54
+ ## Persian OCR Triple Threat
55
+
56
+ All models were evaluated on the same frozen 6,669 printed + 6,669 handwriting rows, with zero missing predictions. Lower is better. Triple Threat is `0.2 × WER + 0.2 × CER + 0.6 × S³`; overall is the equal split macro-average.
57
+
58
+ | Split | Rows | WER | CER | S³ | Essential error | Triple Threat |
59
  |---|---:|---:|---:|---:|---:|---:|
60
  | Handwriting | 6,669 | 19.0833 | 13.6399 | 13.7015 | 14.7567 | 14.7656 |
61
  | Printed | 6,669 | 8.9257 | 2.3535 | 9.8512 | 12.0774 | 8.1666 |
 
63
 
64
  Leaderboard: [Persian OCR Triple Threat](https://huggingface.co/spaces/Reza2kn/PersianOCR-TripleThreat)
65
 
66
+ ## Training and provenance
 
67
 
68
+ - Architecture: `PP-OCRv6_medium_rec`.
69
+ - Public parameter count: `35,578,883`.
70
+ - Stage-8 recognition mix: 2,198,483 rows drawn from Persian handwriting, printed OCR, and native/form replay.
71
+ - Best held-out normalized edit similarity: handwriting `0.9671727`, printed `0.9071054`.
72
+ - Eval-linked checkpoint selection was active. The schedule ended while the selected checkpoint was still improving; no divergence stop fired.
73
+ - Medium training used hard-label CTC and serves as the distillation teacher for the smaller siblings.
74
+ - Frozen benchmark revision: `fefe25215114da8ac0ea21ff5e8f97204b2762d5`.
75
+ - Frozen detection SHA-256: `836044bd3d6dc4c2a66cb8a301e5bf86e48e305a7463ec92eec98f656f46e132`.
76
+ - Internal source release: `stage8-gate42-20260726`.
77
 
78
+ ## Input and output contract
 
 
 
 
 
79
 
80
+ The recognizer works best on horizontal, content-tight line crops. Its exported `inference.yml` is authoritative for resize/padding and the 161-symbol dictionary. The wrappers convert PaddleOCR visual-order Arabic output to logical Persian order while preserving Latin/numeric runs.
 
 
 
 
81
 
82
+ The full-page CLI emits JSON with assembled text plus every recognized line, box, confidence score, and raw visual-order output. For complex forms, grids, multi-column layouts, or exact benchmark reproduction, use the preserved specialized pipeline and layout stages rather than assuming generic detection has perfect reading order.
83
 
84
+ ## Limitations
85
 
86
+ - Persian-focused; other languages were not preserved or benchmarked.
87
+ - Handwriting remains harder than printed text, especially for the smaller siblings.
88
+ - Generic page detection may need layout-specific reading-order logic for forms and multi-column documents.
89
+ - Confidence scores are model scores, not calibrated probabilities.
90
+ - The benchmark measures the bundled family pipeline and should not be interpreted as universal document accuracy.
91
 
92
+ ## فارسی
93
 
94
+ Bina 0.2 Rizeh عضو **متوسط** خانواده OCR فارسی Bina 0.2 است و 35.579 میلیون پارامتر دارد. این مخزن فقط یک checkpoint نیست: مدل inference، تنظیمات و واژه‌نامه کاراکتری، checkpoint آموزش، آشکارساز صفحه، اسکریپت خط و صفحه کامل، نتایج دقیق benchmark و checksumها همگی داخل مخزن هستند.
 
95
 
96
+ اجرای سریع CPU:
 
 
 
 
 
 
 
97
 
98
+ ```bash
99
+ python -m pip install "paddlepaddle>=3.2,<4" "paddleocr>=3.3,<4"
100
+ python bina_page_ocr.py page.jpg --device cpu --output result.json
101
+ ```
102
 
103
+ برای GPU نسخه PaddlePaddle سازگار با CUDA را نصب کنید و `--device gpu:0` بدهید. برای یک خط بریده‌شده از `bina_text_recognition.py` استفاده کنید. خروجی فارسی به ترتیب منطقی خواندن برگردانده می‌شود. جزئیات بیشتر در [`QUICKSTART.md`](./QUICKSTART.md) آمده است.
 
 
 
 
 
 
104
 
105
+ ## License
106
 
107
+ Apache-2.0. The bundled detector is the official Apache-2.0 `PaddlePaddle/PP-OCRv6_medium_det` artifact pinned in `detector/SOURCE.json`.
 
 
RUNTIME_SHA256SUMS ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ b802ea6f182ffb341716b2f649b8f48a2c1f3e4fb6db26f4cfd31771d80cd8b8 inference/inference.json
2
+ f8e1b5b4e9ef11b46c521fed7d1c9b7e7b2d08c4c879aa01353acd7308a6e9fb inference/inference.pdiparams
3
+ 650bfd52635c3a5680479df99a4c5cb3b94e2875b25a7bc3aea45ec1bad6a841 inference/inference.yml
4
+ 3840c5c0c61c294264d2dd77b8777be6ddd90121ef4e0e64abcd22edea581d6e LICENSE
5
+ 9fd4a597a64f4f03ec7056f03514c348f3a25d486a4af8ad7d2af526bddedb63 MODEL_CARD_METRICS.json
6
+ 4704a89e5a5f3ee4ce19f1f1e6050f801efb4c12aaad04207ac2ccf58042090b MODEL_PROVENANCE.json
7
+ 13d7558ea9a87a32d5c314036ca0d3ddccde58f09d59cead52841fbbf9be1a2a QUICKSTART.md
8
+ a146386868a471ed61f3f2914ee201f0212b93bd1271a5c838c523e6ebb127ac README.md
9
+ 19d0372a591ad86dfd22ddac8f4dc9edae1dae0c120fe536cb1d582626a3027c THIRD_PARTY_NOTICES.md
10
+ ad52c0d66e4117d2806c5014f37a9bf8a08788df4f5aa1bea05597bb2b680ba0 bina_page_ocr.py
11
+ b054cde1e6a8842fe0596f38e6a9e762e4c81249c68071306838948a21699e0c bina_text_recognition.py
12
+ cfef0ea9ea896b13d5c433b38dbb48db184bd0f35365120194afd686f278ac58 requirements.txt
13
+ 8ceccaab12056908688a7f31fd28d9efd9f2334a7dccb30df25aa7ca84bdf305 detector/SOURCE.json
14
+ 0f1a7ec35da36173529c7a60238b7f7919e3831929c3f700ad90ad4896adecd5 detector/inference.json
15
+ 85218d2e3d98f5a21c58b4220627be923a97aee5db3cc71f39536ab31ac53960 detector/inference.pdiparams
16
+ 7298d5ead546584af2504d03355f881ac7a7bc0eb1e282d3e159277c1d0af871 detector/inference.yml
THIRD_PARTY_NOTICES.md ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ # Third-party notices
2
+
3
+ The bundled `detector/` artifact is copied without modification from
4
+ [`PaddlePaddle/PP-OCRv6_medium_det`](https://huggingface.co/PaddlePaddle/PP-OCRv6_medium_det) at revision
5
+ `8e0f56fb2ef86b461d99cfc7ac5c137738985f61`. PaddleOCR and that model are distributed under Apache-2.0.
bina_page_ocr.py ADDED
@@ -0,0 +1,123 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Offline full-page Persian OCR using bundled detector plus a Bina recognizer."""
3
+ from __future__ import annotations
4
+ import argparse
5
+ import json
6
+ import re
7
+ from pathlib import Path
8
+ from typing import Any, Iterator
9
+ from paddleocr import PaddleOCR
10
+
11
+ _LTR_RUN = re.compile(r"[a-zA-Z0-9 :*./%+-]")
12
+
13
+ def pred_reverse(text: str) -> str:
14
+ segments: list[str] = []
15
+ current_ltr = ""
16
+ for character in text:
17
+ if _LTR_RUN.search(character):
18
+ current_ltr += character
19
+ continue
20
+ if current_ltr:
21
+ segments.append(current_ltr)
22
+ current_ltr = ""
23
+ segments.append(character)
24
+ if current_ltr:
25
+ segments.append(current_ltr)
26
+ return "".join(reversed(segments))
27
+
28
+ def _json_payload(result: Any) -> dict[str, Any]:
29
+ payload = result.json() if callable(result.json) else result.json
30
+ return payload.get("res", payload)
31
+
32
+ def _box_list(box: Any) -> list[float]:
33
+ if hasattr(box, "tolist"):
34
+ box = box.tolist()
35
+ return [float(value) for value in box]
36
+
37
+ def ordered_lines(payload: dict[str, Any]) -> list[dict[str, Any]]:
38
+ visual_texts = [str(value) for value in payload.get("rec_texts", [])]
39
+ texts = [pred_reverse(value) for value in visual_texts]
40
+ scores = [float(value) for value in payload.get("rec_scores", [0.0] * len(texts))]
41
+ boxes = payload.get("rec_boxes", [])
42
+ if len(boxes) != len(texts):
43
+ return [{"text": text, "score": scores[i], "raw_visual_text": visual_texts[i]} for i, text in enumerate(texts)]
44
+ items = []
45
+ for i, (text, box) in enumerate(zip(texts, boxes)):
46
+ x0, y0, x1, y1 = _box_list(box)
47
+ items.append({
48
+ "text": text,
49
+ "score": scores[i],
50
+ "raw_visual_text": visual_texts[i],
51
+ "box": [x0, y0, x1, y1],
52
+ "x": (x0 + x1) / 2,
53
+ "y": (y0 + y1) / 2,
54
+ "height": max(y1 - y0, 1.0),
55
+ })
56
+ items.sort(key=lambda item: item["y"])
57
+ rows: list[list[dict[str, Any]]] = []
58
+ for item in items:
59
+ if not rows:
60
+ rows.append([item])
61
+ continue
62
+ row = rows[-1]
63
+ mean_y = sum(part["y"] for part in row) / len(row)
64
+ mean_h = sum(part["height"] for part in row) / len(row)
65
+ if abs(item["y"] - mean_y) <= 0.55 * max(item["height"], mean_h):
66
+ row.append(item)
67
+ else:
68
+ rows.append([item])
69
+ output = []
70
+ for row_index, row in enumerate(rows):
71
+ row.sort(key=lambda item: item["x"], reverse=True)
72
+ for item in row:
73
+ output.append({key: value for key, value in item.items() if key not in {"x", "y", "height"}} | {"row": row_index})
74
+ return output
75
+
76
+ class BinaPageOCR:
77
+ def __init__(self, model_dir: str | Path | None = None, detector_dir: str | Path | None = None,
78
+ device: str | None = None, score_threshold: float = 0.0) -> None:
79
+ base = Path(__file__).resolve().parent
80
+ model_dir = Path(model_dir) if model_dir else base / "inference"
81
+ detector_dir = Path(detector_dir) if detector_dir else base / "detector"
82
+ options: dict[str, Any] = {
83
+ "text_detection_model_dir": str(detector_dir),
84
+ "text_recognition_model_dir": str(model_dir),
85
+ "use_doc_orientation_classify": False,
86
+ "use_doc_unwarping": False,
87
+ "use_textline_orientation": False,
88
+ "text_rec_score_thresh": score_threshold,
89
+ }
90
+ if device:
91
+ options["device"] = device
92
+ self._ocr = PaddleOCR(**options)
93
+
94
+ def predict(self, inputs: list[str | Path]) -> Iterator[dict[str, Any]]:
95
+ for source in inputs:
96
+ for page_index, result in enumerate(self._ocr.predict(str(source))):
97
+ raw = _json_payload(result)
98
+ lines = ordered_lines(raw)
99
+ row_text: dict[int, list[str]] = {}
100
+ for line in lines:
101
+ row_text.setdefault(int(line.get("row", len(row_text))), []).append(line["text"])
102
+ text = "\n".join(" ".join(row_text[index]).strip() for index in sorted(row_text) if row_text[index])
103
+ yield {"input_path": str(source), "page_index": page_index, "text": text, "lines": lines}
104
+
105
+ def main() -> int:
106
+ parser = argparse.ArgumentParser(description="Run self-contained full-page Persian OCR with Bina 0.2")
107
+ parser.add_argument("inputs", nargs="+")
108
+ parser.add_argument("--model-dir", default=str(Path(__file__).resolve().parent / "inference"))
109
+ parser.add_argument("--detector-dir", default=str(Path(__file__).resolve().parent / "detector"))
110
+ parser.add_argument("--device", default="cpu", help="cpu, gpu:0, ...")
111
+ parser.add_argument("--score-threshold", type=float, default=0.0)
112
+ parser.add_argument("--output", type=Path)
113
+ args = parser.parse_args()
114
+ model = BinaPageOCR(args.model_dir, args.detector_dir, args.device, args.score_threshold)
115
+ predictions = list(model.predict(args.inputs))
116
+ for prediction in predictions:
117
+ print(json.dumps(prediction, ensure_ascii=False))
118
+ if args.output:
119
+ args.output.write_text(json.dumps(predictions, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
120
+ return 0
121
+
122
+ if __name__ == "__main__":
123
+ raise SystemExit(main())
bina_text_recognition.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Portable logical-order Persian line recognition for the Bina 0.2 family."""
3
+ from __future__ import annotations
4
+ import argparse
5
+ import json
6
+ import re
7
+ from pathlib import Path
8
+ from typing import Any, Iterator
9
+ from paddleocr import TextRecognition
10
+
11
+ _LTR_RUN = re.compile(r"[a-zA-Z0-9 :*./%+-]")
12
+
13
+ def pred_reverse(text: str) -> str:
14
+ """Convert PaddleOCR visual-order Arabic output to logical reading order."""
15
+ segments: list[str] = []
16
+ current_ltr = ""
17
+ for character in text:
18
+ if _LTR_RUN.search(character):
19
+ current_ltr += character
20
+ continue
21
+ if current_ltr:
22
+ segments.append(current_ltr)
23
+ current_ltr = ""
24
+ segments.append(character)
25
+ if current_ltr:
26
+ segments.append(current_ltr)
27
+ return "".join(reversed(segments))
28
+
29
+ class BinaTextRecognition:
30
+ def __init__(self, model_dir: str | Path | None = None, device: str | None = None) -> None:
31
+ model_dir = Path(model_dir) if model_dir else Path(__file__).resolve().parent / "inference"
32
+ options: dict[str, Any] = {"model_dir": str(model_dir)}
33
+ if device:
34
+ options["device"] = device
35
+ self._model = TextRecognition(**options)
36
+
37
+ def predict(self, inputs: str | Path | list[str] | list[Path], batch_size: int = 1) -> Iterator[dict[str, Any]]:
38
+ for result in self._model.predict(input=inputs, batch_size=batch_size):
39
+ payload = result.json() if callable(result.json) else result.json
40
+ raw = payload["res"]
41
+ visual = str(raw["rec_text"])
42
+ yield {
43
+ "input_path": raw.get("input_path"),
44
+ "text": pred_reverse(visual),
45
+ "score": float(raw["rec_score"]),
46
+ "raw_visual_text": visual,
47
+ }
48
+
49
+ def main() -> int:
50
+ parser = argparse.ArgumentParser(description="Recognize Persian text-line crops with Bina 0.2")
51
+ parser.add_argument("images", nargs="+")
52
+ parser.add_argument("--model-dir", default=str(Path(__file__).resolve().parent / "inference"))
53
+ parser.add_argument("--device", default="cpu", help="cpu, gpu:0, ...")
54
+ parser.add_argument("--batch-size", type=int, default=1)
55
+ args = parser.parse_args()
56
+ model = BinaTextRecognition(args.model_dir, device=args.device)
57
+ for prediction in model.predict(args.images, batch_size=args.batch_size):
58
+ print(json.dumps(prediction, ensure_ascii=False))
59
+ return 0
60
+
61
+ if __name__ == "__main__":
62
+ raise SystemExit(main())
detector/SOURCE.json ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ {
2
+ "repo": "PaddlePaddle/PP-OCRv6_medium_det",
3
+ "revision": "8e0f56fb2ef86b461d99cfc7ac5c137738985f61",
4
+ "license": "Apache-2.0",
5
+ "purpose": "Bundled full-page text detector used by bina_page_ocr.py"
6
+ }
detector/inference.json ADDED
The diff for this file is too large to render. See raw diff
 
detector/inference.pdiparams ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:85218d2e3d98f5a21c58b4220627be923a97aee5db3cc71f39536ab31ac53960
3
+ size 61960476
detector/inference.yml ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Global:
2
+ model_name: PP-OCRv6_medium_det
3
+ Hpi:
4
+ backend_configs:
5
+ paddle_infer:
6
+ trt_dynamic_shapes: &id001
7
+ x:
8
+ - - 1
9
+ - 3
10
+ - 32
11
+ - 32
12
+ - - 1
13
+ - 3
14
+ - 736
15
+ - 736
16
+ - - 1
17
+ - 3
18
+ - 4000
19
+ - 4000
20
+ tensorrt:
21
+ dynamic_shapes: *id001
22
+ PostProcess:
23
+ box_thresh: 0.45
24
+ max_candidates: 3000
25
+ name: DBPostProcess
26
+ thresh: 0.2
27
+ unclip_ratio: 1.4
28
+ PreProcess:
29
+ transform_ops:
30
+ - DecodeImage:
31
+ channel_first: false
32
+ img_mode: BGR
33
+ - DetLabelEncode: null
34
+ - DetResizeForTest: null
35
+ - NormalizeImage:
36
+ mean:
37
+ - 0.485
38
+ - 0.456
39
+ - 0.406
40
+ order: hwc
41
+ scale: 1./255.
42
+ std:
43
+ - 0.229
44
+ - 0.224
45
+ - 0.225
46
+ - ToCHWImage: null
47
+ - KeepKeys:
48
+ keep_keys:
49
+ - image
50
+ - shape
51
+ - polys
52
+ - ignore_tags
requirements.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ paddleocr>=3.3.0,<4