medhaocr 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.
medhaocr-0.1.0/LICENSE ADDED
@@ -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,87 @@
1
+ Metadata-Version: 2.4
2
+ Name: medhaocr
3
+ Version: 0.1.0
4
+ Summary: CPU-only OCR for scanned and digital documents (PDF, JPG, JPEG, PNG) that keeps headings, tables and layout
5
+ Author: Maruti L Sankannanavar
6
+ License-Expression: Apache-2.0
7
+ Keywords: ocr,pdf,scanned documents,layout,tables,cpu
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: Operating System :: OS Independent
10
+ Classifier: Topic :: Scientific/Engineering :: Image Recognition
11
+ Classifier: Topic :: Text Processing
12
+ Requires-Python: >=3.10
13
+ Description-Content-Type: text/markdown
14
+ License-File: LICENSE
15
+ Requires-Dist: rapidocr>=3.9
16
+ Requires-Dist: rapid-layout>=1.2
17
+ Requires-Dist: rapid-table>=3.0
18
+ Requires-Dist: onnxruntime>=1.20
19
+ Requires-Dist: openvino>=2025.0
20
+ Requires-Dist: opencv-python-headless>=4.10
21
+ Requires-Dist: numpy>=1.26
22
+ Requires-Dist: pypdfium2>=4.30
23
+ Dynamic: license-file
24
+
25
+ # medhaocr
26
+
27
+ OCR for scanned and digital documents that runs on a normal CPU - no GPU, no cloud. Give it a
28
+ **PDF, JPG, JPEG or PNG** (the type is detected automatically) and it prints the text of every page, keeping
29
+ headings, side-by-side fields and tables in place.
30
+
31
+ ## Install
32
+
33
+ Python 3.10 or newer, then:
34
+
35
+ ```
36
+ pip install medhaocr
37
+ ```
38
+
39
+ The first run downloads the OCR models once (~250 MB, needs internet); after that it works offline.
40
+
41
+ ## Use from the command line
42
+
43
+ ```
44
+ medhaocr scan.pdf
45
+ medhaocr photo.jpg
46
+ medhaocr scan.pdf > scan.txt # save the text to a file
47
+ ```
48
+
49
+ Output - the file name and page number, then that page's text:
50
+
51
+ ```
52
+ scan.pdf - Page 1
53
+ # INVOICE
54
+ Invoice No : 1234 Date : 01/01/2025
55
+ | Item | Qty | Amount |
56
+ |----------|-----|--------|
57
+ | Paper A4 | 2 | 500.00 |
58
+
59
+ scan.pdf - Page 2
60
+ ...
61
+ ```
62
+
63
+ ## Use from Python
64
+
65
+ ```python
66
+ from medhaocr import extract, extract_text
67
+
68
+ for page in extract("scan.pdf"): # one result per page
69
+ print(page["file"], page["page"], page["seconds"])
70
+ print(page["text"])
71
+
72
+ text = extract_text("photo.jpg") # all pages as one string
73
+ ```
74
+
75
+ ## What it does
76
+
77
+ Per page: crop scanner borders, straighten tilted scans, remove punch holes -> detect and read every text line
78
+ (PP-OCRv6; a fast model reads every line, a stronger one re-reads uncertain lines) -> find headings, text blocks,
79
+ tables and logos (PP-DocLayout v2) -> rebuild table rows and columns (SLANet+) -> print in reading order.
80
+ Typically 4-9 seconds per page on a laptop CPU.
81
+
82
+ Best on digital and scanned printed documents. Handwriting is not supported. Always check important values
83
+ (numbers, dates, IDs) against the original.
84
+
85
+ ## License
86
+
87
+ Apache-2.0
@@ -0,0 +1,63 @@
1
+ # medhaocr
2
+
3
+ OCR for scanned and digital documents that runs on a normal CPU - no GPU, no cloud. Give it a
4
+ **PDF, JPG, JPEG or PNG** (the type is detected automatically) and it prints the text of every page, keeping
5
+ headings, side-by-side fields and tables in place.
6
+
7
+ ## Install
8
+
9
+ Python 3.10 or newer, then:
10
+
11
+ ```
12
+ pip install medhaocr
13
+ ```
14
+
15
+ The first run downloads the OCR models once (~250 MB, needs internet); after that it works offline.
16
+
17
+ ## Use from the command line
18
+
19
+ ```
20
+ medhaocr scan.pdf
21
+ medhaocr photo.jpg
22
+ medhaocr scan.pdf > scan.txt # save the text to a file
23
+ ```
24
+
25
+ Output - the file name and page number, then that page's text:
26
+
27
+ ```
28
+ scan.pdf - Page 1
29
+ # INVOICE
30
+ Invoice No : 1234 Date : 01/01/2025
31
+ | Item | Qty | Amount |
32
+ |----------|-----|--------|
33
+ | Paper A4 | 2 | 500.00 |
34
+
35
+ scan.pdf - Page 2
36
+ ...
37
+ ```
38
+
39
+ ## Use from Python
40
+
41
+ ```python
42
+ from medhaocr import extract, extract_text
43
+
44
+ for page in extract("scan.pdf"): # one result per page
45
+ print(page["file"], page["page"], page["seconds"])
46
+ print(page["text"])
47
+
48
+ text = extract_text("photo.jpg") # all pages as one string
49
+ ```
50
+
51
+ ## What it does
52
+
53
+ Per page: crop scanner borders, straighten tilted scans, remove punch holes -> detect and read every text line
54
+ (PP-OCRv6; a fast model reads every line, a stronger one re-reads uncertain lines) -> find headings, text blocks,
55
+ tables and logos (PP-DocLayout v2) -> rebuild table rows and columns (SLANet+) -> print in reading order.
56
+ Typically 4-9 seconds per page on a laptop CPU.
57
+
58
+ Best on digital and scanned printed documents. Handwriting is not supported. Always check important values
59
+ (numbers, dates, IDs) against the original.
60
+
61
+ ## License
62
+
63
+ Apache-2.0
@@ -0,0 +1,36 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "medhaocr"
7
+ version = "0.1.0"
8
+ description = "CPU-only OCR for scanned and digital documents (PDF, JPG, JPEG, PNG) that keeps headings, tables and layout"
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = "Apache-2.0"
12
+ license-files = ["LICENSE"]
13
+ authors = [{ name = "Maruti L Sankannanavar" }]
14
+ keywords = ["ocr", "pdf", "scanned documents", "layout", "tables", "cpu"]
15
+ classifiers = [
16
+ "Programming Language :: Python :: 3",
17
+ "Operating System :: OS Independent",
18
+ "Topic :: Scientific/Engineering :: Image Recognition",
19
+ "Topic :: Text Processing",
20
+ ]
21
+ dependencies = [
22
+ "rapidocr>=3.9",
23
+ "rapid-layout>=1.2",
24
+ "rapid-table>=3.0",
25
+ "onnxruntime>=1.20",
26
+ "openvino>=2025.0",
27
+ "opencv-python-headless>=4.10",
28
+ "numpy>=1.26",
29
+ "pypdfium2>=4.30",
30
+ ]
31
+
32
+ [project.scripts]
33
+ medhaocr = "medhaocr.__main__:main"
34
+
35
+ [tool.setuptools.packages.find]
36
+ where = ["src"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,66 @@
1
+ """
2
+ Medha OCR - CPU-only OCR for scanned documents that keeps the page structure.
3
+
4
+ from medhaocr import extract
5
+ for page in extract("report.pdf"): # pdf, jpg, jpeg or png - detected automatically
6
+ print(page["file"], page["page"])
7
+ print(page["text"])
8
+ """
9
+ import logging
10
+ import os
11
+
12
+ os.environ.setdefault("TQDM_DISABLE", "1") # no progress bars from the table model
13
+
14
+ from .core import MedhaOCR, load_pages, render_text # noqa: E402
15
+
16
+
17
+ def _quiet_model_logs():
18
+ """The OCR / layout / table packages log INFO lines while loading models; keep only warnings."""
19
+ for name in list(logging.root.manager.loggerDict):
20
+ if name.lower().startswith(("rapidocr", "rapid_layout", "rapid_table", "rapidtable")):
21
+ logging.getLogger(name).setLevel(logging.WARNING)
22
+ for name in ("RapidOCR", "RapidTable", "rapid_layout", "rapid_table"):
23
+ logging.getLogger(name).setLevel(logging.WARNING)
24
+
25
+ __version__ = "0.1.0"
26
+ __all__ = ["extract", "extract_text", "MedhaOCR", "SUPPORTED"]
27
+
28
+ SUPPORTED = (".pdf", ".jpg", ".jpeg", ".png")
29
+ _engine = None
30
+
31
+
32
+ def _get_engine():
33
+ global _engine
34
+ if _engine is None: # models load once per process (first call takes a few seconds)
35
+ previous = logging.root.manager.disable
36
+ logging.disable(logging.INFO) # silence INFO lines printed while the models load
37
+ try:
38
+ _engine = MedhaOCR()
39
+ finally:
40
+ logging.disable(previous) # restore the caller's logging settings
41
+ _quiet_model_logs() # loggers created while loading models
42
+ return _engine
43
+
44
+
45
+ def extract(path):
46
+ """OCR a PDF / JPG / JPEG / PNG file.
47
+
48
+ Yields one dict per page, in order:
49
+ {"file": "<file name>", "page": <page number, 1-based>, "text": "<extracted text>", "seconds": <float>}
50
+ """
51
+ path = os.fspath(path)
52
+ if not os.path.isfile(path):
53
+ raise FileNotFoundError(f"file not found: {path}")
54
+ ext = os.path.splitext(path)[1].lower()
55
+ if ext not in SUPPORTED:
56
+ raise ValueError(f"unsupported file type '{ext}' - supported: {', '.join(SUPPORTED)}")
57
+ engine = _get_engine()
58
+ name = os.path.basename(path)
59
+ for n, img in enumerate(load_pages(path), 1):
60
+ res = engine.read_page(img)
61
+ yield {"file": name, "page": n, "text": render_text(res), "seconds": round(res["seconds"], 2)}
62
+
63
+
64
+ def extract_text(path):
65
+ """OCR a file and return all pages as one string: '<file> - Page N' header followed by the page text."""
66
+ return "\n\n".join(f"{p['file']} - Page {p['page']}\n{p['text']}" for p in extract(path))
@@ -0,0 +1,39 @@
1
+ """Command line: medhaocr <file.pdf|.jpg|.jpeg|.png> (or: python -m medhaocr <file>)
2
+
3
+ Prints, for every page:
4
+ <file name> - Page <n>
5
+ <extracted text>
6
+ """
7
+ import logging
8
+ import sys
9
+ import warnings
10
+
11
+
12
+ def main(argv=None):
13
+ argv = sys.argv[1:] if argv is None else argv
14
+ if argv and argv[0] in ("-V", "--version"):
15
+ from . import __version__
16
+ print(f"medhaocr {__version__}")
17
+ return 0
18
+ if len(argv) != 1 or argv[0] in ("-h", "--help"):
19
+ print("usage: medhaocr <file.pdf | file.jpg | file.jpeg | file.png>", file=sys.stderr)
20
+ return 2
21
+ warnings.filterwarnings("ignore")
22
+ logging.disable(logging.WARNING) # keep stdout to the extracted text only
23
+ if hasattr(sys.stdout, "reconfigure"):
24
+ sys.stdout.reconfigure(encoding="utf-8") # Windows consoles: print any character safely
25
+ from . import extract
26
+ try:
27
+ for i, page in enumerate(extract(argv[0])):
28
+ if i:
29
+ print()
30
+ print(f"{page['file']} - Page {page['page']}")
31
+ print(page["text"], flush=True)
32
+ except (FileNotFoundError, ValueError) as e:
33
+ print(f"medhaocr: {e}", file=sys.stderr)
34
+ return 1
35
+ return 0
36
+
37
+
38
+ if __name__ == "__main__":
39
+ sys.exit(main())
@@ -0,0 +1,593 @@
1
+ """Medha OCR engine: preprocessing, OCR, layout analysis, table structure and rendering (CPU only)."""
2
+ import html
3
+ import os
4
+ import re
5
+ import sys
6
+ import time
7
+
8
+ import cv2
9
+ import numpy as np
10
+ from rapidocr import EngineType, ModelType, OCRVersion, RapidOCR
11
+ from rapidocr.utils.process_img import get_rotate_crop_image
12
+
13
+
14
+ PDF_DPI = 200 # PDF pages are rendered at this resolution
15
+ TARGET_SIDE = 1600 # longest image side used for OCR
16
+ OCR_BUDGET_S = 6.0 # per-page OCR time after which re-reads stop (layout + tables need ~2-3 s more)
17
+ RECHECK_BELOW = 0.97 # lines read with lower confidence are re-read by the stronger model
18
+ MIN_RECHECK = 0.60 # below this it is handwriting/scribble; re-reading does not help
19
+ TEXT_COLS = 120 # width of the layout-text view in characters
20
+
21
+ # a letter O/I/l inside a number or before a unit is a digit: 5OMG -> 50MG
22
+ UNITS = r"(?:mg|mcg|ml|g|kg|cm|mm|mmhg|bpm|iu|u|%|hrs?|min|days?|m2)"
23
+ MIXED_DIGIT = re.compile(r"(?<=\d)[OoIl](?=\d)|(?<=\d)[Oo](?=\s?" + UNITS + r"\b)|(?<=\d\.)[OoIl]|(?<=\b)[Oo](?=\.\d)",
24
+ re.IGNORECASE)
25
+
26
+ # layout-model classes -> our block kinds (anything not listed is plain text)
27
+ LAYOUT_KIND = {"doc_title": "heading", "header": "heading", "paragraph_title": "title",
28
+ "header_image": "logo", "image": "image", "chart": "image", "seal": "seal",
29
+ "table": "table", "footer": "footer", "footnote": "footer", "footer_image": "footer"}
30
+
31
+
32
+ # ----------------------------------------------------------------------------- input
33
+ def load_pages(path):
34
+ """Yield BGR page images: every page of a PDF, or the single image."""
35
+ ext = os.path.splitext(path)[1].lower()
36
+ if ext == ".pdf":
37
+ import pypdfium2 as pdfium
38
+ pdf = pdfium.PdfDocument(path)
39
+ try:
40
+ for i in range(len(pdf)):
41
+ bitmap = pdf[i].render(scale=PDF_DPI / 72)
42
+ img = bitmap.to_numpy() # BGR(A) for pdfium's default bitmap format
43
+ if bitmap.mode in ("RGB", "RGBA", "RGBX"):
44
+ img = img[..., [2, 1, 0]]
45
+ elif img.ndim == 3 and img.shape[2] == 4:
46
+ img = img[..., :3]
47
+ elif img.ndim == 2:
48
+ img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
49
+ yield np.ascontiguousarray(img[..., :3])
50
+ finally:
51
+ pdf.close()
52
+ elif ext in (".jpg", ".jpeg", ".png"):
53
+ img = cv2.imdecode(np.fromfile(path, dtype=np.uint8), cv2.IMREAD_COLOR)
54
+ if img is None:
55
+ raise ValueError(f"cannot read image: {path}")
56
+ yield img
57
+ else:
58
+ raise ValueError(f"unsupported file type '{ext}' (use pdf, jpg, jpeg or png)")
59
+
60
+
61
+ # ----------------------------------------------------------------------------- preprocessing
62
+ def crop_border(img, pad=6):
63
+ """Remove the black scanner frame."""
64
+ gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
65
+ _, mask = cv2.threshold(gray, 80, 255, cv2.THRESH_BINARY)
66
+ mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, np.ones((15, 15), np.uint8))
67
+ pts = cv2.findNonZero(mask)
68
+ if pts is None:
69
+ return img
70
+ x, y, w, h = cv2.boundingRect(pts)
71
+ return img[y + pad:y + h - pad, x + pad:x + w - pad]
72
+
73
+
74
+ def resize_to(img, side):
75
+ h, w = img.shape[:2]
76
+ s = side / max(h, w)
77
+ return img if s >= 1 else cv2.resize(img, (int(w * s), int(h * s)), interpolation=cv2.INTER_AREA)
78
+
79
+
80
+ def deskew(img, max_deg=3.0, step=0.1):
81
+ """Straighten a tilted scan: pick the angle giving the sharpest horizontal text-row profile."""
82
+ gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
83
+ small = cv2.resize(gray, None, fx=800 / gray.shape[1], fy=800 / gray.shape[1], interpolation=cv2.INTER_AREA)
84
+ bw = cv2.adaptiveThreshold(small, 1, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY_INV, 25, 15).astype(np.float32)
85
+ h, w = bw.shape
86
+ best, angle = -1.0, 0.0
87
+ for a in np.arange(-max_deg, max_deg + 1e-6, step):
88
+ rot = cv2.warpAffine(bw, cv2.getRotationMatrix2D((w / 2, h / 2), a, 1.0), (w, h), flags=cv2.INTER_NEAREST)
89
+ s = float(np.sum(np.diff(rot.sum(1)) ** 2))
90
+ if s > best:
91
+ best, angle = s, a
92
+ if abs(angle) < 0.05:
93
+ return img
94
+ H, W = img.shape[:2]
95
+ m = cv2.getRotationMatrix2D((W / 2, H / 2), angle, 1.0)
96
+ return cv2.warpAffine(img, m, (W, H), flags=cv2.INTER_CUBIC, borderValue=(255, 255, 255))
97
+
98
+
99
+ def remove_punch_holes(img):
100
+ """Paint out solid round blobs (binder punch holes) so they are not read as characters."""
101
+ gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
102
+ _, bw = cv2.threshold(gray, 70, 255, cv2.THRESH_BINARY_INV)
103
+ n, labels, stats, _ = cv2.connectedComponentsWithStats(bw, 8)
104
+ out, s = img.copy(), img.shape[1] / 1600
105
+ for i in range(1, n):
106
+ x, y, w, h, area = stats[i]
107
+ if 22 * s <= w <= 70 * s and 22 * s <= h <= 70 * s and 0.7 < w / h < 1.4 and area / (w * h) > 0.6:
108
+ out[labels == i] = 255
109
+ return out
110
+
111
+
112
+ def preprocess(img):
113
+ return remove_punch_holes(deskew(resize_to(crop_border(img), TARGET_SIDE)))
114
+
115
+
116
+ # ----------------------------------------------------------------------------- engines
117
+ def _ocr_engine(rec_model):
118
+ return RapidOCR(params={
119
+ "Global.use_cls": False, "Global.log_level": "critical", "Global.text_score": 0.0,
120
+ "Det.ocr_version": OCRVersion.PPOCRV6, "Det.model_type": ModelType.SMALL, "Det.engine_type": EngineType.OPENVINO,
121
+ "Rec.ocr_version": OCRVersion.PPOCRV6, "Rec.model_type": rec_model, "Rec.engine_type": EngineType.ONNXRUNTIME,
122
+ "Rec.rec_batch_num": 1, # no padding: each line's result is independent of other lines
123
+ })
124
+
125
+
126
+ def _bbox(line):
127
+ b = line["box"]
128
+ return float(b[:, 0].min()), float(b[:, 1].min()), float(b[:, 0].max()), float(b[:, 1].max())
129
+
130
+
131
+ class MedhaOCR:
132
+ def __init__(self):
133
+ from concurrent.futures import ThreadPoolExecutor
134
+ from rapid_layout import RapidLayout
135
+ from rapid_table import ModelType as TableModel, RapidTable, RapidTableInput
136
+ self.pool = ThreadPoolExecutor(1)
137
+ self.fast = _ocr_engine(ModelType.TINY) # detector + fast recogniser for every line
138
+ self.strong = _ocr_engine(ModelType.SMALL) # stronger recogniser for uncertain lines
139
+ self.layout = RapidLayout(model_type="pp_doc_layoutv2", conf_thresh=0.4)
140
+ self.table = RapidTable(RapidTableInput(model_type=TableModel.SLANETPLUS, use_ocr=False))
141
+ self.table.cfg.use_ocr = True # we pass our own OCR results; no second OCR engine is loaded
142
+
143
+ # ---- 1. text lines
144
+ def read_lines(self, img, t0):
145
+ det = self.fast(img, use_rec=False)
146
+ if det.boxes is None:
147
+ return []
148
+ boxes = [np.asarray(b, dtype=np.float32) for b in det.boxes]
149
+ crops = [get_rotate_crop_image(img, b.copy()) for b in boxes]
150
+ r = self.fast.recognize_txt(crops)
151
+ lines = [{"box": b, "text": t, "score": float(s)} for b, t, s in zip(boxes, r.txts, r.scores)]
152
+
153
+ # re-read uncertain printed lines with the stronger model (tall + unsure = handwriting: skipped)
154
+ hs = np.array([b[:, 1].max() - b[:, 1].min() for b in boxes])
155
+ sure = [i for i, ln in enumerate(lines) if ln["score"] > 0.97]
156
+ med_h = float(np.median(hs[sure] if sure else hs))
157
+ todo = [i for i, ln in enumerate(lines)
158
+ if MIN_RECHECK <= ln["score"] and not (hs[i] > 1.35 * med_h and ln["score"] < 0.93)
159
+ and (ln["score"] < RECHECK_BELOW or MIXED_DIGIT.search(ln["text"]) or re.search(r"\d{8,}", ln["text"]))]
160
+ # least confident first, short lines first (cheap, and short values like 'Class III' matter most)
161
+ for i in sorted(todo, key=lambda i: (round(lines[i]["score"], 2), len(lines[i]["text"]))):
162
+ if time.perf_counter() - t0 > OCR_BUDGET_S:
163
+ break
164
+ r2 = self.strong.recognize_txt([crops[i]])
165
+ t, s = r2.txts[0], float(r2.scores[0])
166
+ old = lines[i]["text"]
167
+ same = t.replace(" ", "") == old.replace(" ", "")
168
+ if t.strip() and ((same and t.count(" ") > old.count(" ")) or (not same and s > lines[i]["score"])):
169
+ lines[i].update(text=t, score=s)
170
+
171
+ lines = drop_junk([ln for ln in lines if ln["text"].strip()])
172
+ for ln in lines:
173
+ ln["text"] = clean(ln["text"])
174
+ return lines
175
+
176
+ # ---- 2. layout regions
177
+ def read_regions(self, img):
178
+ r = self.layout(img)
179
+ if r.boxes is None:
180
+ return []
181
+ return [{"kind": LAYOUT_KIND.get(c, "text"), "box": [float(v) for v in b], "lines": []}
182
+ for b, c in zip(r.boxes, r.class_names)]
183
+
184
+ # ---- 3. table structure
185
+ def read_table(self, img, region):
186
+ x0, y0, x1, y1 = (int(round(v)) for v in region["box"])
187
+ x0, y0 = max(0, x0), max(0, y0)
188
+ crop = img[y0:y1, x0:x1]
189
+ lines = region["lines"]
190
+ if crop.size == 0 or not lines:
191
+ return None
192
+ boxes = np.array([ln["box"] - np.array([x0, y0], dtype=np.float32) for ln in lines])
193
+ out = self.table([crop], ocr_results=[(boxes, tuple(ln["text"] for ln in lines),
194
+ tuple(ln["score"] for ln in lines))])
195
+ if not out.cell_bboxes or len(out.cell_bboxes[0]) == 0:
196
+ return None
197
+ return fill_table(out.cell_bboxes[0], out.logic_points[0], boxes, [ln["text"] for ln in lines])
198
+
199
+ # ---- whole page
200
+ def read_page(self, img):
201
+ t0 = time.perf_counter()
202
+ img = preprocess(img)
203
+ layout_job = self.pool.submit(self.read_regions, img) # layout model runs in parallel with OCR
204
+ lines = self.read_lines(img, t0)
205
+ annotate_style(img, lines)
206
+ rules = detect_rules(img)
207
+ regions = layout_job.result()
208
+ pictures = [] # logos, photos, barcodes, stamps: kept as images
209
+ for rg in regions:
210
+ if rg["kind"] in ("logo", "image", "seal"):
211
+ x0, y0, x1, y1 = (int(round(v)) for v in rg["box"])
212
+ snip = img[max(0, y0):y1, max(0, x0):x1]
213
+ if snip.size:
214
+ pictures.append({"box": (x0, y0, x1, y1), "snip": snip.copy(), "kind": rg["kind"]})
215
+ blocks = build_blocks(lines, regions)
216
+ for ln in lines: # headings/titles found by the layout model are bold
217
+ if ln.get("kind") in ("heading", "title"):
218
+ ln["bold"] = True
219
+ for blk in blocks:
220
+ if blk["type"] == "table":
221
+ blk["grid"] = self.read_table(img, blk["region"])
222
+ if blk["grid"] is None: # not a real grid (e.g. a boxed form): keep positional layout
223
+ blk.update(type="rows", rows=group_rows(blk["region"]["lines"]))
224
+ H, W = img.shape[:2]
225
+ return {"blocks": blocks, "lines": lines, "rules": rules, "pictures": pictures, "width": W, "height": H,
226
+ "seconds": time.perf_counter() - t0}
227
+
228
+
229
+ # ----------------------------------------------------------------------------- text clean-up
230
+ def clean(text):
231
+ text = MIXED_DIGIT.sub(lambda m: "0" if m.group(0) in "Oo" else "1", text) # 5OMG -> 50MG
232
+ text = re.sub("^[O0o\u25cb]\\s+(?=[A-Z(<])", "", text) # leading checkbox circle
233
+ text = re.sub("(?<=\\s)[O0\u25cb]\\s+(?=[A-Z][a-z])", "", text) # checkbox circle mid-line
234
+ text = re.sub(r"(?<![A-Za-z])[Oo](?=[A-Z][a-z]{2,})", "", text) # 'OUpper' -> 'Upper'
235
+ return text
236
+
237
+
238
+ def drop_junk(lines):
239
+ """Remove signatures, logo fragments and specks (by size and confidence)."""
240
+ if not lines:
241
+ return lines
242
+ heights = [ln["box"][:, 1].max() - ln["box"][:, 1].min() for ln in lines]
243
+ med_h = float(np.median(heights))
244
+ keep = []
245
+ for ln, h in zip(lines, heights):
246
+ t, s = ln["text"].strip(), ln["score"]
247
+ scribble = h > 2.5 * med_h and len(t) <= 12 and s < 0.9
248
+ fragment = ((len(t) <= 4 and s < 0.7) or (len(t) <= 2 and s < 0.85)) and not t.isdigit()
249
+ if not (scribble or fragment):
250
+ keep.append(ln)
251
+ return keep
252
+
253
+
254
+ # ----------------------------------------------------------------------------- visual style
255
+ def _crop_box(img, box, pad=0):
256
+ H, W = img.shape[:2]
257
+ x0, y0 = max(0, int(box[:, 0].min()) - pad), max(0, int(box[:, 1].min()) - pad)
258
+ x1, y1 = min(W, int(box[:, 0].max()) + pad), min(H, int(box[:, 1].max()) + pad)
259
+ return img[y0:y1, x0:x1]
260
+
261
+
262
+ def annotate_style(img, lines):
263
+ """Per line: size (px), ink colour, bold flag, handwriting flag (+ image snippet of handwriting)."""
264
+ if not lines:
265
+ return
266
+ for ln in lines:
267
+ crop = _crop_box(img, ln["box"])
268
+ h = ln["box"][:, 1].max() - ln["box"][:, 1].min()
269
+ ln["size"] = float(h)
270
+ ln["stroke"], ln["color"] = 0.0, "#111111"
271
+ if crop.size == 0:
272
+ continue
273
+ g = cv2.cvtColor(crop, cv2.COLOR_BGR2GRAY)
274
+ _, bw = cv2.threshold(g, 0, 255, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)
275
+ ink = bw > 0
276
+ if ink.sum() < 10:
277
+ continue
278
+ cs, _ = cv2.findContours(bw, cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE)
279
+ perimeter = sum(cv2.arcLength(c, True) for c in cs)
280
+ ln["stroke"] = 2 * ink.sum() / max(perimeter, 1.0) / max(h, 1.0) # stroke width relative to height
281
+ b, gch, r = (np.median(crop[..., k][ink]) for k in range(3))
282
+ dark = min(1.0, 90 / max(1.0, (r + gch + b) / 3)) # print ink is darker than scanned grey
283
+ ln["color"] = "#%02x%02x%02x" % tuple(int(v * dark) for v in (r, gch, b))
284
+ heights = np.array([ln["size"] for ln in lines])
285
+ strokes = np.array([ln["stroke"] for ln in lines])
286
+ med_h = float(np.median(heights))
287
+ for ln in lines:
288
+ peers = strokes[(heights > 0.8 * ln["size"]) & (heights < 1.25 * ln["size"]) & (strokes > 0)]
289
+ ref = np.median(peers) if len(peers) >= 5 else np.median(strokes[strokes > 0])
290
+ ln["bold"] = bool(ln["stroke"] > 1.3 * ref)
291
+ ln["hand"] = bool((ln["score"] < 0.85 and ln["size"] > 1.3 * med_h) or ln["score"] < 0.75)
292
+ if ln["hand"]:
293
+ ln["snip"] = _crop_box(img, ln["box"], pad=2).copy()
294
+
295
+
296
+ def detect_rules(img):
297
+ """Printed form lines / table borders as segments (x0, y0, x1, y1, thickness)."""
298
+ gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
299
+ bw = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY_INV, 25, 12)
300
+ H, W = gray.shape
301
+ segs = []
302
+ for kernel, horizontal in (((max(40, W // 25), 1), True), ((1, max(40, H // 35)), False)):
303
+ m = cv2.morphologyEx(bw, cv2.MORPH_OPEN, cv2.getStructuringElement(cv2.MORPH_RECT, kernel))
304
+ cs, _ = cv2.findContours(m, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
305
+ for c in cs:
306
+ x, y, w, h = cv2.boundingRect(c)
307
+ if horizontal and w >= kernel[0] and h <= 8:
308
+ segs.append((x, y + h / 2, x + w, y + h / 2, max(1, h)))
309
+ elif not horizontal and h >= kernel[1] and w <= 8:
310
+ segs.append((x + w / 2, y, x + w / 2, y + h, max(1, w)))
311
+ return segs
312
+
313
+
314
+ # ----------------------------------------------------------------------------- structure
315
+ def build_blocks(lines, regions):
316
+ """Assign text lines to layout regions, then cut the page into horizontal bands (reading order).
317
+ Returns blocks: {"type": "table", "region"} or {"type": "rows", "rows": [[item, ...], ...]}."""
318
+ # each line goes to the region covering most of it (tables win ties, then the smaller region)
319
+ orphans = []
320
+ for ln in lines:
321
+ x0, y0, x1, y1 = _bbox(ln)
322
+ area = max(1.0, (x1 - x0) * (y1 - y0))
323
+ best = None
324
+ for rg in regions:
325
+ rx0, ry0, rx1, ry1 = rg["box"]
326
+ ov = max(0.0, min(x1, rx1) - max(x0, rx0)) * max(0.0, min(y1, ry1) - max(y0, ry0)) / area
327
+ key = (ov >= 0.5, rg["kind"] == "table", -(rx1 - rx0) * (ry1 - ry0))
328
+ if ov >= 0.5 and (best is None or key > best[0]):
329
+ best = (key, rg)
330
+ if best:
331
+ best[1]["lines"].append(ln)
332
+ else:
333
+ orphans.append(ln)
334
+ regions = regions + [{"kind": "text", "box": list(_bbox(ln)), "lines": [ln]} for ln in orphans]
335
+
336
+ # every line carries the kind of its region; logos/images become one "[logo: ...]" item
337
+ usable = []
338
+ for rg in regions:
339
+ if rg["kind"] in ("logo", "image", "seal"):
340
+ words = " ".join(i["text"] for row in group_rows(rg["lines"]) for i in row)
341
+ x0, y0, x1, y1 = rg["box"]
342
+ box = np.array([[x0, y0], [x1, y0], [x1, y1], [x0, y1]], dtype=np.float32)
343
+ label = f"[{rg['kind']}: {words}]" if words else f"[{rg['kind']}]"
344
+ rg["lines"] = [{"box": box, "text": label, "score": 1.0}]
345
+ if not rg["lines"]:
346
+ continue
347
+ for ln in rg["lines"]:
348
+ ln["kind"] = rg["kind"] if rg["kind"] != "table" else "text"
349
+ usable.append(rg)
350
+
351
+ # horizontal bands: regions that sit side by side share a band; a table is always its own band
352
+ bands = []
353
+ for rg in sorted(usable, key=lambda r: r["box"][1]):
354
+ y0, y1 = rg["box"][1], rg["box"][3]
355
+ if bands and rg["kind"] != "table" and not bands[-1]["table"]:
356
+ b = bands[-1]
357
+ if min(y1, b["y1"]) - max(y0, b["y0"]) > 0.3 * min(y1 - y0, b["y1"] - b["y0"]):
358
+ b["regions"].append(rg)
359
+ b["y0"], b["y1"] = min(b["y0"], y0), max(b["y1"], y1)
360
+ continue
361
+ bands.append({"y0": y0, "y1": y1, "table": rg["kind"] == "table", "regions": [rg]})
362
+
363
+ blocks = []
364
+ for b in bands:
365
+ if b["table"]:
366
+ blocks.append({"type": "table", "region": b["regions"][0], "y0": b["y0"], "y1": b["y1"]})
367
+ else:
368
+ blocks.append({"type": "rows", "rows": group_rows([ln for rg in b["regions"] for ln in rg["lines"]]),
369
+ "y0": b["y0"], "y1": b["y1"]})
370
+ return blocks
371
+
372
+
373
+ def group_rows(lines):
374
+ """Group text boxes into rows (top to bottom), items in a row left to right."""
375
+ rows = []
376
+ for ln in sorted(lines, key=lambda ln: ln["box"][:, 1].mean()):
377
+ cy = ln["box"][:, 1].mean()
378
+ h = ln["box"][:, 1].max() - ln["box"][:, 1].min()
379
+ near = [(abs(cy - r["cy"]), r) for r in rows if abs(cy - r["cy"]) < 0.45 * min(h, r["h"])]
380
+ if near:
381
+ min(near, key=lambda n: n[0])[1]["items"].append(ln)
382
+ else:
383
+ rows.append({"cy": cy, "h": h, "items": [ln]})
384
+ rows.sort(key=lambda r: r["cy"])
385
+ return [sorted(r["items"], key=lambda i: i["box"][:, 0].min()) for r in rows]
386
+
387
+
388
+ def fill_table(cell_boxes, logic, line_boxes, texts):
389
+ """Put OCR lines into the table structure predicted by SLANet+.
390
+ The predicted cell boxes drift on long tables, so the row positions are first aligned to the text
391
+ (least-squares fit y_cell = a*y_text + b, refined 5 times), then each line goes to its row and to the
392
+ cell of that row under its x-centre. Returns a rectangular grid of strings, or None if the region is
393
+ not really a grid (a boxed form where cells hold whole paragraphs)."""
394
+ cells = []
395
+ for cb, (r0, r1, c0, c1) in zip(cell_boxes, logic):
396
+ xs, ys = cb[0::2], cb[1::2]
397
+ cells.append({"r0": int(r0), "r1": int(r1), "c0": int(c0), "c1": int(c1),
398
+ "x0": float(xs.min()), "x1": float(xs.max()), "y0": float(ys.min()), "y1": float(ys.max()),
399
+ "lines": []})
400
+ R = max(c["r1"] for c in cells) + 1
401
+ C = max(c["c1"] for c in cells) + 1
402
+ centers = np.full(R, np.nan)
403
+ for r in range(R):
404
+ ys = [(c["y0"] + c["y1"]) / 2 for c in cells if c["r0"] == c["r1"] == r]
405
+ if ys:
406
+ centers[r] = np.median(ys)
407
+ known = ~np.isnan(centers)
408
+ if known.sum() < 2:
409
+ return None
410
+ centers = np.interp(np.arange(R), np.flatnonzero(known), centers[known])
411
+
412
+ ly = np.array([(b[:, 1].min() + b[:, 1].max()) / 2 for b in line_boxes])
413
+ lx = np.array([(b[:, 0].min() + b[:, 0].max()) / 2 for b in line_boxes])
414
+ a, b = 1.0, 0.0
415
+ for _ in range(5): # align text rows to predicted rows
416
+ rows = np.abs((a * ly + b)[:, None] - centers[None, :]).argmin(1)
417
+ if len(set(rows)) < 2:
418
+ break
419
+ a, b = np.polyfit(ly, centers[rows], 1)
420
+ rows = np.abs((a * ly + b)[:, None] - centers[None, :]).argmin(1)
421
+
422
+ for i, r in enumerate(rows):
423
+ cand = [c for c in cells if c["r0"] <= r <= c["r1"]] or cells
424
+ inside = [c for c in cand if c["x0"] <= lx[i] <= c["x1"]]
425
+ cell = min(inside or cand, key=lambda c: (c["x1"] - c["x0"]) if inside else
426
+ min(abs(lx[i] - c["x0"]), abs(lx[i] - c["x1"])))
427
+ cell["lines"].append(i)
428
+
429
+ filled = [c for c in cells if c["lines"]]
430
+ if not filled or len(texts) / len(filled) > 2.5: # paragraphs in boxes, not a data grid
431
+ return None
432
+ grid = [[""] * C for _ in range(R)]
433
+ for c in filled:
434
+ order = sorted(c["lines"], key=lambda i: (round(ly[i] / 12), lx[i]))
435
+ grid[c["r0"]][c["c0"]] = " ".join(texts[i] for i in order)
436
+ return [row for row in grid if any(row)] or None # all predicted columns kept (blank cells stay blank)
437
+
438
+
439
+ # ----------------------------------------------------------------------------- rendering
440
+ def render_text(page):
441
+ """Layout text: headings as '#', rows aligned to their position on the page, tables as aligned grids."""
442
+ items = [i for blk in page["blocks"] if blk["type"] == "rows" for row in blk["rows"] for i in row]
443
+ xs = [i["box"][:, 0].min() for i in items]
444
+ left = min(xs) if xs else 0.0
445
+ scale = TEXT_COLS / max(1.0, page["width"] - left)
446
+ line_h = float(np.median([i["box"][:, 1].max() - i["box"][:, 1].min() for i in items] or [20]))
447
+ out, footer_seen, prev_y1 = [], False, None
448
+ for blk in page["blocks"]:
449
+ if prev_y1 is not None and (blk["type"] == "table" or blk["y0"] - prev_y1 > 0.9 * line_h):
450
+ out.append("") # blank line only where the page has a gap
451
+ prev_y1 = blk["y1"]
452
+ if blk["type"] == "table":
453
+ out.append(grid_to_text(blk["grid"]))
454
+ prev_y1 = -1e9 # always a blank line after a table
455
+ continue
456
+ for row in blk["rows"]:
457
+ kinds = {i.get("kind", "text") for i in row}
458
+ if kinds == {"footer"} and not footer_seen:
459
+ out.append("-" * TEXT_COLS)
460
+ footer_seen = True
461
+ line = ""
462
+ for i in row:
463
+ col = int((i["box"][:, 0].min() - left) * scale)
464
+ line += " " * (col - len(line)) if col > len(line) else (" " if line else "")
465
+ line += i["text"]
466
+ if kinds == {"heading"}:
467
+ line = "# " + line.strip()
468
+ elif kinds <= {"heading", "title"}:
469
+ line = "## " + line.strip()
470
+ out.append(line.rstrip())
471
+ return "\n".join(out).strip("\n")
472
+
473
+
474
+ def grid_to_text(grid):
475
+ widths = [max(len(r[c]) for r in grid) for c in range(len(grid[0]))]
476
+ fmt = lambda r: "| " + " | ".join(v.ljust(w) for v, w in zip(r, widths)) + " |"
477
+ lines = [fmt(grid[0]), "|" + "|".join("-" * (w + 2) for w in widths) + "|"]
478
+ return "\n".join(lines + [fmt(r) for r in grid[1:]])
479
+
480
+
481
+ HTML_HEAD = """<!doctype html><html><head><meta charset="utf-8"><title>Medha OCR - {title}</title><style>
482
+ body{{background:#e9ecef;font-family:Segoe UI,Arial,sans-serif;margin:0;padding:24px;color:#111}}
483
+ .page{{background:#fff;max-width:980px;margin:0 auto 28px;padding:36px 44px;box-shadow:0 1px 6px #0002}}
484
+ .pg{{color:#888;font-size:12px;margin-bottom:14px}}
485
+ .row{{position:relative;min-height:1.5em;line-height:1.5em;white-space:nowrap}}
486
+ .row span{{position:absolute;white-space:nowrap}}
487
+ .heading{{font-size:1.35em;font-weight:700;min-height:1.8em}} .title{{font-weight:700;margin-top:.5em}}
488
+ .footer{{color:#555;font-size:.85em}} hr{{border:0;border-top:1px solid #ccc;margin:14px 0}}
489
+ .logo,.image,.seal{{color:#1a5fb4;font-style:italic}}
490
+ .block{{margin-bottom:.6em}} table{{border-collapse:collapse;margin:8px 0 14px;font-size:.92em}}
491
+ td{{border:1px solid #999;padding:3px 8px;vertical-align:top}} tr:first-child td{{font-weight:700;background:#f3f5f8}}
492
+ </style></head><body>"""
493
+
494
+
495
+ def render_html(pages, title):
496
+ out = [HTML_HEAD.format(title=html.escape(title))]
497
+ for n, page in enumerate(pages, 1):
498
+ items = [i for blk in page["blocks"] if blk["type"] == "rows" for row in blk["rows"] for i in row]
499
+ left = min([i["box"][:, 0].min() for i in items] or [0.0])
500
+ span = max(1.0, page["width"] - left)
501
+ out.append(f'<section class="page"><div class="pg">Page {n}</div>')
502
+ footer_seen = False
503
+ for blk in page["blocks"]:
504
+ out.append('<div class="block">')
505
+ if blk["type"] == "table":
506
+ out.append("<table>")
507
+ for row in blk["grid"]:
508
+ out.append("<tr>" + "".join(f"<td>{html.escape(v)}</td>" for v in row) + "</tr>")
509
+ out.append("</table>")
510
+ else:
511
+ for row in blk["rows"]:
512
+ kinds = {i.get("kind", "text") for i in row}
513
+ cls = "heading" if kinds == {"heading"} else "title" if kinds <= {"heading", "title"} else \
514
+ "footer" if kinds == {"footer"} else ""
515
+ if cls == "footer" and not footer_seen:
516
+ out.append("<hr>")
517
+ footer_seen = True
518
+ spans = "".join(
519
+ f'<span class="{i.get("kind", "")}" style="left:{100 * (i["box"][:, 0].min() - left) / span:.1f}%">'
520
+ f'{html.escape(i["text"])}</span>' for i in row)
521
+ out.append(f'<div class="row {cls}">{spans}</div>')
522
+ out.append("</div>")
523
+ out.append("</section>")
524
+ out.append("</body></html>")
525
+ return "\n".join(out)
526
+
527
+
528
+ VIEW_W = 900 # page width (px) in the page view
529
+
530
+
531
+ def page_elements(page, view_w=VIEW_W):
532
+ """Everything needed to redraw a page at view_w pixels wide: rules, pictures, text items, handwriting."""
533
+ s = view_w / page["width"]
534
+ pics = [p for p in page["pictures"]]
535
+ in_pic = lambda ln: any(p["kind"] == "logo" and p["box"][0] <= ln["box"][:, 0].mean() <= p["box"][2]
536
+ and p["box"][1] <= ln["box"][:, 1].mean() <= p["box"][3] for p in pics)
537
+ snip = lambda im, w, h: cv2.resize(im, (max(1, int(w)), max(1, int(h))), interpolation=cv2.INTER_AREA)
538
+ el = {"w": view_w, "h": page["height"] * s, "rules": [], "images": [], "texts": []}
539
+ # one body-text size per page: detected box heights jitter, real documents use a few fixed sizes
540
+ printed = [ln["size"] for ln in page["lines"] if not ln.get("hand") and ln["score"] > 0.9]
541
+ body = float(np.median(printed)) if printed else 0.0
542
+ norm = lambda h: body if body and 0.8 * body <= h <= 1.3 * body else h
543
+ for x0, y0, x1, y1, t in page["rules"]:
544
+ el["rules"].append((x0 * s, y0 * s, x1 * s, y1 * s, max(1.0, t * s)))
545
+ for p in pics:
546
+ x0, y0, x1, y1 = p["box"]
547
+ el["images"].append({"x": x0 * s, "y": y0 * s, "img": snip(p["snip"], (x1 - x0) * s, (y1 - y0) * s),
548
+ "title": p["kind"]})
549
+ for ln in page["lines"]:
550
+ if in_pic(ln):
551
+ continue # text inside a logo is drawn by the logo image
552
+ x0, y0 = ln["box"][:, 0].min() * s, ln["box"][:, 1].min() * s
553
+ w, h = (ln["box"][:, 0].max() - ln["box"][:, 0].min()) * s, ln["size"] * s
554
+ if ln.get("hand") and ln.get("snip") is not None:
555
+ el["images"].append({"x": x0, "y": y0, "img": snip(ln["snip"], w + 4 * s, h + 4 * s),
556
+ "title": "handwriting (OCR: " + ln["text"] + ")"})
557
+ else:
558
+ el["texts"].append({"x": x0, "y": y0, "w": w, "px": max(6.0, norm(ln["size"]) * s * 0.8), "text": ln["text"],
559
+ "bold": ln.get("bold", False), "color": ln.get("color", "#111")})
560
+ return el
561
+
562
+
563
+ def _png_b64(img):
564
+ import base64
565
+ return base64.b64encode(cv2.imencode(".png", img)[1].tobytes()).decode()
566
+
567
+
568
+ def render_page_html(pages, title):
569
+ """Faithful page view: every line at its own position, size, weight and colour; form lines; pictures."""
570
+ out = [f"""<!doctype html><html><head><meta charset="utf-8"><title>Medha OCR - {html.escape(title)}</title><style>
571
+ body{{background:#e9ecef;margin:0;padding:24px;font-family:Arial,Helvetica,sans-serif}}
572
+ .pg{{color:#666;font-size:12px;margin:0 auto 4px;width:{VIEW_W}px}}
573
+ .pv{{position:relative;background:#fff;margin:0 auto 28px;box-shadow:0 1px 6px #0003;overflow:hidden}}
574
+ .pv svg{{position:absolute;left:0;top:0}} .pv img{{position:absolute}}
575
+ .t{{position:absolute;white-space:nowrap;line-height:1;transform-origin:0 0}}
576
+ </style></head><body>"""]
577
+ for n, page in enumerate(pages, 1):
578
+ el = page_elements(page)
579
+ out.append(f'<div class="pg">Page {n}</div><div class="pv" style="width:{el["w"]:.0f}px;height:{el["h"]:.0f}px">')
580
+ out.append(f'<svg width="{el["w"]:.0f}" height="{el["h"]:.0f}">' + "".join(
581
+ f'<line x1="{a:.1f}" y1="{b:.1f}" x2="{c:.1f}" y2="{d:.1f}" stroke="#444" stroke-width="{t:.1f}"/>'
582
+ for a, b, c, d, t in el["rules"]) + "</svg>")
583
+ for im in el["images"]:
584
+ out.append(f'<img src="data:image/png;base64,{_png_b64(im["img"])}" title="{html.escape(im["title"])}" '
585
+ f'style="left:{im["x"]:.1f}px;top:{im["y"]:.1f}px">')
586
+ for t in el["texts"]:
587
+ out.append(f'<span class="t" data-w="{t["w"]:.1f}" style="left:{t["x"]:.1f}px;top:{t["y"]:.1f}px;'
588
+ f'font-size:{t["px"]:.1f}px;font-weight:{700 if t["bold"] else 400};color:{t["color"]}">'
589
+ f'{html.escape(t["text"])}</span>')
590
+ out.append("</div>")
591
+ out.append("""<script>for(const e of document.querySelectorAll('.t')){const w=e.getBoundingClientRect().width;
592
+ if(w>0)e.style.transform='scaleX('+(parseFloat(e.dataset.w)/w)+')';}</script></body></html>""")
593
+ return "\n".join(out)
@@ -0,0 +1,87 @@
1
+ Metadata-Version: 2.4
2
+ Name: medhaocr
3
+ Version: 0.1.0
4
+ Summary: CPU-only OCR for scanned and digital documents (PDF, JPG, JPEG, PNG) that keeps headings, tables and layout
5
+ Author: Maruti L Sankannanavar
6
+ License-Expression: Apache-2.0
7
+ Keywords: ocr,pdf,scanned documents,layout,tables,cpu
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: Operating System :: OS Independent
10
+ Classifier: Topic :: Scientific/Engineering :: Image Recognition
11
+ Classifier: Topic :: Text Processing
12
+ Requires-Python: >=3.10
13
+ Description-Content-Type: text/markdown
14
+ License-File: LICENSE
15
+ Requires-Dist: rapidocr>=3.9
16
+ Requires-Dist: rapid-layout>=1.2
17
+ Requires-Dist: rapid-table>=3.0
18
+ Requires-Dist: onnxruntime>=1.20
19
+ Requires-Dist: openvino>=2025.0
20
+ Requires-Dist: opencv-python-headless>=4.10
21
+ Requires-Dist: numpy>=1.26
22
+ Requires-Dist: pypdfium2>=4.30
23
+ Dynamic: license-file
24
+
25
+ # medhaocr
26
+
27
+ OCR for scanned and digital documents that runs on a normal CPU - no GPU, no cloud. Give it a
28
+ **PDF, JPG, JPEG or PNG** (the type is detected automatically) and it prints the text of every page, keeping
29
+ headings, side-by-side fields and tables in place.
30
+
31
+ ## Install
32
+
33
+ Python 3.10 or newer, then:
34
+
35
+ ```
36
+ pip install medhaocr
37
+ ```
38
+
39
+ The first run downloads the OCR models once (~250 MB, needs internet); after that it works offline.
40
+
41
+ ## Use from the command line
42
+
43
+ ```
44
+ medhaocr scan.pdf
45
+ medhaocr photo.jpg
46
+ medhaocr scan.pdf > scan.txt # save the text to a file
47
+ ```
48
+
49
+ Output - the file name and page number, then that page's text:
50
+
51
+ ```
52
+ scan.pdf - Page 1
53
+ # INVOICE
54
+ Invoice No : 1234 Date : 01/01/2025
55
+ | Item | Qty | Amount |
56
+ |----------|-----|--------|
57
+ | Paper A4 | 2 | 500.00 |
58
+
59
+ scan.pdf - Page 2
60
+ ...
61
+ ```
62
+
63
+ ## Use from Python
64
+
65
+ ```python
66
+ from medhaocr import extract, extract_text
67
+
68
+ for page in extract("scan.pdf"): # one result per page
69
+ print(page["file"], page["page"], page["seconds"])
70
+ print(page["text"])
71
+
72
+ text = extract_text("photo.jpg") # all pages as one string
73
+ ```
74
+
75
+ ## What it does
76
+
77
+ Per page: crop scanner borders, straighten tilted scans, remove punch holes -> detect and read every text line
78
+ (PP-OCRv6; a fast model reads every line, a stronger one re-reads uncertain lines) -> find headings, text blocks,
79
+ tables and logos (PP-DocLayout v2) -> rebuild table rows and columns (SLANet+) -> print in reading order.
80
+ Typically 4-9 seconds per page on a laptop CPU.
81
+
82
+ Best on digital and scanned printed documents. Handwriting is not supported. Always check important values
83
+ (numbers, dates, IDs) against the original.
84
+
85
+ ## License
86
+
87
+ Apache-2.0
@@ -0,0 +1,12 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ src/medhaocr/__init__.py
5
+ src/medhaocr/__main__.py
6
+ src/medhaocr/core.py
7
+ src/medhaocr.egg-info/PKG-INFO
8
+ src/medhaocr.egg-info/SOURCES.txt
9
+ src/medhaocr.egg-info/dependency_links.txt
10
+ src/medhaocr.egg-info/entry_points.txt
11
+ src/medhaocr.egg-info/requires.txt
12
+ src/medhaocr.egg-info/top_level.txt
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ medhaocr = medhaocr.__main__:main
@@ -0,0 +1,8 @@
1
+ rapidocr>=3.9
2
+ rapid-layout>=1.2
3
+ rapid-table>=3.0
4
+ onnxruntime>=1.20
5
+ openvino>=2025.0
6
+ opencv-python-headless>=4.10
7
+ numpy>=1.26
8
+ pypdfium2>=4.30
@@ -0,0 +1 @@
1
+ medhaocr