nuqta-ocr 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,6 @@
1
+ __pycache__/
2
+ *.egg-info/
3
+ dist/
4
+ .venv/
5
+ .pytest_cache/
6
+ landing/
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,134 @@
1
+ Metadata-Version: 2.5
2
+ Name: nuqta-ocr
3
+ Version: 0.1.0
4
+ Summary: Nuqta OCR: accurate Arabic document OCR with faithful tashkeel (open 0.8B and 4B models)
5
+ Project-URL: Homepage, https://huggingface.co/collections/SalahALHaismawi/nuqta-ocr-6ad4af255195b706ac93d1d4
6
+ Project-URL: Repository, https://github.com/SalahAlHaismawi/nuqta-ocr
7
+ Project-URL: Demo, https://huggingface.co/spaces/SalahALHaismawi/Nuqta-OCR
8
+ Project-URL: Model 4B, https://huggingface.co/SalahALHaismawi/Nuqta-OCR-4B
9
+ Project-URL: Model 0.8B, https://huggingface.co/SalahALHaismawi/Nuqta-OCR-0.8B
10
+ Author: Salah AlHaismawi, Mohamed Saleh Tulib, Ahmed ElSayed Mohamed Ibrahim
11
+ License-Expression: Apache-2.0
12
+ License-File: LICENSE
13
+ Keywords: arabic,arabic-ocr,diacritics,document-ai,handwriting,mrz,ocr,passport,pdf-to-markdown,tashkeel,vlm
14
+ Classifier: Development Status :: 4 - Beta
15
+ Classifier: Intended Audience :: Developers
16
+ Classifier: Intended Audience :: Science/Research
17
+ Classifier: License :: OSI Approved :: Apache Software License
18
+ Classifier: Natural Language :: Arabic
19
+ Classifier: Programming Language :: Python :: 3
20
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
21
+ Classifier: Topic :: Scientific/Engineering :: Image Recognition
22
+ Classifier: Topic :: Text Processing :: Linguistic
23
+ Requires-Python: >=3.10
24
+ Requires-Dist: accelerate>=1.0
25
+ Requires-Dist: pillow>=10
26
+ Requires-Dist: pypdfium2>=4
27
+ Requires-Dist: torch>=2.4
28
+ Requires-Dist: torchvision
29
+ Requires-Dist: transformers>=4.57
30
+ Provides-Extra: bench
31
+ Requires-Dist: apted>=1.0.3; extra == 'bench'
32
+ Requires-Dist: beautifulsoup4>=4.12; extra == 'bench'
33
+ Requires-Dist: distance>=0.1.3; extra == 'bench'
34
+ Requires-Dist: httpx>=0.27; extra == 'bench'
35
+ Requires-Dist: huggingface-hub>=0.24; extra == 'bench'
36
+ Requires-Dist: levenshtein>=0.25; extra == 'bench'
37
+ Requires-Dist: lxml>=5; extra == 'bench'
38
+ Requires-Dist: pyarrow>=14; extra == 'bench'
39
+ Requires-Dist: sacrebleu<3,>=2.4; extra == 'bench'
40
+ Provides-Extra: dev
41
+ Requires-Dist: pytest>=8; extra == 'dev'
42
+ Provides-Extra: fast
43
+ Requires-Dist: causal-conv1d>=1.5; extra == 'fast'
44
+ Requires-Dist: flash-linear-attention>=0.5; extra == 'fast'
45
+ Provides-Extra: vllm
46
+ Requires-Dist: vllm>=0.19; extra == 'vllm'
47
+ Description-Content-Type: text/markdown
48
+
49
+ <p align="center"><img src="https://raw.githubusercontent.com/SalahAlHaismawi/nuqta-ocr/main/assets/nuqta_logo.png" alt="Nuqta OCR" width="440"></p>
50
+
51
+ # Nuqta OCR
52
+
53
+ Accurate Arabic document OCR with **faithful tashkeel**, in two open models: **Nuqta-OCR 4B** (#1 on KITAB-Bench and Misraj-DocOCR among published results) and **Nuqta-OCR 0.8B** (best for its size: ahead of Gemini-2.0-Flash, level with or slightly ahead of Baseer, runs on phones).
54
+
55
+ - Reads books, scans, official documents, tables, IDs and passports
56
+ - Copies the tashkeel printed on the page and almost never adds any (0.08–0.16 invented marks per 100 letters)
57
+ - Markdown output with HTML tables, in reading order
58
+ - Runs on-premises on a single GPU: your documents never leave your network
59
+
60
+ ## Install
61
+
62
+ ```bash
63
+ pip install "nuqta-ocr[vllm]" # recommended: fast, batched (Linux + NVIDIA GPU)
64
+ pip install "nuqta-ocr[fast]" # transformers + fast kernels (no vLLM needed)
65
+ pip install nuqta-ocr # transformers only (slow on long pages)
66
+ ```
67
+
68
+ ## Quick start
69
+
70
+ ```python
71
+ from nuqta import OCR
72
+
73
+ if __name__ == "__main__": # required with the vLLM backend (it starts worker processes)
74
+ ocr = OCR("nuqta-0.8b") # or "nuqta-4b" (most accurate)
75
+
76
+ print(ocr.read("page.jpg").text) # as written: tashkeel only where printed
77
+ print(ocr.read("scan.pdf", mode="markdown").text) # headings, lists, HTML tables; every page
78
+ print(ocr.read("passport.jpg", mode="id").fields) # MRZ fields + check digits
79
+
80
+ results = ocr.read_many(["a.jpg", "b.png", "c.pdf"]) # batched with vLLM
81
+ ```
82
+
83
+ Command line:
84
+
85
+ ```bash
86
+ nuqta read page.jpg
87
+ nuqta read scan.pdf --mode markdown
88
+ nuqta read passport.jpg --mode id --json
89
+ ```
90
+
91
+ ## Modes
92
+
93
+ | mode | output |
94
+ |---|---|
95
+ | `as-written` (default) | the text exactly as printed, tashkeel only where it is printed |
96
+ | `bare` | the text without any tashkeel |
97
+ | `markdown` | headings, paragraphs, lists and tables (HTML) in reading order |
98
+ | `id` | `markdown` reading + structured fields: passport / visa / ID-card MRZ with ICAO check digits; Egyptian national ID fields cross-checked against the national number |
99
+
100
+ ## What the library does for you
101
+
102
+ - **Page rule:** full pages are shown to the model at its training resolution (2.4 MP); word, line and card crops keep their size. Small page renders (e.g. 72-dpi PDF pages) otherwise lose letters.
103
+ - **Loop guard:** if a page reading repeats itself, the page is re-read at its native size; any repetition left is trimmed (`Page.looped` tells you).
104
+ - **PDFs:** every page rendered at 200 dpi.
105
+ - **ID checks:** a failed check digit or an inconsistent national number is reported, never silently "fixed". Send those fields to a human.
106
+
107
+ ## Speed (0.8B, one 24 GB GPU)
108
+
109
+ | | vLLM | transformers + `[fast]` |
110
+ |---|---|---|
111
+ | text line | ~0.2 s | ~1 s |
112
+ | book page | ~3 s | ~3.5 s |
113
+ | markdown document page | ~3 s | ~6 s |
114
+
115
+ ## Results
116
+
117
+ | | KITAB-Bench CER ↓ | Misraj-DocOCR MARS ↑ |
118
+ |---|---|---|
119
+ | **Nuqta-OCR 4B** | **0.106** | **82.8** |
120
+ | **Nuqta-OCR 0.8B** | **0.117** | **77.1** |
121
+ | Previous best (Gemini-2.0-Flash / Baseer) | 0.13 | 76.9 |
122
+
123
+ Recommended input size (what the library does). The 0.8B's lead over Baseer is within the benchmark's noise.
124
+
125
+ Full tables, confidence intervals and disclosures are in the model cards; the full benchmarks are
126
+ [KITAB-Bench](https://github.com/mbzuai-oryx/KITAB-Bench) and [Misraj-DocOCR](https://huggingface.co/datasets/Misraj/Misraj-DocOCR).
127
+
128
+ ## License
129
+
130
+ Code: Apache-2.0. Models: see their model cards.
131
+
132
+ ## Contributors
133
+
134
+ Salah AlHaismawi · Mohamed Saleh Tulib · Ahmed ElSayed Mohamed Ibrahim
@@ -0,0 +1,86 @@
1
+ <p align="center"><img src="https://raw.githubusercontent.com/SalahAlHaismawi/nuqta-ocr/main/assets/nuqta_logo.png" alt="Nuqta OCR" width="440"></p>
2
+
3
+ # Nuqta OCR
4
+
5
+ Accurate Arabic document OCR with **faithful tashkeel**, in two open models: **Nuqta-OCR 4B** (#1 on KITAB-Bench and Misraj-DocOCR among published results) and **Nuqta-OCR 0.8B** (best for its size: ahead of Gemini-2.0-Flash, level with or slightly ahead of Baseer, runs on phones).
6
+
7
+ - Reads books, scans, official documents, tables, IDs and passports
8
+ - Copies the tashkeel printed on the page and almost never adds any (0.08–0.16 invented marks per 100 letters)
9
+ - Markdown output with HTML tables, in reading order
10
+ - Runs on-premises on a single GPU: your documents never leave your network
11
+
12
+ ## Install
13
+
14
+ ```bash
15
+ pip install "nuqta-ocr[vllm]" # recommended: fast, batched (Linux + NVIDIA GPU)
16
+ pip install "nuqta-ocr[fast]" # transformers + fast kernels (no vLLM needed)
17
+ pip install nuqta-ocr # transformers only (slow on long pages)
18
+ ```
19
+
20
+ ## Quick start
21
+
22
+ ```python
23
+ from nuqta import OCR
24
+
25
+ if __name__ == "__main__": # required with the vLLM backend (it starts worker processes)
26
+ ocr = OCR("nuqta-0.8b") # or "nuqta-4b" (most accurate)
27
+
28
+ print(ocr.read("page.jpg").text) # as written: tashkeel only where printed
29
+ print(ocr.read("scan.pdf", mode="markdown").text) # headings, lists, HTML tables; every page
30
+ print(ocr.read("passport.jpg", mode="id").fields) # MRZ fields + check digits
31
+
32
+ results = ocr.read_many(["a.jpg", "b.png", "c.pdf"]) # batched with vLLM
33
+ ```
34
+
35
+ Command line:
36
+
37
+ ```bash
38
+ nuqta read page.jpg
39
+ nuqta read scan.pdf --mode markdown
40
+ nuqta read passport.jpg --mode id --json
41
+ ```
42
+
43
+ ## Modes
44
+
45
+ | mode | output |
46
+ |---|---|
47
+ | `as-written` (default) | the text exactly as printed, tashkeel only where it is printed |
48
+ | `bare` | the text without any tashkeel |
49
+ | `markdown` | headings, paragraphs, lists and tables (HTML) in reading order |
50
+ | `id` | `markdown` reading + structured fields: passport / visa / ID-card MRZ with ICAO check digits; Egyptian national ID fields cross-checked against the national number |
51
+
52
+ ## What the library does for you
53
+
54
+ - **Page rule:** full pages are shown to the model at its training resolution (2.4 MP); word, line and card crops keep their size. Small page renders (e.g. 72-dpi PDF pages) otherwise lose letters.
55
+ - **Loop guard:** if a page reading repeats itself, the page is re-read at its native size; any repetition left is trimmed (`Page.looped` tells you).
56
+ - **PDFs:** every page rendered at 200 dpi.
57
+ - **ID checks:** a failed check digit or an inconsistent national number is reported, never silently "fixed". Send those fields to a human.
58
+
59
+ ## Speed (0.8B, one 24 GB GPU)
60
+
61
+ | | vLLM | transformers + `[fast]` |
62
+ |---|---|---|
63
+ | text line | ~0.2 s | ~1 s |
64
+ | book page | ~3 s | ~3.5 s |
65
+ | markdown document page | ~3 s | ~6 s |
66
+
67
+ ## Results
68
+
69
+ | | KITAB-Bench CER ↓ | Misraj-DocOCR MARS ↑ |
70
+ |---|---|---|
71
+ | **Nuqta-OCR 4B** | **0.106** | **82.8** |
72
+ | **Nuqta-OCR 0.8B** | **0.117** | **77.1** |
73
+ | Previous best (Gemini-2.0-Flash / Baseer) | 0.13 | 76.9 |
74
+
75
+ Recommended input size (what the library does). The 0.8B's lead over Baseer is within the benchmark's noise.
76
+
77
+ Full tables, confidence intervals and disclosures are in the model cards; the full benchmarks are
78
+ [KITAB-Bench](https://github.com/mbzuai-oryx/KITAB-Bench) and [Misraj-DocOCR](https://huggingface.co/datasets/Misraj/Misraj-DocOCR).
79
+
80
+ ## License
81
+
82
+ Code: Apache-2.0. Models: see their model cards.
83
+
84
+ ## Contributors
85
+
86
+ Salah AlHaismawi · Mohamed Saleh Tulib · Ahmed ElSayed Mohamed Ibrahim
@@ -0,0 +1,11 @@
1
+ # Nuqta OCR
2
+
3
+ > Nuqta OCR is an open-weights Arabic OCR system: Nuqta-OCR 4B (#1 on KITAB-Bench and Misraj-DocOCR among published results) and the compact Nuqta-OCR 0.8B (runs on phones as GGUF). It converts Arabic scans, photos and PDFs (books, official documents, tables, IDs and passports) into text or Markdown with HTML tables, and copies the tashkeel (diacritics) printed on the page, almost never adding any. Apache-2.0.
4
+
5
+ - Install: `pip install "nuqta-ocr[vllm]"`; use: `from nuqta import OCR; OCR("nuqta-4b").read("page.jpg").text`
6
+ - Modes: as-written (tashkeel as printed), bare, markdown (tables as HTML), id (MRZ + ID fields with check digits)
7
+ - Results 4B: KITAB-Bench CER 0.106 (Gemini-2.0-Flash 0.13); Misraj-DocOCR MARS 82.8 (Baseer 76.9), TEDS 76.1, CER 0.121
8
+ - Results 0.8B: KITAB-Bench CER 0.117; Misraj-DocOCR MARS 77.1 (within noise of Baseer)
9
+ - Models: https://huggingface.co/SalahALHaismawi/Nuqta-OCR-4B, https://huggingface.co/SalahALHaismawi/Nuqta-OCR-0.8B
10
+ - GGUF (llama.cpp, offline): https://huggingface.co/SalahALHaismawi/Nuqta-OCR-0.8B-GGUF, https://huggingface.co/SalahALHaismawi/Nuqta-OCR-4B-GGUF
11
+ - Demo: https://huggingface.co/spaces/SalahALHaismawi/Nuqta-OCR · Code: https://github.com/SalahAlHaismawi/nuqta-ocr
@@ -0,0 +1,65 @@
1
+ [project]
2
+ name = "nuqta-ocr"
3
+ version = "0.1.0"
4
+ description = "Nuqta OCR: accurate Arabic document OCR with faithful tashkeel (open 0.8B and 4B models)"
5
+ readme = "README.md"
6
+ license = "Apache-2.0"
7
+ requires-python = ">=3.10"
8
+ authors = [{ name = "Salah AlHaismawi" }, { name = "Mohamed Saleh Tulib" }, { name = "Ahmed ElSayed Mohamed Ibrahim" }]
9
+ classifiers = [
10
+ "Development Status :: 4 - Beta",
11
+ "Intended Audience :: Developers",
12
+ "Intended Audience :: Science/Research",
13
+ "License :: OSI Approved :: Apache Software License",
14
+ "Natural Language :: Arabic",
15
+ "Programming Language :: Python :: 3",
16
+ "Topic :: Scientific/Engineering :: Artificial Intelligence",
17
+ "Topic :: Scientific/Engineering :: Image Recognition",
18
+ "Topic :: Text Processing :: Linguistic",
19
+ ]
20
+ keywords = ["arabic", "ocr", "arabic-ocr", "tashkeel", "diacritics", "document-ai", "pdf-to-markdown", "handwriting", "passport", "mrz", "vlm"]
21
+ dependencies = [
22
+ "pillow>=10",
23
+ "pypdfium2>=4",
24
+ "torch>=2.4",
25
+ "torchvision",
26
+ "transformers>=4.57",
27
+ "accelerate>=1.0",
28
+ ]
29
+
30
+ [project.optional-dependencies]
31
+ vllm = ["vllm>=0.19"]
32
+ fast = ["flash-linear-attention>=0.5", "causal-conv1d>=1.5"] # fast kernels for the transformers backend
33
+ dev = ["pytest>=8"]
34
+ # benchmarks/ (run.py + score.py): dataset download, endpoint client and the official KITAB-Bench / Misraj scoring
35
+ bench = [
36
+ "huggingface_hub>=0.24",
37
+ "pyarrow>=14",
38
+ "httpx>=0.27",
39
+ "levenshtein>=0.25", # python-Levenshtein's maintained name, same distance
40
+ "sacrebleu>=2.4,<3", # KITAB-Bench pins 2.5.1; the published numbers were scored with 2.6.0
41
+ "apted>=1.0.3", # TEDS (KITAB-Bench pdfs-eval/teds_metric.py)
42
+ "distance>=0.1.3",
43
+ "lxml>=5",
44
+ "beautifulsoup4>=4.12",
45
+ ]
46
+
47
+ [project.urls]
48
+ Homepage = "https://huggingface.co/collections/SalahALHaismawi/nuqta-ocr-6ad4af255195b706ac93d1d4"
49
+ Repository = "https://github.com/SalahAlHaismawi/nuqta-ocr"
50
+ Demo = "https://huggingface.co/spaces/SalahALHaismawi/Nuqta-OCR"
51
+ "Model 4B" = "https://huggingface.co/SalahALHaismawi/Nuqta-OCR-4B"
52
+ "Model 0.8B" = "https://huggingface.co/SalahALHaismawi/Nuqta-OCR-0.8B"
53
+
54
+ [project.scripts]
55
+ nuqta = "nuqta.cli:main"
56
+
57
+ [build-system]
58
+ requires = ["hatchling"]
59
+ build-backend = "hatchling.build"
60
+
61
+ [tool.hatch.build.targets.wheel]
62
+ packages = ["src/nuqta"]
63
+
64
+ [tool.hatch.build.targets.sdist]
65
+ include = ["/src/nuqta", "/tests", "/README.md", "/LICENSE", "/pyproject.toml", "/llms.txt"]
@@ -0,0 +1,7 @@
1
+ """Nuqta OCR: accurate Arabic document OCR with faithful tashkeel."""
2
+ from .ocr import OCR, Page, Result, read_fields
3
+ from .preprocess import is_page, prepare
4
+ from .text import MODES, PROMPTS, looped, trim_loops
5
+
6
+ __all__ = ["OCR", "Page", "Result", "read_fields", "is_page", "prepare", "MODES", "PROMPTS", "looped", "trim_loops"]
7
+ __version__ = "0.1.0"
@@ -0,0 +1,79 @@
1
+ """Generation backends: Hugging Face transformers (default) and vLLM (fast batched serving, optional).
2
+
3
+ Both decode greedily (temperature 0, no repetition penalty), with thinking disabled: the settings the published
4
+ benchmark numbers were measured with.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import base64
9
+ import io
10
+
11
+ from PIL import Image
12
+
13
+ MAX_NEW_TOKENS = 8192
14
+
15
+
16
+ def _data_url(im: Image.Image) -> str:
17
+ buf = io.BytesIO()
18
+ im.save(buf, format="PNG")
19
+ return "data:image/png;base64," + base64.b64encode(buf.getvalue()).decode()
20
+
21
+
22
+ class TransformersBackend:
23
+ def __init__(self, model: str, device_map: str = "auto", dtype: str = "bfloat16"):
24
+ import torch
25
+ from transformers import AutoModelForImageTextToText, AutoProcessor
26
+
27
+ self.torch = torch
28
+ self.processor = AutoProcessor.from_pretrained(model)
29
+ self.model = AutoModelForImageTextToText.from_pretrained(model, dtype=getattr(torch, dtype),
30
+ device_map=device_map)
31
+ self.model.eval()
32
+ # stop at the end of the answer turn: the checkpoints' generation_config names only <|endoftext|>, so without
33
+ # this generate() runs on into new chat turns up to max_new_tokens (vLLM stops via the chat template)
34
+ tok = self.processor.tokenizer
35
+ self.eos = [i for i in {tok.convert_tokens_to_ids("<|im_end|>"), tok.eos_token_id,
36
+ tok.convert_tokens_to_ids("<|endoftext|>")} if isinstance(i, int) and i >= 0]
37
+
38
+ def generate(self, items: list[tuple[Image.Image, str]], max_new_tokens: int = MAX_NEW_TOKENS) -> list[str]:
39
+ out = []
40
+ for im, prompt in items: # one at a time: pages differ a lot in size, padding a batch wastes memory
41
+ msgs = [{"role": "user", "content": [{"type": "image", "image": im}, {"type": "text", "text": prompt}]}]
42
+ inputs = self.processor.apply_chat_template(msgs, add_generation_prompt=True, tokenize=True,
43
+ return_dict=True, return_tensors="pt",
44
+ enable_thinking=False).to(self.model.device)
45
+ with self.torch.inference_mode():
46
+ ids = self.model.generate(**inputs, max_new_tokens=max_new_tokens, do_sample=False, eos_token_id=self.eos,
47
+ pad_token_id=self.eos[0])
48
+ out.append(self.processor.decode(ids[0, inputs["input_ids"].shape[1]:], skip_special_tokens=True))
49
+ return out
50
+
51
+
52
+ class VLLMBackend:
53
+ def __init__(self, model: str, gpu_memory_utilization: float = 0.85, max_model_len: int = 16384, **kw):
54
+ from vllm import LLM, SamplingParams
55
+
56
+ self.llm = LLM(model=model, gpu_memory_utilization=gpu_memory_utilization, max_model_len=max_model_len,
57
+ limit_mm_per_prompt={"image": 1}, **kw)
58
+ self.SamplingParams = SamplingParams
59
+
60
+ def generate(self, items: list[tuple[Image.Image, str]], max_new_tokens: int = MAX_NEW_TOKENS) -> list[str]:
61
+ convs = [[{"role": "user", "content": [{"type": "image_url", "image_url": {"url": _data_url(im)}},
62
+ {"type": "text", "text": prompt}]}] for im, prompt in items]
63
+ sp = self.SamplingParams(temperature=0.0, max_tokens=max_new_tokens, repetition_penalty=1.0)
64
+ res = self.llm.chat(convs, sp, chat_template_kwargs={"enable_thinking": False}, use_tqdm=False)
65
+ return [r.outputs[0].text for r in res]
66
+
67
+
68
+ def make_backend(model: str, backend: str = "auto", **kw):
69
+ if backend == "auto":
70
+ try:
71
+ import vllm # noqa: F401
72
+ backend = "vllm"
73
+ except ImportError:
74
+ backend = "transformers"
75
+ if backend == "vllm":
76
+ return VLLMBackend(model, **kw)
77
+ if backend == "transformers":
78
+ return TransformersBackend(model, **kw)
79
+ raise ValueError(f"unknown backend {backend!r} (auto, transformers, vllm)")
@@ -0,0 +1,42 @@
1
+ """nuqta read FILE [FILE ...] [--mode as-written|bare|markdown|id] [--model PATH_OR_HUB_ID] [--json]"""
2
+ from __future__ import annotations
3
+
4
+ import argparse
5
+ import json
6
+ import sys
7
+
8
+ from .text import MODES
9
+
10
+ DEFAULT_MODEL = "nuqta-0.8b"
11
+
12
+
13
+ def main(argv: list[str] | None = None) -> None:
14
+ ap = argparse.ArgumentParser(prog="nuqta", description="Nuqta OCR: Arabic document OCR with faithful tashkeel")
15
+ sub = ap.add_subparsers(dest="cmd", required=True)
16
+ r = sub.add_parser("read", help="read images / PDFs and print the text")
17
+ r.add_argument("files", nargs="+")
18
+ r.add_argument("--mode", default="as-written", choices=MODES + ("id",))
19
+ r.add_argument("--model", default=DEFAULT_MODEL)
20
+ r.add_argument("--backend", default="auto", choices=["auto", "transformers", "vllm"])
21
+ r.add_argument("--no-enlarge", action="store_true", help="read pages at their native size")
22
+ r.add_argument("--json", action="store_true", help="one JSON object per file (text, pages, fields)")
23
+ a = ap.parse_args(argv)
24
+
25
+ from .ocr import OCR
26
+
27
+ ocr = OCR(a.model, backend=a.backend, enlarge_pages=not a.no_enlarge)
28
+ for f, res in zip(a.files, ocr.read_many(a.files, mode=a.mode)):
29
+ if a.json:
30
+ print(json.dumps({"file": f, "mode": res.mode, "text": res.text, "fields": res.fields,
31
+ "pages": [vars(p) for p in res.pages]}, ensure_ascii=False, default=str))
32
+ else:
33
+ if len(a.files) > 1:
34
+ print(f"==> {f} <==")
35
+ print(res.text)
36
+ if res.fields:
37
+ print(json.dumps(res.fields, ensure_ascii=False, indent=1, default=str))
38
+ sys.stdout.flush()
39
+
40
+
41
+ if __name__ == "__main__":
42
+ main()
@@ -0,0 +1,151 @@
1
+ """Egyptian national ID card (بطاقة تحقيق الشخصية) reading -> fields (2026-10-14).
2
+
3
+ The card prints no field labels: the front is header, first name, the rest of the name, address lines, (birth date),
4
+ the 14-digit national number and the card serial; the back is the national number, the issue month, profession lines,
5
+ sex, religion, marital status and «البطاقة سارية حتى <expiry>». Fields are taken by line position and shape.
6
+
7
+ The national number is self-describing: digit 1 the century (2 = 19xx, 3 = 20xx), 2-7 the birth date YYMMDD, 8-9 the
8
+ governorate of birth, 13 odd for a man, even for a woman. `nid_info` decodes it; the decoded birth date / sex /
9
+ governorate cross-check the printed values (a misread digit rarely keeps them consistent; the address is where the
10
+ holder lives now, so a different governorate is no error).
11
+ """
12
+ import re
13
+ from datetime import date
14
+
15
+ _AI = str.maketrans("٠١٢٣٤٥٦٧٨٩۰۱۲۳۴۵۶۷۸۹", "01234567890123456789")
16
+ _TO_AI = str.maketrans("0123456789", "٠١٢٣٤٥٦٧٨٩")
17
+ GOV = {"01": "القاهرة", "02": "الإسكندرية", "03": "بورسعيد", "04": "السويس", "11": "دمياط", "12": "الدقهلية",
18
+ "13": "الشرقية", "14": "القليوبية", "15": "كفر الشيخ", "16": "الغربية", "17": "المنوفية", "18": "البحيرة",
19
+ "19": "الإسماعيلية", "21": "الجيزة", "22": "بني سويف", "23": "الفيوم", "24": "المنيا", "25": "أسيوط",
20
+ "26": "سوهاج", "27": "قنا", "28": "أسوان", "29": "الأقصر", "31": "البحر الأحمر", "32": "الوادي الجديد",
21
+ "33": "مطروح", "34": "شمال سيناء", "35": "جنوب سيناء", "88": "خارج الجمهورية"}
22
+ # spellings on cards / in addresses that differ from GOV («اسكندرية», «الاسماعيلية», «بنى سويف», ...)
23
+ _GOV_KEYS = {g: {re.sub("[أإآ]", "ا", g).replace("ى", "ي"), re.sub("^ال", "", re.sub("[أإآ]", "ا", g)).replace("ى", "ي")}
24
+ for g in GOV.values()}
25
+ _HEAD = re.compile(r"جمهورية\s+مصر\s+العربية|بطاقة\s+تحقيق\s+الشخصية")
26
+ _NID = re.compile(r"(?<![\d٠-٩])[23٢٣](?:\s?[\d٠-٩]){13}(?![\d٠-٩])")
27
+ _DATE = re.compile(r"[\d٠-٩]{4}\s*/\s*[\d٠-٩]{1,2}(?:\s*/\s*[\d٠-٩]{1,2})?")
28
+ _SEX = {"ذكر", "أنثى", "انثى", "انثي"}
29
+ _RELIGION = re.compile(r"^(?:مسلم|مسلمة|مسلمه|مسيحي|مسيحى|مسيحية|مسيحيه|يهودي|يهودى)$")
30
+ _MARITAL = re.compile(r"^(?:أعزب|اعزب|عزباء|آنسة|انسة|آنسه|انسه|متزوج|متزوجة|متزوجه|مطلق|مطلقة|مطلقه|أرمل|ارمل|أرملة|ارملة|ارمله)$")
31
+ _SERIAL = re.compile(r"^[A-Z]{1,3}\s?[\d٠-٩]{6,8}$|^[\d٠-٩]{8}[\d٠-٩A-Z]?$")
32
+
33
+
34
+ def looks_egyptian(text: str) -> bool:
35
+ return bool(_HEAD.search(text) or ("سارية حتى" in text and _NID.search(text)))
36
+
37
+
38
+ def nid_info(nid: str) -> dict | None:
39
+ """Decode a 14-digit national number; None when it cannot be one (bad century / date / governorate)."""
40
+ d = re.sub(r"\D", "", nid.translate(_AI))
41
+ if len(d) != 14 or d[0] not in "23":
42
+ return None
43
+ try:
44
+ dob = date((1900 if d[0] == "2" else 2000) + int(d[1:3]), int(d[3:5]), int(d[5:7]))
45
+ except ValueError:
46
+ return None
47
+ if d[7:9] not in GOV:
48
+ return None
49
+ return {"dob": dob, "gov": GOV[d[7:9]], "sex": "ذكر" if int(d[12]) % 2 else "أنثى"}
50
+
51
+
52
+ def _date(v: str):
53
+ m = re.fullmatch(r"(\d{4})/(\d{1,2})/(\d{1,2})", re.sub(r"\s", "", v.translate(_AI)))
54
+ try:
55
+ return date(int(m[1]), int(m[2]), int(m[3])) if m else None
56
+ except ValueError:
57
+ return None
58
+
59
+
60
+ def gov_in(gov: str, text: str) -> bool:
61
+ t = re.sub("[أإآ]", "ا", text).replace("ى", "ي")
62
+ return any(k in t for k in _GOV_KEYS.get(gov, ()))
63
+
64
+
65
+ def parse(text: str) -> dict:
66
+ """Fields of an Egyptian ID front or back reading; {} when it is not one."""
67
+ if not looks_egyptian(text):
68
+ return {}
69
+ lines = [re.sub(r"\*\*|</?t[dhr]>|^#+\s*", "", x).strip() for x in text.split("\n")]
70
+ lines = [x for x in lines if x and not re.fullmatch(r"<img>.*?</img>|image here", x) and not _HEAD.fullmatch(x)]
71
+ f: dict[str, str] = {}
72
+ words, addr = [], []
73
+ back = any("سارية حتى" in x for x in lines) or any(x in _SEX or _RELIGION.match(x) for x in lines)
74
+ for x in lines:
75
+ if _HEAD.search(x):
76
+ continue
77
+ m = _NID.search(x)
78
+ if m and "nid" not in f:
79
+ f["nid"] = m.group(0)
80
+ continue
81
+ if "سارية حتى" in x:
82
+ d = _DATE.search(x)
83
+ if d:
84
+ f["doe"] = d.group(0)
85
+ else:
86
+ f["_doe_next"] = "1"
87
+ continue
88
+ d = _DATE.fullmatch(x)
89
+ if d:
90
+ if f.pop("_doe_next", None):
91
+ f["doe"] = x
92
+ elif back and x.count("/") + x.count("/") == 1:
93
+ f.setdefault("doi", x) # the back prints the issue month «٢٠١٥/١١»
94
+ elif not back:
95
+ # newer fronts print the expiry too («٢٠٣٠/٠٢»): a date after the card could have been issued
96
+ y = int(re.sub(r"\D", "", x.translate(_AI))[:4])
97
+ f.setdefault("doe" if y > 2010 or x.count("/") == 1 else "dob", x)
98
+ else:
99
+ f.setdefault("doe" if "doi" in f else "doi", x)
100
+ continue
101
+ if _SERIAL.match(x) and "nid" in f and not back:
102
+ f.setdefault("no", x)
103
+ continue
104
+ if x in _SEX:
105
+ f["sex"] = x
106
+ continue
107
+ if _RELIGION.match(x):
108
+ f["religion"] = x
109
+ continue
110
+ if _MARITAL.match(x):
111
+ f["marital"] = x
112
+ continue
113
+ if re.fullmatch(r"[\d٠-٩]{1,2}", x): # husband's name line / card copy number «١»
114
+ continue
115
+ if re.search("[ء-ي]", x):
116
+ (words if back else (words if len(words) < 2 and "nid" not in f and not addr else addr)).append(x)
117
+ f.pop("_doe_next", None)
118
+ if back:
119
+ if words:
120
+ f["prof"] = " ".join(words)
121
+ else:
122
+ if words:
123
+ f["name"] = " ".join(words)
124
+ if addr:
125
+ f["address"] = " ".join(addr)
126
+ f.setdefault("nat", "مصري")
127
+ return f
128
+
129
+
130
+ def check(f: dict, conf: dict) -> None:
131
+ """Cross-check / fill from the national number: birth date, sex, governorate of birth (front address)."""
132
+ info = nid_info(f.get("nid", ""))
133
+ if not f.get("nid"):
134
+ return
135
+ if not info:
136
+ conf["nid"] = "check" # cannot be a national number: a digit is misread
137
+ return
138
+ ok = True
139
+ if f.get("dob"):
140
+ ok &= _date(f["dob"]) == info["dob"]
141
+ else:
142
+ f["dob"] = info["dob"].strftime("%Y/%m/%d").translate(_TO_AI)
143
+ conf["dob"] = "nid"
144
+ if not f.get("pob"):
145
+ f["pob"], conf["pob"] = info["gov"], "nid" # governorate of birth
146
+ if f.get("sex"):
147
+ ok &= (f["sex"] == "ذكر") == (info["sex"] == "ذكر")
148
+ else:
149
+ f["sex"], conf["sex"] = info["sex"], "nid"
150
+ # the governorate of birth is often the address one too, but people move: agreement is evidence, not a rule
151
+ conf["nid"] = ("verified" if conf.get("dob") != "nid" or gov_in(info["gov"], f.get("address", "")) else "agreed") if ok else "check"
@@ -0,0 +1,130 @@
1
+ """Passport / ID machine-readable zone (ICAO 9303) from an OCR reading (2026-10-13).
2
+
3
+ parse_mrz(text) finds the MRZ lines in a model reading (TD3 passports 2 x 44, TD2 2 x 36, TD1 ID cards 3 x 30),
4
+ (visas MRV-A 2 x 44 / MRV-B 2 x 36: document code V, no composite check digit)
5
+ splits them into fields, checks every check digit and, given the whole reading, whether the number and dates also
6
+ appear in the printed (visual) zone. Nothing is corrected silently: a failed check digit is reported as failed.
7
+ The model may drop trailing '<' filler, so lines are padded to the format length; a field that falls in the
8
+ missing part is reported as unread.
9
+ """
10
+ import re
11
+ from datetime import date
12
+
13
+ _LINE = re.compile(r"^[A-Z0-9<]{20,50}$")
14
+ _WEIGHTS = (7, 3, 1)
15
+ _MONTHS = ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"]
16
+ _TAG = re.compile(r"</?(?:td|th|tr|p|br|div|span|b|strong|em|i|code)\b[^<>]*>", re.IGNORECASE)
17
+
18
+
19
+ def check_digit(s: str) -> str:
20
+ """ICAO 9303 check digit: weights 7, 3, 1; '<' = 0, A-Z = 10-35."""
21
+ total = 0
22
+ for i, c in enumerate(s):
23
+ v = int(c) if c.isdigit() else (ord(c) - 55 if "A" <= c <= "Z" else 0)
24
+ total += v * _WEIGHTS[i % 3]
25
+ return str(total % 10)
26
+
27
+
28
+ def _candidates(text: str) -> list[str]:
29
+ out = []
30
+ for raw in text.splitlines():
31
+ s = _TAG.sub("", raw) # markup the reading may wrap around the line (<td>, <p>); MRZ '<' is not a tag
32
+ s = re.sub(r"\s+", "", s).upper().replace("«", "<").replace("‹", "<")
33
+ # a line with no '<' (TD3 line 2 with a full optional field) counts only when long and number-heavy
34
+ ok = _LINE.match(s) and ("<" in s or (len(s) >= 28 and sum(c.isdigit() for c in s) >= 6))
35
+ out.append(s if ok else "")
36
+ return out
37
+
38
+
39
+ def _groups(lines: list[str]) -> list[list[str]]:
40
+ groups, cur = [], []
41
+ for s in lines + [""]:
42
+ if s:
43
+ cur.append(s)
44
+ elif cur:
45
+ if any("<" in x for x in cur):
46
+ groups.append(cur)
47
+ cur = []
48
+ return groups
49
+
50
+
51
+ def _fmt(lines: list[str]) -> tuple[str, int] | None:
52
+ if len(lines) >= 3:
53
+ return "TD1", 30
54
+ if len(lines) == 2:
55
+ n = max(len(x) for x in lines)
56
+ return ("TD2", 36) if abs(n - 36) < abs(n - 44) and not lines[0].startswith("P") else ("TD3", 44)
57
+ return None
58
+
59
+
60
+ def _names(s: str) -> tuple[str, str]:
61
+ s = s.rstrip("<")
62
+ sur, _, given = s.partition("<<")
63
+ return sur.replace("<", " ").strip(), given.replace("<", " ").strip()
64
+
65
+
66
+ def _date(yymmdd: str, future: bool) -> str | None:
67
+ if not re.fullmatch(r"\d{6}", yymmdd):
68
+ return None
69
+ yy, mm, dd = int(yymmdd[:2]), int(yymmdd[2:4]), int(yymmdd[4:])
70
+ now = date.today().year % 100
71
+ year = 2000 + yy if (future or yy <= now) else 1900 + yy
72
+ try:
73
+ return date(year, mm, dd).strftime("%d-%m-%Y")
74
+ except ValueError:
75
+ return None
76
+
77
+
78
+ def _check(value: str, digit: str) -> bool | None:
79
+ if not value or not digit or "<" * len(value) == value and digit == "<":
80
+ return None # unread (missing filler part) or an empty optional field
81
+ return check_digit(value) == digit
82
+
83
+
84
+ def parse_mrz(text: str) -> dict | None:
85
+ """The first MRZ block in `text` as fields + check-digit results, or None."""
86
+ for g in _groups(_candidates(text)):
87
+ f = _fmt(g)
88
+ if not f:
89
+ continue
90
+ kind, n = f
91
+ ls = [x[:n].ljust(n, "<") for x in g[: 3 if kind == "TD1" else 2]]
92
+ cut = [len(x) for x in g] # how much of each line was actually read
93
+ if kind == "TD1":
94
+ a, b, c = ls
95
+ num, nd, dob, dd, sex, exp, ed = a[5:14], a[14], b[0:6], b[6], b[7], b[8:14], b[14]
96
+ out = {"format": "TD1 (ID card)", "doc_type": a[0:2].strip("<"), "issuer": a[2:5], "nationality": b[15:18]}
97
+ sur, given = _names(c)
98
+ comp = (a[5:30] + b[0:7] + b[8:15] + b[18:29], b[29]) if cut[1] >= 30 else None
99
+ else:
100
+ a, b = ls
101
+ num, nd, dob, dd, sex, exp, ed = b[0:9], b[9], b[13:19], b[19], b[20], b[21:27], b[27]
102
+ visa = a[0] == "V" # MRV: the optional data runs to the end of line 2, there is no composite digit
103
+ out = {"format": ("MRV-A (visa)" if n == 44 else "MRV-B (visa)") if visa else "TD3 (passport)" if kind == "TD3" else "TD2",
104
+ "doc_type": a[0:2].strip("<"), "issuer": a[2:5], "nationality": b[10:13]}
105
+ sur, given = _names(a[5:])
106
+ last = n - 1
107
+ comp = (b[0:10] + b[13:20] + b[21:last], b[last]) if cut[1] >= n and not visa else None
108
+ out.update({"surname": sur, "given_names": given, "number": num.rstrip("<"), "sex": sex.replace("<", "X"),
109
+ "birth": _date(dob, False), "expiry": _date(exp, True)})
110
+ checks = {"number": _check(num, nd), "birth": _check(dob, dd), "expiry": _check(exp, ed)}
111
+ if comp:
112
+ checks["composite"] = _check(*comp)
113
+ out["checks"] = checks
114
+ out["valid"] = all(v is not False for v in checks.values()) and any(v for v in checks.values())
115
+ out["lines"] = g
116
+ # cross-check with the printed (visual) zone of the same reading (the MRZ lines themselves left out)
117
+ vis = "\n".join(x for x in text.splitlines() if re.sub(r"\s+", "", _TAG.sub("", x)).upper() not in g)
118
+ flat = re.sub(r"\s+", "", vis)
119
+ seen = {}
120
+ if out["number"]:
121
+ seen["number"] = out["number"] in flat
122
+ for k in ("birth", "expiry"):
123
+ if out[k]:
124
+ d, m, y = out[k].split("-")
125
+ mon = _MONTHS[int(m) - 1]
126
+ seen[k] = any(v in flat.upper() for v in (f"{d}-{m}-{y}", f"{d}/{m}/{y}", f"{d}.{m}.{y}", f"{y}-{m}-{d}",
127
+ f"{y}/{m}/{d}", f"{d}{mon}{y}", f"{d}{mon}{y[2:]}"))
128
+ out["printed_match"] = seen
129
+ return out
130
+ return None
@@ -0,0 +1,123 @@
1
+ """Nuqta OCR: the main entry point."""
2
+ from __future__ import annotations
3
+
4
+ from dataclasses import dataclass, field
5
+ from pathlib import Path
6
+
7
+ from PIL import Image
8
+
9
+ from . import egyid, mrz
10
+ from .backends import MAX_NEW_TOKENS, make_backend
11
+ from .preprocess import load_image, plain, prepare
12
+ from .text import MODES, PROMPTS, clean, looped, trim_loops
13
+
14
+
15
+ @dataclass
16
+ class Page:
17
+ text: str
18
+ looped: bool = False # even the fallback reading repeated itself (text was trimmed)
19
+ fallback: bool = False # the page was re-read at native size because the first reading looped
20
+
21
+
22
+ @dataclass
23
+ class Result:
24
+ pages: list[Page]
25
+ mode: str
26
+ fields: dict = field(default_factory=dict) # mode="id" only
27
+
28
+ @property
29
+ def text(self) -> str:
30
+ return "\n\n".join(p.text for p in self.pages)
31
+
32
+ def __str__(self) -> str:
33
+ return self.text
34
+
35
+
36
+ def _pdf_pages(path: Path, dpi: int = 200) -> list[Image.Image]:
37
+ import pypdfium2 as pdfium
38
+
39
+ doc = pdfium.PdfDocument(str(path))
40
+ return [doc[i].render(scale=dpi / 72).to_pil().convert("RGB") for i in range(len(doc))]
41
+
42
+
43
+ MODELS = {"nuqta-0.8b": "SalahALHaismawi/Nuqta-OCR-0.8B", "nuqta-4b": "SalahALHaismawi/Nuqta-OCR-4B"}
44
+
45
+
46
+ class OCR:
47
+ """Read Arabic documents.
48
+
49
+ ocr = OCR("nuqta-0.8b") # or "nuqta-4b", a hub id or a local path
50
+ ocr.read("page.jpg").text # as written: tashkeel only where printed
51
+ ocr.read("scan.pdf", mode="markdown") # headings, lists, HTML tables, every page
52
+ ocr.read("passport.jpg", mode="id").fields
53
+
54
+ Modes: as-written (default), bare (no tashkeel), markdown, id.
55
+ backend: "auto" (vLLM when installed, else transformers), "transformers" or "vllm".
56
+ """
57
+
58
+ def __init__(self, model: str, backend: str = "auto", enlarge_pages: bool = True, **backend_kw):
59
+ self.backend = make_backend(MODELS.get(model.lower(), model), backend, **backend_kw)
60
+ self.enlarge_pages = enlarge_pages
61
+
62
+ # -- reading
63
+ def _read_images(self, images: list[Image.Image], prompt: str, max_new_tokens: int) -> list[Page]:
64
+ first = [prepare(im, self.enlarge_pages) for im in images]
65
+ outs = [clean(t) for t in self.backend.generate([(im, prompt) for im in first], max_new_tokens)]
66
+ pages = [Page(t) for t in outs]
67
+ # loop fallback: re-read a looping page at its native size (if that is a different input)
68
+ redo = [i for i, t in enumerate(outs) if looped(t) and first[i].size != plain(images[i]).size]
69
+ if redo:
70
+ again = [clean(t) for t in self.backend.generate([(plain(images[i]), prompt) for i in redo], max_new_tokens)]
71
+ for i, t in zip(redo, again):
72
+ if not looped(t):
73
+ pages[i] = Page(t, fallback=True)
74
+ for p in pages:
75
+ if looped(p.text):
76
+ p.text, p.looped = trim_loops(p.text), True
77
+ return pages
78
+
79
+ def read(self, src, mode: str = "as-written", max_new_tokens: int = MAX_NEW_TOKENS) -> Result:
80
+ """Read one image (path, bytes or PIL image) or a PDF (every page)."""
81
+ return self.read_many([src], mode, max_new_tokens)[0]
82
+
83
+ def read_many(self, srcs: list, mode: str = "as-written", max_new_tokens: int = MAX_NEW_TOKENS) -> list[Result]:
84
+ """Read several files; with the vLLM backend they are batched."""
85
+ if mode not in MODES + ("id",):
86
+ raise ValueError(f"mode must be one of {MODES + ('id',)}")
87
+ prompt = PROMPTS["markdown" if mode == "id" else mode]
88
+ images, owner = [], []
89
+ for k, src in enumerate(srcs):
90
+ if isinstance(src, (str, Path)) and str(src).lower().endswith(".pdf"):
91
+ ims = _pdf_pages(Path(src))
92
+ else:
93
+ ims = [load_image(src)]
94
+ images += ims
95
+ owner += [k] * len(ims)
96
+ pages = self._read_images(images, prompt, max_new_tokens)
97
+ results = [Result([], mode) for _ in srcs]
98
+ for k, p in zip(owner, pages):
99
+ results[k].pages.append(p)
100
+ if mode == "id":
101
+ for r in results:
102
+ r.fields = read_fields(r.text)
103
+ return results
104
+
105
+
106
+ def read_fields(text: str) -> dict:
107
+ """Structured fields from an ID / passport reading, with validity checks.
108
+
109
+ mrz: the machine-readable zone (passports, visas, TD1 cards): fields + ICAO check digits ("valid") and
110
+ whether the number and dates also appear in the printed zone.
111
+ egyptian: Egyptian national ID fields; the 14-digit national number is decoded and cross-checked against the
112
+ printed birth date and sex ("nid": verified / agreed / check). "check" = a digit is probably misread.
113
+ A failed check means: send this field to a human. Nothing is corrected silently."""
114
+ out: dict = {}
115
+ m = mrz.parse_mrz(text)
116
+ if m:
117
+ out["mrz"] = {k: v for k, v in m.items() if k != "lines"}
118
+ e = egyid.parse(text)
119
+ if e:
120
+ conf: dict = {}
121
+ egyid.check(e, conf)
122
+ out["egyptian"] = {"fields": e, "checks": conf}
123
+ return out
@@ -0,0 +1,60 @@
1
+ """Image input policy: what the model saw in training, so what it should see at inference.
2
+
3
+ * Pages (page-shaped images: aspect <= 2 and short side >= 450 px) are enlarged to the training size, 2.4 MP.
4
+ Small page renders (e.g. 612x792 PDF pages with ~10 px text) otherwise lose letters and loop; on our held-out
5
+ page sets this never hurt and cut handwritten-page errors by 41%.
6
+ * Crops (words, lines, paragraphs, cards: everything not page-shaped) keep their size. Enlarging crops hurt
7
+ (word crops: +90% CER at 2.4 MP).
8
+ * Every image is capped at 2.4 MP, the training cap.
9
+ * Transparent PNGs are composited onto white (a plain RGB conversion turns transparent pixels black).
10
+ """
11
+ from __future__ import annotations
12
+
13
+ import io
14
+ from pathlib import Path
15
+
16
+ from PIL import Image
17
+
18
+ TRAIN_PIXELS = 2_400_000
19
+ PAGE_MIN_SHORT_SIDE = 450
20
+ PAGE_MAX_ASPECT = 2.0
21
+
22
+
23
+ def load_image(src) -> Image.Image:
24
+ """A path, bytes or a PIL image -> an RGB PIL image."""
25
+ if isinstance(src, Image.Image):
26
+ im = src
27
+ elif isinstance(src, (bytes, bytearray)):
28
+ im = Image.open(io.BytesIO(src))
29
+ else:
30
+ im = Image.open(Path(src))
31
+ if im.mode in ("RGBA", "LA", "PA") or (im.mode == "P" and "transparency" in im.info):
32
+ im = im.convert("RGBA")
33
+ bg = Image.new("RGBA", im.size, (255, 255, 255, 255))
34
+ im = Image.alpha_composite(bg, im)
35
+ return im.convert("RGB")
36
+
37
+
38
+ def is_page(im: Image.Image) -> bool:
39
+ w, h = im.size
40
+ return max(w, h) / max(min(w, h), 1) <= PAGE_MAX_ASPECT and min(w, h) >= PAGE_MIN_SHORT_SIDE
41
+
42
+
43
+ def _scale_to(im: Image.Image, pixels: int) -> Image.Image:
44
+ k = (pixels / (im.width * im.height)) ** 0.5
45
+ return im.resize((max(32, int(im.width * k)), max(32, int(im.height * k))), Image.LANCZOS)
46
+
47
+
48
+ def prepare(im: Image.Image, enlarge_pages: bool = True) -> Image.Image:
49
+ """The release input policy (see the module docstring)."""
50
+ area = im.width * im.height
51
+ if enlarge_pages and is_page(im) and area < TRAIN_PIXELS:
52
+ return _scale_to(im, TRAIN_PIXELS)
53
+ if area > TRAIN_PIXELS:
54
+ return _scale_to(im, TRAIN_PIXELS)
55
+ return im
56
+
57
+
58
+ def plain(im: Image.Image) -> Image.Image:
59
+ """The fallback reading's input: native size, only capped."""
60
+ return _scale_to(im, TRAIN_PIXELS) if im.width * im.height > TRAIN_PIXELS else im
@@ -0,0 +1,64 @@
1
+ """Output clean-up and loop detection."""
2
+ from __future__ import annotations
3
+
4
+ import re
5
+
6
+ PROMPTS = {
7
+ "as-written": "Transcribe the Arabic text in this image exactly as written. Include only the diacritics (tashkeel) "
8
+ "that are visible in the image.",
9
+ "bare": "Transcribe the Arabic text in this image without any diacritics.",
10
+ "markdown": "Convert this document to Markdown: headings, paragraphs, lists and tables in reading order. Include "
11
+ "only the diacritics visible in the image.",
12
+ }
13
+ MODES = tuple(PROMPTS)
14
+
15
+ _THINK = re.compile(r"<think>.*?</think>", re.S)
16
+ _FENCE = re.compile(r"^```\w*\n?|\n?```$")
17
+ _CHAR_RUN = re.compile(r"([^\s<])\1{199,}") # 200+ of one character: dotted / underlined form lines are shorter
18
+ _CYCLE = re.compile(r"(.{8,200}?)(?:\s*\1){2,}", re.S)
19
+ LOOP_CHARS = 200 # a reading that loses more than this to trim_loops counts as looped
20
+ END_REPEATS = 5 # a span repeated this often up to the very end of the output (cut off by the token limit) is a loop
21
+ RUNAWAY_REPEATS = 20 # a span repeated this often is a loop even mid-text; fewer repeats only count at the very end
22
+ LINE_REPEATS = 10 # a long line re-appearing this often is a loop (refrains and repeated table rows stay)
23
+
24
+
25
+ def clean(text: str) -> str:
26
+ text = _THINK.sub("", text or "")
27
+ return _FENCE.sub("", text.strip()).strip()
28
+
29
+
30
+ def trim_loops(text: str) -> str:
31
+ """Remove runaway repetition only. Genuine repeats stay: identical table rows, dotted form lines, refrains and MRZ
32
+ filler («<<<<»). A runaway is a span repeated back to back that either runs on to the end of the output (where
33
+ generation was cut off) END_REPEATS+ times or repeats RUNAWAY_REPEATS+ times anywhere; it keeps one copy. A run of 200+ identical characters
34
+ keeps one, and a long line (>= 40 chars) that appears LINE_REPEATS+ times is kept only at its first occurrence."""
35
+ text = _CHAR_RUN.sub(r"\1", text)
36
+
37
+ def cut(m):
38
+ unit = m.group(1)
39
+ if not unit.replace("<", "").strip(): # MRZ filler
40
+ return m.group(0)
41
+ reps = len(m.group(0)) / max(len(unit), 1)
42
+ at_end = m.end() >= len(m.string.rstrip()) - 1
43
+ return unit if ((at_end and reps >= END_REPEATS) or reps >= RUNAWAY_REPEATS) else m.group(0)
44
+
45
+ prev = None
46
+ while prev != text:
47
+ prev = text
48
+ text = _CYCLE.sub(cut, text)
49
+ lines = text.split("\n")
50
+ keys = [re.sub(r"\s+", " ", line).strip() for line in lines]
51
+ count = {}
52
+ for k in keys:
53
+ count[k] = count.get(k, 0) + 1
54
+ seen, out = set(), []
55
+ for line, k in zip(lines, keys):
56
+ if len(k) >= 40 and count[k] >= LINE_REPEATS and k in seen:
57
+ continue
58
+ seen.add(k)
59
+ out.append(line)
60
+ return "\n".join(out)
61
+
62
+
63
+ def looped(text: str) -> bool:
64
+ return len(text) - len(trim_loops(text)) > LOOP_CHARS
@@ -0,0 +1,49 @@
1
+ from PIL import Image
2
+
3
+ from nuqta import is_page, looped, prepare, read_fields, trim_loops
4
+ from nuqta.preprocess import TRAIN_PIXELS, plain
5
+ from nuqta.text import clean
6
+
7
+
8
+ def test_page_rule_enlarges_small_pages_only():
9
+ page = Image.new("RGB", (612, 792), "white") # a 72-dpi PDF page render
10
+ big = prepare(page)
11
+ assert is_page(page) and abs(big.width * big.height - TRAIN_PIXELS) / TRAIN_PIXELS < 0.01
12
+ line = Image.new("RGB", (1200, 80), "white") # a text line crop: never enlarged
13
+ assert not is_page(line) and prepare(line).size == line.size
14
+ word = Image.new("RGB", (300, 120), "white")
15
+ assert prepare(word).size == word.size
16
+
17
+
18
+ def test_cap_at_training_size():
19
+ huge = Image.new("RGB", (4000, 3000), "white")
20
+ for im in (prepare(huge), plain(huge)):
21
+ assert im.width * im.height <= TRAIN_PIXELS * 1.01
22
+
23
+
24
+ def test_loops():
25
+ page = "السطر الأول من الصفحة\n" + "١ | ١ | " * 200
26
+ assert looped(page) and len(trim_loops(page)) < 100
27
+ assert not looped("نص عادي بلا تكرار " * 3)
28
+ assert trim_loops("P<UTO<<<<<<<<<<<<<<<<<<<<<<") == "P<UTO<<<<<<<<<<<<<<<<<<<<<<" # MRZ filler is kept
29
+
30
+
31
+ def test_clean():
32
+ assert clean("<think>x</think>```markdown\n# عنوان\n```") == "# عنوان"
33
+
34
+
35
+ def test_mrz_icao_specimen():
36
+ text = "PASSPORT\nP<UTOERIKSSON<<ANNA<MARIA<<<<<<<<<<<<<<<<<<<\nL898902C36UTO7408122F1204159ZE184226B<<<<<10"
37
+ m = read_fields(text)["mrz"]
38
+ assert m["valid"] and m["number"] == "L898902C3" and m["surname"] == "ERIKSSON"
39
+
40
+
41
+ def test_trim_loops_keeps_real_repeats_and_cuts_runaways():
42
+ from nuqta.text import looped, trim_loops
43
+ row = "<tr><td>قلم</td><td>1</td><td>5</td></tr>"
44
+ for keep in ("<table>" + row * 9 + "</table>\nالمجموع 45", # identical table rows
45
+ "الاسم: ...................................... التاريخ: ____________________", # form lines
46
+ "\n".join(["يا ليلُ الصبُّ متى غدُه أقيامُ الساعةِ موعدُهُ"] * 4)): # refrain
47
+ assert trim_loops(keep) == keep and not looped(keep)
48
+ runaway = "مقدمة النص. " + "وهذا مثال متكرر " * 60
49
+ assert looped(runaway) and len(trim_loops(runaway)) < 60