v0.1.1: v0.1 + automatic upright correction (tilted, sideways, upside-down pages)
Browse files- README.md +3 -0
- SHA256SUMS +22 -0
- v0.1.1/README.md +147 -0
- v0.1.1/compact_lm.py +61 -0
- v0.1.1/decode.py +68 -0
- v0.1.1/digits.py +29 -0
- v0.1.1/lines.py +34 -0
- v0.1.1/models/det_fp32.onnx +3 -0
- v0.1.1/models/det_hw_fp32.onnx +3 -0
- v0.1.1/models/lm.npz +3 -0
- v0.1.1/models/meta.json +200 -0
- v0.1.1/models/rec_fp32.onnx +3 -0
- v0.1.1/models/rec_int8.onnx +3 -0
- v0.1.1/ocr.py +104 -0
- v0.1.1/pdf_route.py +65 -0
- v0.1.1/pdf_text.py +38 -0
- v0.1.1/reading_order.py +84 -0
- v0.1.1/requirements.txt +6 -0
- v0.1.1/third_party/indra_ocr/LICENSE +202 -0
- v0.1.1/third_party/indra_ocr/__init__.py +1 -0
- v0.1.1/third_party/indra_ocr/textlayer.py +253 -0
- v0.1.1/third_party/indra_ocr/vocab.py +289 -0
- v0.1.1/upright.py +64 -0
- v0.1.1/upright_checks.json +170 -0
README.md
CHANGED
|
@@ -25,6 +25,9 @@ Small CPU OCR for **printed and handwritten Nepali and English**, plus PDFs thro
|
|
| 25 |
|---|---|---|
|
| 26 |
| [`v0.1/`](v0.1) | Printed Nepali and English: scans, newspapers, PDFs | Released 12 Nov 2026 |
|
| 27 |
| [`v0.2/`](v0.2) | Handwriting, notebooks, phone photos (same print quality as v0.1) | Candidate, 13 Nov 2026 |
|
|
|
|
|
|
|
|
|
|
| 28 |
|
| 29 |
## Results on locked test sets
|
| 30 |
|
|
|
|
| 25 |
|---|---|---|
|
| 26 |
| [`v0.1/`](v0.1) | Printed Nepali and English: scans, newspapers, PDFs | Released 12 Nov 2026 |
|
| 27 |
| [`v0.2/`](v0.2) | Handwriting, notebooks, phone photos (same print quality as v0.1) | Candidate, 13 Nov 2026 |
|
| 28 |
+
| [`v0.1.1/`](v0.1.1) | v0.1 + automatic upright correction: tilted, sideways or upside-down pages and photos | Released 27 Nov 2026 |
|
| 29 |
+
|
| 30 |
+
**New in v0.1.1:** automatic upright correction. Turned pages now read as well as straight ones (Sarvam Nepali turned 7°: 51.72% → 6.62% CER; turned 90°: 79.79% → 6.17%; handwriting photos upside down: 95.93% → 51.38%), with no significant change on straight pages. Same models as v0.1. Details: [`v0.1.1/README.md`](v0.1.1/README.md). Download: `hf download ampixa/nepali-tiny-ocr --revision v0.1.1 --include "v0.1.1/*" --local-dir nepali-tiny-ocr`.
|
| 31 |
|
| 32 |
## Results on locked test sets
|
| 33 |
|
SHA256SUMS
CHANGED
|
@@ -38,3 +38,25 @@ c925041e1663d53df35bff4da5ad6bac41d51be15ebe68f78b44f22118e1f47a v0.2/third_par
|
|
| 38 |
cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30 v0.2/third_party/indra_ocr/LICENSE
|
| 39 |
34e7ab4cbe231f495f9df3abbd9880c22ceb1c0eff84d88648307d4666d63327 v0.2/third_party/indra_ocr/textlayer.py
|
| 40 |
7660d70fb6384094958578452ee86fed813377a63ee1a58c5203cad607219929 v0.2/third_party/indra_ocr/vocab.py
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 38 |
cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30 v0.2/third_party/indra_ocr/LICENSE
|
| 39 |
34e7ab4cbe231f495f9df3abbd9880c22ceb1c0eff84d88648307d4666d63327 v0.2/third_party/indra_ocr/textlayer.py
|
| 40 |
7660d70fb6384094958578452ee86fed813377a63ee1a58c5203cad607219929 v0.2/third_party/indra_ocr/vocab.py
|
| 41 |
+
c971596c3cb69297ce0baee9c3a67fe1b27adb13d8ebaa714d1a1adf5bbc3af7 v0.1.1/README.md
|
| 42 |
+
f92be6cf63cf65cb834dfdf7640321d15e2a3f737df08701c4896747aa0143f8 v0.1.1/compact_lm.py
|
| 43 |
+
f67f3113c6286b4e70ccc43420a85f17e98d61a63eec74bc291fb4a11a1ffe7b v0.1.1/decode.py
|
| 44 |
+
095df69ead204405a034d44abf3d8f43f4b5af34c9630a606cb74e314fa1bb70 v0.1.1/digits.py
|
| 45 |
+
a5ae050f0f976d45316f63d65ef1686ad34dc04a33e12768d36832bce66b3ce7 v0.1.1/lines.py
|
| 46 |
+
980d204e218cd5c839bf7abab2c3dfb131320cf95e780a50ecc3dc3bf4b26006 v0.1.1/models/det_fp32.onnx
|
| 47 |
+
75b33af5f1594119704cffa09de05fbf9938113c857aaa52ba84c9b8f8113ae5 v0.1.1/models/det_hw_fp32.onnx
|
| 48 |
+
fda3ea120008c867bff579289df708bc82efab7cd1633dcfe0706f8848687564 v0.1.1/models/lm.npz
|
| 49 |
+
608d7a5e731dbf1d069e42af8e5691631aadef0c210ca9f43e928e5bf76e4017 v0.1.1/models/meta.json
|
| 50 |
+
47b2b82c163aee09da9b1b5da016cf2789b294e9d8aa6e0618dd2b382f28df80 v0.1.1/models/rec_fp32.onnx
|
| 51 |
+
8f5c548fb21b1d4d746a7d2df9246011f258f84e3b5ffc88168100bcd19cf105 v0.1.1/models/rec_int8.onnx
|
| 52 |
+
1cccd5eddb444041a675e2d72f6556f1b8a4ae40380928cde58a725d1c1b4606 v0.1.1/ocr.py
|
| 53 |
+
09bd49f36625a912fdcd0ca41e98eefe363ff385145811747ae751a7902100af v0.1.1/pdf_route.py
|
| 54 |
+
fd43e13b30f51c3eb172d0cbad93e9b2f12d08b9652fc3d0c085d03a04108ec5 v0.1.1/pdf_text.py
|
| 55 |
+
a6a30a82c6e8f48edb8387d7edce0e33f7c6bfea19b03bf28b37790d7900814a v0.1.1/reading_order.py
|
| 56 |
+
32228d14a99b7494e5825baf560416299accf0ae8cabd3040b8cd4df0992a445 v0.1.1/requirements.txt
|
| 57 |
+
cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30 v0.1.1/third_party/indra_ocr/LICENSE
|
| 58 |
+
c925041e1663d53df35bff4da5ad6bac41d51be15ebe68f78b44f22118e1f47a v0.1.1/third_party/indra_ocr/__init__.py
|
| 59 |
+
34e7ab4cbe231f495f9df3abbd9880c22ceb1c0eff84d88648307d4666d63327 v0.1.1/third_party/indra_ocr/textlayer.py
|
| 60 |
+
7660d70fb6384094958578452ee86fed813377a63ee1a58c5203cad607219929 v0.1.1/third_party/indra_ocr/vocab.py
|
| 61 |
+
f1e12b6d9d04ac7c2076df67741b437dc1020625feb62716923940775cf39678 v0.1.1/upright.py
|
| 62 |
+
f78af9e5da792aa570d73eb7d9d4b6a173e150785e7c246e8e79114f3fd417ec v0.1.1/upright_checks.json
|
v0.1.1/README.md
ADDED
|
@@ -0,0 +1,147 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# sanoOCR v0.1.1 (27 Nov 2026): v0.1 + automatic upright correction
|
| 2 |
+
|
| 3 |
+
**What is new:** pages and photos that are tilted, sideways or upside down are now turned upright before the lines are found. v0.1 assumed straight pages: its error rate doubled at 3° of tilt and the text was mostly lost from about 8°, and at 90° or 180°.
|
| 4 |
+
|
| 5 |
+
**Nothing else changed:** same line reader (`s_pdf_bal`), line finders, language model and settings as v0.1. Use v0.1.1 wherever you used v0.1.
|
| 6 |
+
|
| 7 |
+
How it works (`upright.py`, no new network): the tilt is measured from how the ink lines up (text lines give the sharpest row pattern when horizontal), the page is turned level, and upright vs upside down is decided by reading the widest lines both ways and keeping the side the line reader is more confident on. Any angle from 0° to 360° is handled. It adds about 356 ms per page (one CPU thread). The thresholds were set on dev sets only; the test sets below were not used for tuning.
|
| 8 |
+
|
| 9 |
+
```bash
|
| 10 |
+
python ocr.py photo.jpg # upright correction is on by default
|
| 11 |
+
python ocr.py page.png --no-upright # skip it for pages known to be straight
|
| 12 |
+
```
|
| 13 |
+
|
| 14 |
+
`--json` output gives `upright_deg` per page (the counter-clockwise turn that was applied). Line `box` coordinates refer to the turned page.
|
| 15 |
+
|
| 16 |
+
## Checks (full system, CER %, same items with the correction off and on)
|
| 17 |
+
|
| 18 |
+
Straight inputs must not get worse (95% paired bootstrap of on − off):
|
| 19 |
+
|
| 20 |
+
| Test | Off (v0.1) | On (v0.1.1) | Change, 95% CI |
|
| 21 |
+
|---|---|---|---|
|
| 22 |
+
| Sarvam real Nepali documents (437, print mode) | 4.58% | 4.58% | +0.00 to +0.00 |
|
| 23 |
+
| Sarvam real English documents (299, print mode) | 6.73% | 6.73% | -0.00 to +0.00 |
|
| 24 |
+
| Sarvam Hindi documents (not a target language; reported, not gated) (228, print mode) | 20.85% | 20.97% | -1.01 to +1.52 |
|
| 25 |
+
| Government PDF pages, rendered (118, print mode) | 4.75% | 4.77% | +0.00 to +0.07 |
|
| 26 |
+
| Phone-photo handwriting lines (dev) (308, handwriting mode) | 44.9% | 44.06% | -1.94 to +0.12 |
|
| 27 |
+
| Handwritten lines, photo look (dev) (600, handwriting mode) | 18.28% | 18.29% | -0.09 to +0.11 |
|
| 28 |
+
|
| 29 |
+
Rotated inputs (the test images turned by a known angle):
|
| 30 |
+
|
| 31 |
+
| Test | Turned by | v0.1 | v0.1.1 | Same items upright (v0.1.1) |
|
| 32 |
+
|---|---|---|---|---|
|
| 33 |
+
| Sarvam real Nepali documents (150) | 7° | 51.72% | **6.62%** | 6.16% |
|
| 34 |
+
| Sarvam real Nepali documents (150) | 90° | 79.79% | **6.17%** | 6.16% |
|
| 35 |
+
| Sarvam real Nepali documents (150) | 180° | 86.91% | **6.53%** | 6.16% |
|
| 36 |
+
| Sarvam real Nepali documents (150) | 270° | 83.86% | **6.22%** | 6.16% |
|
| 37 |
+
| Government PDF pages (118) | 7° | 40.33% | **5.9%** | 4.77% |
|
| 38 |
+
| Government PDF pages (118) | 90° | 82.36% | **5.88%** | 4.77% |
|
| 39 |
+
| Government PDF pages (118) | 180° | 82.98% | **4.9%** | 4.77% |
|
| 40 |
+
| Government PDF pages (118) | 270° | 83.06% | **6.02%** | 4.77% |
|
| 41 |
+
| Phone-photo handwriting lines (308) | 7° | 37.37% | **30.59%** | 44.06% |
|
| 42 |
+
| Phone-photo handwriting lines (308) | 90° | 100.0% | **43.52%** | 44.06% |
|
| 43 |
+
| Phone-photo handwriting lines (308) | 180° | 95.93% | **51.38%** | 44.06% |
|
| 44 |
+
| Phone-photo handwriting lines (308) | 270° | 100.0% | **45.81%** | 44.06% |
|
| 45 |
+
|
| 46 |
+
Scored with Unicode whitespace collapsed, micro CER; absolute numbers are not comparable with the main results table, compare the columns. The locked handwriting test was not used. Limits: a single handwritten line crop that is upside down is turned back about 3 times in 4 (pages with several lines are much more reliable); the correction turns the page as a whole; it does not fix perspective (photos taken at a steep angle), curled pages or lines that bend.
|
| 47 |
+
|
| 48 |
+
---
|
| 49 |
+
|
| 50 |
+
# Original v0.1 notes
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
A small OCR system for printed and handwritten Nepali and English, for CPU. No PyTorch and no GPU needed. No Indra model weights are included.
|
| 54 |
+
|
| 55 |
+
**What changed since v0:**
|
| 56 |
+
- **New line reader, s_pdf_bal.** It is the v0 reader (s_digits) trained further on 192,354 real printed lines from 37 Gorkhapatra editions (May 2023 – Nov 2026), with exact labels taken from the PDFs' own text.
|
| 57 |
+
- **Reader shipped in full precision** (3.27 MB). The 8-bit copy (1.06 MB) is still included, but it gives up most of the gain on worn print.
|
| 58 |
+
- **Same size:** 814,143 parameters.
|
| 59 |
+
|
| 60 |
+
## Run
|
| 61 |
+
|
| 62 |
+
```
|
| 63 |
+
pip install -r requirements.txt # numpy, opencv-python-headless, onnxruntime, pypdfium2==4.30.0, regex
|
| 64 |
+
sudo apt install poppler-utils # optional: pdftotext, used for PDF pages whose text layer is trusted
|
| 65 |
+
python ocr.py page.png # printed page or block
|
| 66 |
+
python ocr.py document.pdf --json # per page: route (text layer or OCR), text, time
|
| 67 |
+
python ocr.py letter.jpg --mode handwriting
|
| 68 |
+
python ocr.py page.png --no-lm # faster; better on clean digital print
|
| 69 |
+
python ocr.py page.png --rec rec_int8.onnx # smaller line reader
|
| 70 |
+
```
|
| 71 |
+
|
| 72 |
+
From Python: `from ocr import OCR; o = OCR(mode="print"); o.image(gray_uint8)["text"]`, or `o.pdf(path)`.
|
| 73 |
+
|
| 74 |
+
## What is inside (70 MB)
|
| 75 |
+
|
| 76 |
+
| File | What | Size |
|
| 77 |
+
|---|---|---|
|
| 78 |
+
| `models/rec_fp32.onnx` | Line reader s_pdf_bal, 814,143 parameters (default) | 3.27 MB |
|
| 79 |
+
| `models/rec_int8.onnx` | Same reader, 8-bit (first and last layers kept in float) | 1.06 MB |
|
| 80 |
+
| `models/det_fp32.onnx` | Printed line finder det_a, 59,746 parameters | 0.25 MB |
|
| 81 |
+
| `models/det_hw_fp32.onnx` | Handwritten line finder det_hw_a, 59,746 parameters | 0.25 MB |
|
| 82 |
+
| `models/lm.npz` | Character 7-gram language model (Wikipedia training text + handwriting training texts), n-grams seen 3+ times | 69 MB |
|
| 83 |
+
| `ocr.py` | Find lines → reading order → straighten → read → drop unsure lines → language model → one digit script per number | |
|
| 84 |
+
| `pdf_route.py`, `pdf_text.py` | Per PDF page: use the text layer if it passes the trust checks, otherwise render at 150 dpi and OCR | |
|
| 85 |
+
| `third_party/indra_ocr/` | Two Apache-2.0 code modules (text-layer reading, syllable checks), code only | |
|
| 86 |
+
|
| 87 |
+
Network parameters in the full system: 873,889 (line reader + one line finder).
|
| 88 |
+
|
| 89 |
+
## Modes
|
| 90 |
+
|
| 91 |
+
| Mode | Line finder | Line order | Drops unsure lines | Language model weight, bonus |
|
| 92 |
+
|---|---|---|---|---|
|
| 93 |
+
| `print` (default) | det_a, full size | columns, tables row by row | under 0.5 | 0.2, 2 |
|
| 94 |
+
| `handwriting` | det_hw_a, 0.35× size (A4 scans about 2,500 px wide) | top to bottom | none | 0.4, 1 |
|
| 95 |
+
|
| 96 |
+
## Test results (locked test sets, opened once on 12 Nov; all settings chosen on practice data first)
|
| 97 |
+
|
| 98 |
+
Character error (CER) and word error (WER), lower is better. "Change" compares with v0 on the same items; a range that excludes 0 is a real difference.
|
| 99 |
+
|
| 100 |
+
| Test | v0.1 | v0 (10 Nov) | Change | Indra OCR |
|
| 101 |
+
|---|---|---|---|---|
|
| 102 |
+
| Real Nepali documents, Sarvam (437 blocks) | **4.76% / 15.5%** | 5.34% / 20.1% | −0.68 to −0.48 points | 21.59% / 66.1% |
|
| 103 |
+
| Real English documents, Sarvam (299 blocks) | 6.34% / 16.7% | 6.16% / 15.5% | +0.05 to +0.30 (slightly worse) | 7.21% / 20.3% |
|
| 104 |
+
| Gorkhapatra newspaper lines (1,500), line reader only | 0.37% / 2.4% | 0.36% / 2.5% | no change | 3.96% (fine-tuned Indra 0.34%) |
|
| 105 |
+
| Handwritten lines, 84 unseen writers | 5.28% / 17.2% | 5.30% / 17.3% | no change | (not trained on handwriting) |
|
| 106 |
+
| Handwritten words, same writers | 7.07% / 19.9% | 7.11% / 19.9% | no change | |
|
| 107 |
+
| Handwritten words, IndicScan (other source) | 15.85% | 15.92% | no change | |
|
| 108 |
+
|
| 109 |
+
The newspaper test lines are short word groups cut from 3 editions that were never used for training. Training lines that overlapped any test text were removed first, because notices are reprinted across editions.
|
| 110 |
+
|
| 111 |
+
## Practice-data checks of this package (12 Nov)
|
| 112 |
+
|
| 113 |
+
| Check | v0.1 | v0 |
|
| 114 |
+
|---|---|---|
|
| 115 |
+
| Real Hindi documents, Sarvam dev (228 blocks) | 20.86% | 21.20% |
|
| 116 |
+
| Gorkhapatra full lines, 2 held-out editions | 0.75% | 1.39% |
|
| 117 |
+
| English legal PDFs (Law Commission) | 0.84% | 0.92% |
|
| 118 |
+
| Clean digital print, 60 generated pages in 20 fonts | 0.90% (0.80% with `--no-lm`) | 0.94% (0.92%) |
|
| 119 |
+
| Handwritten lines, dev writers | 6.02% | 6.07% |
|
| 120 |
+
|
| 121 |
+
## Speed (one CPU thread on the OCR server)
|
| 122 |
+
|
| 123 |
+
| Step | Time |
|
| 124 |
+
|---|---|
|
| 125 |
+
| Finding lines | about 58 ms per page or block |
|
| 126 |
+
| Reading a line | 1.4 ms (0.8 ms with `rec_int8.onnx`) |
|
| 127 |
+
| Language model correction | about 21 ms per line (Python; the slowest part) |
|
| 128 |
+
| PDF page with a trusted text layer | about 25 ms |
|
| 129 |
+
| Scanned A4 page, two threads, with the language model | about 0.6 s |
|
| 130 |
+
|
| 131 |
+
## Known limits
|
| 132 |
+
|
| 133 |
+
- **Clean digital print:** the language model doesn't help there; use `--no-lm`.
|
| 134 |
+
- **Old worn letterpress and dictionaries** remain the main source of errors on real documents.
|
| 135 |
+
- **English documents got slightly worse** than in v0 (+0.2 points).
|
| 136 |
+
- **Handwriting:** the line finder's scale is tuned on A4 scans. Phone photos are not supported yet.
|
| 137 |
+
- **PDF text:** the poppler extractor is preferred. Poppler is GPL and is run as a separate program; without it the pdfium extractor is used.
|
| 138 |
+
- **Dense tables** may still be read column by column.
|
| 139 |
+
|
| 140 |
+
## Data and licences
|
| 141 |
+
|
| 142 |
+
- **Training data:**
|
| 143 |
+
- computer-made lines from 66 OFL font families and Wikipedia text (CC BY-SA, attribution required);
|
| 144 |
+
- Gorkhapatra newspaper lines (full-use licence confirmed by the project owner);
|
| 145 |
+
- handwriting datasets 1 and 2 (licences confirmed by the project owner);
|
| 146 |
+
- DHCD digits (CC BY 4.0).
|
| 147 |
+
- **Label conversion:** Gorkhapatra's Preeti-style fonts were converted to Unicode with npttf2utf (GPL). That converter was used only to make the labels and is not included here.
|
v0.1.1/compact_lm.py
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Compact form of decode.CharLM for release: the same Witten-Bell model written in backoff form.
|
| 2 |
+
For every stored n-gram (h + ch) we keep its full interpolated log-probability; for every context h we keep the backoff
|
| 3 |
+
weight log(u / (t + u)). Then
|
| 4 |
+
p(ch | h) = lp[h + ch] if h + ch is stored
|
| 5 |
+
= bow[h] + p(ch | h[1:]) otherwise (bow is 0 for an unseen context)
|
| 6 |
+
p(ch | "") falls back to bow[""] + log(1 / V).
|
| 7 |
+
With nothing pruned this equals CharLM.p exactly (up to float16 rounding). Pruning drops rare n-grams and contexts, which then back off.
|
| 8 |
+
Keys are 64-bit blake2b hashes of the UTF-8 string, kept sorted for binary search; values are float16. No Python dicts at run time."""
|
| 9 |
+
import hashlib, math
|
| 10 |
+
import numpy as np
|
| 11 |
+
|
| 12 |
+
def key(s):
|
| 13 |
+
return int.from_bytes(hashlib.blake2b(s.encode("utf-8"), digest_size=8).digest(), "little")
|
| 14 |
+
|
| 15 |
+
class CompactLM:
|
| 16 |
+
def __init__(s, path):
|
| 17 |
+
z = np.load(path)
|
| 18 |
+
s.o = int(z["order"]); s.V = int(z["V"]); s.nk, s.nv = z["ngram_keys"], z["ngram_lp"]; s.ck, s.cv = z["ctx_keys"], z["ctx_bow"]
|
| 19 |
+
s.base = math.log(1.0 / s.V); s.cache = {}
|
| 20 |
+
@staticmethod
|
| 21 |
+
def _find(keys, vals, k):
|
| 22 |
+
i = int(np.searchsorted(keys, np.uint64(k)))
|
| 23 |
+
return float(vals[i]) if i < len(keys) and int(keys[i]) == k else None
|
| 24 |
+
def p(s, h, ch):
|
| 25 |
+
h = h[-(s.o - 1):] if s.o > 1 else ""; ck_ = (h, ch)
|
| 26 |
+
r = s.cache.get(ck_)
|
| 27 |
+
if r is not None: return r
|
| 28 |
+
acc = 0.0; res = None
|
| 29 |
+
for i in range(len(h) + 1): # longest context first
|
| 30 |
+
hh = h[i:]; v = s._find(s.nk, s.nv, key(hh + ch))
|
| 31 |
+
if v is not None: res = acc + v; break
|
| 32 |
+
b = s._find(s.ck, s.cv, key(hh))
|
| 33 |
+
if b is not None: acc += b
|
| 34 |
+
if res is None: res = acc + s.base
|
| 35 |
+
if len(s.cache) > 2_000_000: s.cache.clear()
|
| 36 |
+
s.cache[ck_] = res; return res
|
| 37 |
+
|
| 38 |
+
def arrays(lm):
|
| 39 |
+
"""Every n-gram's interpolated log-probability and every context's backoff weight, with orders and counts for pruning."""
|
| 40 |
+
from array import array
|
| 41 |
+
nk, nv, no, nc = array("Q"), array("f"), array("B"), array("I")
|
| 42 |
+
for g, c in lm.c.items():
|
| 43 |
+
nk.append(key(g)); nv.append(lm.p(g[:-1], g[-1])); no.append(len(g)); nc.append(min(c, 2**32 - 1))
|
| 44 |
+
if len(lm.cache) > 1_000_000: lm.cache.clear()
|
| 45 |
+
ck, cv, co, cc = array("Q"), array("f"), array("B"), array("I")
|
| 46 |
+
for h, t in lm.t.items():
|
| 47 |
+
u = lm.u[h]; ck.append(key(h)); cv.append(math.log(u / (t + u))); co.append(len(h)); cc.append(min(t, 2**32 - 1))
|
| 48 |
+
f = lambda a, d: np.frombuffer(a, d).copy()
|
| 49 |
+
return dict(o=lm.o, V=lm.V, nk=f(nk, np.uint64), nv=f(nv, np.float32), no=f(no, np.uint8), nc=f(nc, np.uint32),
|
| 50 |
+
ck=f(ck, np.uint64), cv=f(cv, np.float32), co=f(co, np.uint8), cc=f(cc, np.uint32))
|
| 51 |
+
|
| 52 |
+
def write(A, path, min_count=1, min_order=3, dtype=np.float16):
|
| 53 |
+
"""N-grams of order >= min_order seen fewer than min_count times are dropped, and contexts of length >= min_order - 1
|
| 54 |
+
seen fewer than min_count times. Returns (n-grams kept, contexts kept)."""
|
| 55 |
+
m = (A["no"] < min_order) | (A["nc"] >= min_count); nk, nv = A["nk"][m], A["nv"][m]
|
| 56 |
+
o = np.argsort(nk); nk, nv = nk[o], nv[o].astype(dtype)
|
| 57 |
+
m = (A["co"] < min_order - 1) | (A["cc"] >= min_count); ck, cv = A["ck"][m], A["cv"][m]
|
| 58 |
+
o = np.argsort(ck); ck, cv = ck[o], cv[o].astype(dtype)
|
| 59 |
+
assert (np.diff(nk) > 0).all() and (np.diff(ck) > 0).all(), "hash collision"
|
| 60 |
+
np.savez(path, order=A["o"], V=A["V"], ngram_keys=nk, ngram_lp=nv, ctx_keys=ck, ctx_bow=cv)
|
| 61 |
+
return len(nk), len(ck)
|
v0.1.1/decode.py
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Shared decoding: greedy CTC, CTC prefix beam search with a character n-gram language model, and the language model class itself."""
|
| 2 |
+
import math
|
| 3 |
+
from collections import defaultdict
|
| 4 |
+
import numpy as np
|
| 5 |
+
|
| 6 |
+
class CharLM:
|
| 7 |
+
"""Witten-Bell interpolated character n-gram model. Probabilities are cached per (context, char)."""
|
| 8 |
+
def __init__(s, lines, order):
|
| 9 |
+
s.o = order; s.c = defaultdict(int); s.t = defaultdict(int); s.u = defaultdict(int); V = set()
|
| 10 |
+
for l in lines:
|
| 11 |
+
l = "\x02" * (order - 1) + l + "\x03"; V.update(l)
|
| 12 |
+
for i in range(order - 1, len(l)):
|
| 13 |
+
for k in range(order):
|
| 14 |
+
h = l[i - k:i]; g = h + l[i]
|
| 15 |
+
if g not in s.c: s.u[h] += 1
|
| 16 |
+
s.c[g] += 1; s.t[h] += 1
|
| 17 |
+
s.V = len(V); s.cache = {}
|
| 18 |
+
def p(s, h, ch):
|
| 19 |
+
h = h[-(s.o - 1):] if s.o > 1 else ""; key = (h, ch)
|
| 20 |
+
if key in s.cache: return s.cache[key]
|
| 21 |
+
pr = 1.0 / s.V
|
| 22 |
+
for k in range(0, len(h) + 1):
|
| 23 |
+
hh = h[len(h) - k:]; t = s.t.get(hh, 0)
|
| 24 |
+
if t == 0: break
|
| 25 |
+
uu = s.u[hh]; pr = (s.c.get(hh + ch, 0) + uu * pr) / (t + uu)
|
| 26 |
+
lp = math.log(pr)
|
| 27 |
+
if len(s.cache) > 2_000_000: s.cache.clear()
|
| 28 |
+
s.cache[key] = lp; return lp
|
| 29 |
+
|
| 30 |
+
def load_lm(path):
|
| 31 |
+
"""Language models were pickled from a script, so the class is looked up on __main__."""
|
| 32 |
+
if str(path).endswith(".npz"): # compact release format (compact_lm.py)
|
| 33 |
+
from compact_lm import CompactLM; return CompactLM(path)
|
| 34 |
+
import pickle, __main__
|
| 35 |
+
__main__.CharLM = CharLM; lm = pickle.load(open(path, "rb")); lm.cache = {}; return lm
|
| 36 |
+
|
| 37 |
+
def greedy(lp, chars):
|
| 38 |
+
"""lp: [T, classes] log-probabilities. Returns (text, confidence = mean peak probability of emitted characters)."""
|
| 39 |
+
ids = lp.argmax(1); pm = np.exp(lp.max(1)); keep = (ids != 0) & np.concatenate([[True], ids[1:] != ids[:-1]])
|
| 40 |
+
return "".join(chars[i - 1] for i in ids[keep]), float(pm[keep].mean()) if keep.any() else 0.0
|
| 41 |
+
|
| 42 |
+
def _lse(a, b):
|
| 43 |
+
if a == -math.inf: return b
|
| 44 |
+
if b == -math.inf: return a
|
| 45 |
+
m = max(a, b); return m + math.log1p(math.exp(-abs(a - b)))
|
| 46 |
+
|
| 47 |
+
def beam(lp, chars, lm, alpha, beta, B=8, prune=-7.0):
|
| 48 |
+
"""CTC prefix beam search; LM log-probability (times alpha) is added per appended character, beta rewards length."""
|
| 49 |
+
beams = {"": (0.0, -math.inf, 0.0)}
|
| 50 |
+
for t in range(lp.shape[0]):
|
| 51 |
+
row = lp[t]; cand = np.nonzero(row > prune)[0]
|
| 52 |
+
if row[0] > -0.05 and len(cand) == 1:
|
| 53 |
+
beams = {k: (_lse(pb, pnb) + row[0], -math.inf, ls) for k, (pb, pnb, ls) in beams.items()}; continue
|
| 54 |
+
nb = defaultdict(lambda: [-math.inf, -math.inf, 0.0])
|
| 55 |
+
for pre, (pb, pnb, ls) in beams.items():
|
| 56 |
+
tot = _lse(pb, pnb)
|
| 57 |
+
for v in cand.tolist():
|
| 58 |
+
p = float(row[v])
|
| 59 |
+
if v == 0:
|
| 60 |
+
e = nb[pre]; e[0] = _lse(e[0], tot + p); e[2] = ls; continue
|
| 61 |
+
ch = chars[v - 1]; last = pre[-1] if pre else None
|
| 62 |
+
if ch == last:
|
| 63 |
+
e = nb[pre]; e[1] = _lse(e[1], pnb + p); e[2] = ls
|
| 64 |
+
ext = pre + ch; e2 = nb[ext]; e2[1] = _lse(e2[1], pb + p); e2[2] = ls + alpha * lm.p(pre, ch)
|
| 65 |
+
else:
|
| 66 |
+
ext = pre + ch; e2 = nb[ext]; e2[1] = _lse(e2[1], tot + p); e2[2] = ls + alpha * lm.p(pre, ch)
|
| 67 |
+
beams = dict(sorted(((k, tuple(v)) for k, v in nb.items()), key=lambda kv: -(_lse(kv[1][0], kv[1][1]) + kv[1][2] + beta * len(kv[0])))[:B])
|
| 68 |
+
return max(beams.items(), key=lambda kv: _lse(kv[1][0], kv[1][1]) + kv[1][2] + alpha * lm.p(kv[0], "\x03") + beta * len(kv[0]))[0]
|
v0.1.1/digits.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""One digit script per number. The recognizer sometimes mixes Latin and Devanagari digits inside one number (2075/१0/१3), which is never
|
| 2 |
+
right in Nepali or English text. For each run of digits (separators - / . , : allowed inside), the script whose digit classes get more
|
| 3 |
+
total probability over the run's frames wins, and every digit of the run is written in that script. No parameters; uses the CTC output."""
|
| 4 |
+
import re
|
| 5 |
+
import numpy as np
|
| 6 |
+
LAT, DEV = "0123456789", "०१२३४५६७८९"
|
| 7 |
+
TO_LAT, TO_DEV = str.maketrans(DEV, LAT), str.maketrans(LAT, DEV)
|
| 8 |
+
RUN = re.compile(r"[0-9०-९](?:[-/.,:]?[0-9०-९])*")
|
| 9 |
+
|
| 10 |
+
def run_scripts(lp, chars):
|
| 11 |
+
"""Greedy path of a line's log-probabilities [T, classes]: for each digit run, 'lat' or 'dev' by summed probability mass."""
|
| 12 |
+
li = [chars.index(c) + 1 for c in LAT if c in chars]; di = [chars.index(c) + 1 for c in DEV if c in chars]
|
| 13 |
+
if not li or not di: return []
|
| 14 |
+
ids = lp.argmax(1); keep = (ids != 0) & np.concatenate([[True], ids[1:] != ids[:-1]]); fr = np.nonzero(keep)[0]
|
| 15 |
+
txt = "".join(chars[i - 1] for i in ids[keep]); P = np.exp(lp); out = []
|
| 16 |
+
for m in RUN.finditer(txt):
|
| 17 |
+
ts = [fr[k] for k in range(m.start(), m.end()) if txt[k] in LAT or txt[k] in DEV]
|
| 18 |
+
out.append("lat" if P[ts][:, li].sum() >= P[ts][:, di].sum() else "dev")
|
| 19 |
+
return out
|
| 20 |
+
|
| 21 |
+
def unify(text, scripts):
|
| 22 |
+
"""Rewrite each digit run of text in its script; runs are matched to scripts in order. Runs without a matching script use their own majority."""
|
| 23 |
+
k = [0]
|
| 24 |
+
def f(m):
|
| 25 |
+
s = m.group(0); i = k[0]; k[0] += 1
|
| 26 |
+
if i < len(scripts): sc = scripts[i]
|
| 27 |
+
else: sc = "lat" if sum(c in LAT for c in s) >= sum(c in DEV for c in s) else "dev"
|
| 28 |
+
return s.translate(TO_LAT if sc == "lat" else TO_DEV)
|
| 29 |
+
return RUN.sub(f, text)
|
v0.1.1/lines.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Line image loading shared by training and evaluation, so both see the same preprocessing."""
|
| 2 |
+
import numpy as np, cv2
|
| 3 |
+
H = 32
|
| 4 |
+
def text_band(gray):
|
| 5 |
+
"""Crop to the main band of ink rows plus a fixed margin, so text fills the same share of the height however the crop was made. Adds no parameters."""
|
| 6 |
+
h = gray.shape[0]
|
| 7 |
+
if h < 8: return gray
|
| 8 |
+
lo, hi = float(gray.min()), float(np.percentile(gray, 90))
|
| 9 |
+
if hi - lo < 30: return gray
|
| 10 |
+
prof = (gray < (lo + hi) / 2).mean(1); on = prof > max(.01, .15 * prof.max()); best = (0, 0); s = None
|
| 11 |
+
for i, v in enumerate(list(on) + [False]):
|
| 12 |
+
if v and s is None: s = i
|
| 13 |
+
if not v and s is not None:
|
| 14 |
+
if prof[s:i].sum() > prof[best[0]:best[1]].sum(): best = (s, i)
|
| 15 |
+
s = None
|
| 16 |
+
a, b = best
|
| 17 |
+
if b - a < 4: return gray
|
| 18 |
+
# extend over faint rows holding vowel signs and lower marks, then add a margin
|
| 19 |
+
n = b - a; a2 = max(0, a - int(.35 * n)); b2 = min(h, b + int(.35 * n)); m = int(.1 * n) + 1
|
| 20 |
+
while a2 > 0 and a > a2 and prof[a2:a].max() < .002: a2 += 1; break
|
| 21 |
+
return gray[max(0, a2 - m):min(h, b2 + m)]
|
| 22 |
+
def prep(gray, H=32, norm=False):
|
| 23 |
+
if norm: gray = text_band(gray)
|
| 24 |
+
h, w = gray.shape[:2]; nw = max(8, min(4096, round(w * H / max(1, h))))
|
| 25 |
+
g = cv2.resize(gray, (nw, H), interpolation=cv2.INTER_AREA if h > H else cv2.INTER_LINEAR).astype(np.float32)
|
| 26 |
+
return 1 - g / 255
|
| 27 |
+
def batch(arrs):
|
| 28 |
+
H = arrs[0].shape[0]; W = max(a.shape[1] for a in arrs); W += (-W) % 8; x = np.zeros((len(arrs), 1, H, W), np.float32)
|
| 29 |
+
for i, a in enumerate(arrs): x[i, 0, :, :a.shape[1]] = a
|
| 30 |
+
return x, np.array([a.shape[1] for a in arrs], np.int64)
|
| 31 |
+
def crop(gray, box):
|
| 32 |
+
x0, y0, x1, y1 = box; h = y1 - y0; px, py = .3 * h, .2 * h
|
| 33 |
+
X0, Y0, X1, Y1 = int(max(0, x0 - px)), int(max(0, y0 - py)), int(x1 + px), int(y1 + py)
|
| 34 |
+
c = gray[Y0:Y1, X0:X1]; return c if c.size else gray[:8, :8]
|
v0.1.1/models/det_fp32.onnx
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:980d204e218cd5c839bf7abab2c3dfb131320cf95e780a50ecc3dc3bf4b26006
|
| 3 |
+
size 252274
|
v0.1.1/models/det_hw_fp32.onnx
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:75b33af5f1594119704cffa09de05fbf9938113c857aaa52ba84c9b8f8113ae5
|
| 3 |
+
size 252274
|
v0.1.1/models/lm.npz
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:fda3ea120008c867bff579289df708bc82efab7cd1633dcfe0706f8848687564
|
| 3 |
+
size 68810288
|
v0.1.1/models/meta.json
ADDED
|
@@ -0,0 +1,200 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"chars": [
|
| 3 |
+
" ",
|
| 4 |
+
"!",
|
| 5 |
+
"\"",
|
| 6 |
+
"#",
|
| 7 |
+
"$",
|
| 8 |
+
"%",
|
| 9 |
+
"&",
|
| 10 |
+
"'",
|
| 11 |
+
"(",
|
| 12 |
+
")",
|
| 13 |
+
"*",
|
| 14 |
+
"+",
|
| 15 |
+
",",
|
| 16 |
+
"-",
|
| 17 |
+
".",
|
| 18 |
+
"/",
|
| 19 |
+
"0",
|
| 20 |
+
"1",
|
| 21 |
+
"2",
|
| 22 |
+
"3",
|
| 23 |
+
"4",
|
| 24 |
+
"5",
|
| 25 |
+
"6",
|
| 26 |
+
"7",
|
| 27 |
+
"8",
|
| 28 |
+
"9",
|
| 29 |
+
":",
|
| 30 |
+
";",
|
| 31 |
+
"<",
|
| 32 |
+
"=",
|
| 33 |
+
">",
|
| 34 |
+
"?",
|
| 35 |
+
"@",
|
| 36 |
+
"A",
|
| 37 |
+
"B",
|
| 38 |
+
"C",
|
| 39 |
+
"D",
|
| 40 |
+
"E",
|
| 41 |
+
"F",
|
| 42 |
+
"G",
|
| 43 |
+
"H",
|
| 44 |
+
"I",
|
| 45 |
+
"J",
|
| 46 |
+
"K",
|
| 47 |
+
"L",
|
| 48 |
+
"M",
|
| 49 |
+
"N",
|
| 50 |
+
"O",
|
| 51 |
+
"P",
|
| 52 |
+
"Q",
|
| 53 |
+
"R",
|
| 54 |
+
"S",
|
| 55 |
+
"T",
|
| 56 |
+
"U",
|
| 57 |
+
"V",
|
| 58 |
+
"W",
|
| 59 |
+
"X",
|
| 60 |
+
"Y",
|
| 61 |
+
"Z",
|
| 62 |
+
"[",
|
| 63 |
+
"\\",
|
| 64 |
+
"]",
|
| 65 |
+
"^",
|
| 66 |
+
"_",
|
| 67 |
+
"`",
|
| 68 |
+
"a",
|
| 69 |
+
"b",
|
| 70 |
+
"c",
|
| 71 |
+
"d",
|
| 72 |
+
"e",
|
| 73 |
+
"f",
|
| 74 |
+
"g",
|
| 75 |
+
"h",
|
| 76 |
+
"i",
|
| 77 |
+
"j",
|
| 78 |
+
"k",
|
| 79 |
+
"l",
|
| 80 |
+
"m",
|
| 81 |
+
"n",
|
| 82 |
+
"o",
|
| 83 |
+
"p",
|
| 84 |
+
"q",
|
| 85 |
+
"r",
|
| 86 |
+
"s",
|
| 87 |
+
"t",
|
| 88 |
+
"u",
|
| 89 |
+
"v",
|
| 90 |
+
"w",
|
| 91 |
+
"x",
|
| 92 |
+
"y",
|
| 93 |
+
"z",
|
| 94 |
+
"{",
|
| 95 |
+
"|",
|
| 96 |
+
"}",
|
| 97 |
+
"~",
|
| 98 |
+
"£",
|
| 99 |
+
"©",
|
| 100 |
+
"®",
|
| 101 |
+
"°",
|
| 102 |
+
"×",
|
| 103 |
+
"ँ",
|
| 104 |
+
"ं",
|
| 105 |
+
"ः",
|
| 106 |
+
"अ",
|
| 107 |
+
"आ",
|
| 108 |
+
"इ",
|
| 109 |
+
"ई",
|
| 110 |
+
"उ",
|
| 111 |
+
"ऊ",
|
| 112 |
+
"ऋ",
|
| 113 |
+
"ए",
|
| 114 |
+
"ऐ",
|
| 115 |
+
"ऑ",
|
| 116 |
+
"ओ",
|
| 117 |
+
"औ",
|
| 118 |
+
"क",
|
| 119 |
+
"ख",
|
| 120 |
+
"ग",
|
| 121 |
+
"घ",
|
| 122 |
+
"ङ",
|
| 123 |
+
"च",
|
| 124 |
+
"छ",
|
| 125 |
+
"ज",
|
| 126 |
+
"झ",
|
| 127 |
+
"ञ",
|
| 128 |
+
"ट",
|
| 129 |
+
"ठ",
|
| 130 |
+
"ड",
|
| 131 |
+
"ढ",
|
| 132 |
+
"ण",
|
| 133 |
+
"त",
|
| 134 |
+
"थ",
|
| 135 |
+
"द",
|
| 136 |
+
"ध",
|
| 137 |
+
"न",
|
| 138 |
+
"प",
|
| 139 |
+
"फ",
|
| 140 |
+
"ब",
|
| 141 |
+
"भ",
|
| 142 |
+
"म",
|
| 143 |
+
"य",
|
| 144 |
+
"र",
|
| 145 |
+
"ऱ",
|
| 146 |
+
"ल",
|
| 147 |
+
"ळ",
|
| 148 |
+
"व",
|
| 149 |
+
"श",
|
| 150 |
+
"ष",
|
| 151 |
+
"स",
|
| 152 |
+
"ह",
|
| 153 |
+
"़",
|
| 154 |
+
"ऽ",
|
| 155 |
+
"ा",
|
| 156 |
+
"ि",
|
| 157 |
+
"ी",
|
| 158 |
+
"ु",
|
| 159 |
+
"ू",
|
| 160 |
+
"ृ",
|
| 161 |
+
"ॅ",
|
| 162 |
+
"े",
|
| 163 |
+
"ै",
|
| 164 |
+
"ॉ",
|
| 165 |
+
"ो",
|
| 166 |
+
"ौ",
|
| 167 |
+
"्",
|
| 168 |
+
"ॐ",
|
| 169 |
+
"ॠ",
|
| 170 |
+
"।",
|
| 171 |
+
"॥",
|
| 172 |
+
"०",
|
| 173 |
+
"१",
|
| 174 |
+
"२",
|
| 175 |
+
"३",
|
| 176 |
+
"४",
|
| 177 |
+
"५",
|
| 178 |
+
"६",
|
| 179 |
+
"७",
|
| 180 |
+
"८",
|
| 181 |
+
"९",
|
| 182 |
+
"॰",
|
| 183 |
+
"–",
|
| 184 |
+
"—",
|
| 185 |
+
"‘",
|
| 186 |
+
"’",
|
| 187 |
+
"“",
|
| 188 |
+
"”",
|
| 189 |
+
"•",
|
| 190 |
+
"₨",
|
| 191 |
+
"€",
|
| 192 |
+
"₹"
|
| 193 |
+
],
|
| 194 |
+
"H": 48,
|
| 195 |
+
"norm": false,
|
| 196 |
+
"params": 814143,
|
| 197 |
+
"rec": "runs/s_pdf_bal/best.pt",
|
| 198 |
+
"det": "runs/det_a/best.pt",
|
| 199 |
+
"det_params": 59746
|
| 200 |
+
}
|
v0.1.1/models/rec_fp32.onnx
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:47b2b82c163aee09da9b1b5da016cf2789b294e9d8aa6e0618dd2b382f28df80
|
| 3 |
+
size 3274175
|
v0.1.1/models/rec_int8.onnx
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:8f5c548fb21b1d4d746a7d2df9246011f258f84e3b5ffc88168100bcd19cf105
|
| 3 |
+
size 1059014
|
v0.1.1/ocr.py
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""End-to-end Nepali + English OCR for CPU, without PyTorch.
|
| 3 |
+
Images: upright correction (any rotation, upright.py) -> line detector (ONNX) -> reading order -> per-line straightening -> recognizer (ONNX, int8) -> confidence filter -> CTC beam search
|
| 4 |
+
with a compact character language model -> one digit script per number (digits.py). PDFs: each page is routed; a trusted text layer is read directly, any other page is rendered and OCR'd.
|
| 5 |
+
Two modes with the settings each was validated with: print (pipeline_eval.py, frozen 10 Nov, plus table-aware reading order) and
|
| 6 |
+
handwriting (nhd_pipeline.py: handwriting line detector at scale 0.35 for ~A4 scans, lines sorted by centre height, no confidence filter).
|
| 7 |
+
usage: python ocr.py FILE [FILE ...] [--mode print|handwriting] [--no-lm] [--threads 1] [--dpi 150] [--json]"""
|
| 8 |
+
import argparse, json, math, sys, time
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
import numpy as np, cv2, onnxruntime as ort
|
| 11 |
+
T = Path(__file__).resolve().parent; sys.path[:0] = [str(T), str(T/"third_party")]
|
| 12 |
+
import decode as D, reading_order as RO, digits as DG
|
| 13 |
+
from lines import prep
|
| 14 |
+
import upright as UP
|
| 15 |
+
CORE = .4 # detector core band = middle 40% of the line height (as in tiny_det.py)
|
| 16 |
+
MODES = {"print": dict(det="det_fp32.onnx", det_scale=1.0, alpha=.2, beta=2.0, min_conf=.5, order="xycut"),
|
| 17 |
+
"handwriting": dict(det="det_hw_fp32.onnx", det_scale=.35, alpha=.4, beta=1.0, min_conf=0.0, order="y")}
|
| 18 |
+
|
| 19 |
+
def boxes_from(prob, scale=1.0, stride=2, th=.5, min_area=3):
|
| 20 |
+
"""Line boxes [x0, y0, x1, y1, slope] in input pixels from the detector's core probability map (tiny_det.boxes_from, thick=True, slopes=True)."""
|
| 21 |
+
n, lab, st, _ = cv2.connectedComponentsWithStats((prob >= th).astype(np.uint8), connectivity=4); out = []
|
| 22 |
+
for i in range(1, n):
|
| 23 |
+
x, y, bw, bh, a = st[i]
|
| 24 |
+
if a < min_area: continue
|
| 25 |
+
ch = bh * stride; cy = (y + bh / 2) * stride; t = min(ch, a / bw * stride); H = (ch - t) + t / CORE; m = .25 * t / CORE
|
| 26 |
+
b = [(x * stride - m) / scale, (cy - H / 2) / scale, ((x + bw) * stride + m) / scale, (cy + H / 2) / scale]
|
| 27 |
+
ys, xs = np.nonzero(lab[y:y + bh, x:x + bw] == i); k = 0.0
|
| 28 |
+
if bw >= 8 and len(xs) > 10 and np.ptp(xs) > 0: k = float(np.polyfit(xs, ys, 1)[0])
|
| 29 |
+
out.append(b + [k])
|
| 30 |
+
return out
|
| 31 |
+
|
| 32 |
+
class OCR:
|
| 33 |
+
def __init__(s, model=T/"models", rec="rec_fp32.onnx", lm=T/"models/lm.npz",
|
| 34 |
+
mode="print", threads=1, digits=True, tables=True, det_th=.5, upright=True, **over):
|
| 35 |
+
c = dict(MODES[mode]); c.update(over) # any mode setting can be overridden by keyword
|
| 36 |
+
model = Path(model); meta = json.load(open(model/"meta.json", encoding="utf-8")); s.chars, s.H, s.norm = meta["chars"], meta["H"], meta["norm"]
|
| 37 |
+
so = ort.SessionOptions(); so.intra_op_num_threads = threads; so.inter_op_num_threads = 1
|
| 38 |
+
s.rec = ort.InferenceSession(str(model/rec), so, providers=["CPUExecutionProvider"]); s.det = ort.InferenceSession(str(model/c["det"]), so, providers=["CPUExecutionProvider"])
|
| 39 |
+
s.lm = D.load_lm(lm) if lm else None; s.alpha, s.beta, s.min_conf, s.det_scale, s.order = c["alpha"], c["beta"], c["min_conf"], c["det_scale"], c["order"]
|
| 40 |
+
s.upright = upright
|
| 41 |
+
s.det_th, s.digits, s.tables, s.mode = det_th, digits, tables, mode
|
| 42 |
+
def detect(s, g):
|
| 43 |
+
h, w = g.shape; sc = min(s.det_scale, 2400 / max(h, w))
|
| 44 |
+
gg = cv2.resize(g, (max(16, int(w * sc)), max(16, int(h * sc))), interpolation=cv2.INTER_AREA if sc < 1 else cv2.INTER_LINEAR) if sc != 1 else g # AREA: antialiased shrink, like PIL
|
| 45 |
+
H, Wd = gg.shape; z = np.zeros(((H + 31) // 32 * 32, (Wd + 31) // 32 * 32), np.float32); z[:H, :Wd] = 1 - gg.astype(np.float32) / 255
|
| 46 |
+
lg = s.det.run(None, {"x": z[None, None]})[0][0, 0][:H // 2, :Wd // 2]; p = 1 / (1 + np.exp(-lg))
|
| 47 |
+
bx = [[max(0, b[0]), max(0, b[1]), min(w, b[2]), min(h, b[3]), b[4]] for b in boxes_from(p, sc, th=s.det_th)]
|
| 48 |
+
if not bx: return []
|
| 49 |
+
if s.order == "y": return sorted(bx, key=lambda b: (b[1] + b[3]) / 2) # top to bottom by line centre, as nhd_pipeline.py
|
| 50 |
+
return RO.xycut_shear(bx, tables=s.tables)
|
| 51 |
+
@staticmethod
|
| 52 |
+
def crop(g, b):
|
| 53 |
+
"""Tight crop of a line box; a tilted line is sheared level and the rise trimmed (pipeline_eval.tight with straighten=1)."""
|
| 54 |
+
x0, y0, x1, y1 = [int(round(v)) for v in b[:4]]; k = g[max(0, y0):y1, max(0, x0):x1]
|
| 55 |
+
if not k.size: return g[:8, :8]
|
| 56 |
+
sl = b[4]
|
| 57 |
+
if abs(sl) > .004:
|
| 58 |
+
hh, ww = k.shape; M = np.float32([[1, 0, 0], [sl, 1, -sl * ww / 2]])
|
| 59 |
+
im = cv2.warpAffine(k, M, (ww, hh), flags=cv2.INTER_LINEAR | cv2.WARP_INVERSE_MAP, borderValue=255)
|
| 60 |
+
c = int(abs(sl) * ww / 2); k = im[c:hh - c] if hh - 2 * c >= 8 else im
|
| 61 |
+
return k
|
| 62 |
+
def read_line(s, k):
|
| 63 |
+
x = prep(k, s.H, s.norm)[None, None].astype(np.float32); lg = s.rec.run(None, {"x": x})[0][0]
|
| 64 |
+
lp = lg - lg.max(1, keepdims=True); lp = lp - np.log(np.exp(lp).sum(1, keepdims=True))
|
| 65 |
+
t, cf = D.greedy(lp, s.chars)
|
| 66 |
+
if cf < s.min_conf: return "", cf
|
| 67 |
+
out = D.beam(lp, s.chars, s.lm, s.alpha, s.beta) if s.lm else t
|
| 68 |
+
return (DG.unify(out, DG.run_scripts(lp, s.chars)) if s.digits else out), cf
|
| 69 |
+
def image(s, g):
|
| 70 |
+
"""g: grayscale uint8 page or block. Returns text (lines joined by newlines) and per-line detail."""
|
| 71 |
+
t0 = time.perf_counter(); deg = 0.0
|
| 72 |
+
if s.upright: g, deg = UP.fix(s, g)
|
| 73 |
+
bx = s.detect(g); t1 = time.perf_counter(); L = []
|
| 74 |
+
for b in bx:
|
| 75 |
+
t, cf = s.read_line(s.crop(g, b)); L.append(dict(box=[round(v, 1) for v in b[:4]], text=t, conf=round(cf, 3)))
|
| 76 |
+
t2 = time.perf_counter()
|
| 77 |
+
return dict(text="\n".join(l["text"] for l in L if l["text"]), lines=L, upright_deg=deg, ms=dict(detect=round(1000 * (t1 - t0), 1), read=round(1000 * (t2 - t1), 1)))
|
| 78 |
+
def pdf(s, path, dpi=150, extractor="poppler"):
|
| 79 |
+
import pypdfium2 as pdfium, pdf_route as PR, pdf_text as PT, subprocess, shutil
|
| 80 |
+
if extractor == "poppler" and not shutil.which("pdftotext"): extractor = "pdfium" # poppler-utils not installed
|
| 81 |
+
out = []; doc = pdfium.PdfDocument(str(path))
|
| 82 |
+
for i in range(len(doc)):
|
| 83 |
+
p = doc[i]; t0 = time.perf_counter(); g100 = np.asarray(p.render(scale=100 / 72).to_pil().convert("L")); ok, tl, info = PR.page_text_ok(p, g100, 100 / 72)
|
| 84 |
+
if ok:
|
| 85 |
+
txt = PT.page_text(p) if extractor == "pdfium" else subprocess.run(["pdftotext", "-raw", "-f", str(i + 1), "-l", str(i + 1), str(path), "-"], capture_output=True, text=True).stdout.strip()
|
| 86 |
+
out.append(dict(page=i + 1, route="text", text=txt, ms=round(1000 * (time.perf_counter() - t0), 1)))
|
| 87 |
+
else:
|
| 88 |
+
g = np.asarray(p.render(scale=dpi / 72).to_pil().convert("L")); r = s.image(g)
|
| 89 |
+
out.append(dict(page=i + 1, route="ocr", reason=info.get("reason", ""), text=r["text"], ms=round(1000 * (time.perf_counter() - t0), 1)))
|
| 90 |
+
p.close()
|
| 91 |
+
doc.close(); return out
|
| 92 |
+
|
| 93 |
+
if __name__ == "__main__":
|
| 94 |
+
a = argparse.ArgumentParser(); a.add_argument("files", nargs="+"); a.add_argument("--model", default=str(T/"models")); a.add_argument("--rec", default="rec_fp32.onnx", help="rec_int8.onnx: 1.06 MB, slightly less accurate on worn print")
|
| 95 |
+
a.add_argument("--lm", default=str(T/"models/lm.npz")); a.add_argument("--no-lm", action="store_true"); a.add_argument("--mode", default="print", choices=list(MODES))
|
| 96 |
+
a.add_argument("--threads", type=int, default=1); a.add_argument("--dpi", type=int, default=150); a.add_argument("--json", action="store_true")
|
| 97 |
+
a.add_argument("--no-upright", action="store_true", help="skip the page upright correction (pages known to be straight)"); x = a.parse_args()
|
| 98 |
+
o = OCR(x.model, x.rec, None if x.no_lm else x.lm, mode=x.mode, threads=x.threads, upright=not x.no_upright)
|
| 99 |
+
for f in x.files:
|
| 100 |
+
if f.lower().endswith(".pdf"): r = o.pdf(f, x.dpi)
|
| 101 |
+
else: r = [o.image(cv2.imread(f, cv2.IMREAD_GRAYSCALE))]
|
| 102 |
+
if x.json: print(json.dumps(dict(file=f, pages=r), ensure_ascii=False))
|
| 103 |
+
else:
|
| 104 |
+
for pg in r: print(pg["text"])
|
v0.1.1/pdf_route.py
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Decide per PDF page: use the embedded text, or send the page to OCR. Adds no model parameters.
|
| 3 |
+
Reuses the Apache-2.0 text-layer checks from indra_ocr and adds a check for legacy Nepali fonts (Preeti and similar),
|
| 4 |
+
whose text layer is valid Latin text that is really Nepali in a custom encoding."""
|
| 5 |
+
import argparse, ctypes, json, re, sys, time, unicodedata as u
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
import numpy as np, pypdfium2 as pdfium, pypdfium2.raw as R
|
| 8 |
+
from indra_ocr.textlayer import read_text_layer, extract_runs
|
| 9 |
+
from indra_ocr.vocab import indic_page_ok
|
| 10 |
+
LEGACY_FONTS = re.compile(r"preeti|kantipur|sagarmatha|himali|himalb|pcs ?nepali|ganesh|kanchan|aakriti|sumodacharya|shangrila|nepali", re.I)
|
| 11 |
+
UNICODE_OK = re.compile(r"noto|kalimati|mangal|mukta|annapurna|unicode|lohit|nirmala|kokila|utsaah|aparajita", re.I)
|
| 12 |
+
def font_names(page):
|
| 13 |
+
names = set(); buf = ctypes.create_string_buffer(256)
|
| 14 |
+
for o in page.get_objects(max_depth=4):
|
| 15 |
+
if o.type != R.FPDF_PAGEOBJ_TEXT: continue
|
| 16 |
+
f = R.FPDFTextObj_GetFont(o.raw)
|
| 17 |
+
if f and (getattr(R, "FPDFFont_GetBaseFontName", None) or R.FPDFFont_GetFontName)(f, buf, 256): names.add(buf.value.decode("utf-8", "ignore"))
|
| 18 |
+
return names
|
| 19 |
+
def legacy_text_score(text):
|
| 20 |
+
"""Share of tokens that look like legacy-font Nepali: letters mixed with symbols or digits, as in g]kfn or ;/sf/."""
|
| 21 |
+
toks = [t for t in text.split() if any(c.isalpha() for c in t) and all(ord(c) < 128 for c in t) and not re.search(r"@|www\.|https?:|\.(com|org|np|gov|net)\b", t, re.I)]
|
| 22 |
+
if not toks: return 0.0
|
| 23 |
+
def odd(t):
|
| 24 |
+
c = t.strip(".,:;!?()'\"-")
|
| 25 |
+
return bool(re.search(r"[a-zA-Z][\]\[;{}\\|=+~^`\"<>#%&*_0-9][a-zA-Z]|^[;\]\[{}/\\|=+~^`][a-zA-Z]|[a-zA-Z][\]\[;{}/\\|=+~^`]$", c)) or bool(re.search(r"[a-z][A-Z].*[a-z][A-Z]", c))
|
| 26 |
+
return sum(map(odd, toks)) / len(toks)
|
| 27 |
+
def broken_mix_score(text):
|
| 28 |
+
"""Share of Devanagari tokens holding characters that do not belong in a word, as in सामाÛय £ा where a font map failed partway."""
|
| 29 |
+
toks = [t for t in text.split() if any(0x900 <= ord(c) <= 0x97f for c in t)]
|
| 30 |
+
if not toks: return 0.0
|
| 31 |
+
ok = lambda c: 0x900 <= ord(c) <= 0x97f or ord(c) < 128 or u.category(c)[0] in "PZ" or c in "\u200c\u200d₹"
|
| 32 |
+
return sum(any(not ok(c) for c in t) for t in toks) / len(toks)
|
| 33 |
+
def ink_coverage(gray, lines, scale, pad=3):
|
| 34 |
+
"""Share of the page's dark pixels that lie inside text-layer boxes. Low coverage means a scan or image with little real text, such as a watermark."""
|
| 35 |
+
ink = gray < 160; total = int(ink.sum())
|
| 36 |
+
if not total: return 1.0
|
| 37 |
+
m = np.zeros_like(ink); H, W = ink.shape
|
| 38 |
+
for l in lines:
|
| 39 |
+
x0, y0, x1, y1 = l.bbox; m[max(0, int(y0 * scale) - pad):min(H, int(y1 * scale) + pad + 1), max(0, int(x0 * scale) - pad):min(W, int(x1 * scale) + pad + 1)] = True
|
| 40 |
+
return float((ink & m).sum() / total)
|
| 41 |
+
def page_text_ok(page, gray, scale):
|
| 42 |
+
tl = read_text_layer(page, gray, scale); info = dict(tl.stats, trusted_base=tl.trusted, reason=tl.reason)
|
| 43 |
+
if not tl.trusted: return False, tl, info
|
| 44 |
+
text = " ".join(l.text for l in tl.lines); fonts = font_names(page); info["fonts"] = sorted(fonts)
|
| 45 |
+
letters = [c for c in text if c.isalpha()]; info["deva_share"] = round(sum(0x900 <= ord(c) <= 0x97f for c in letters) / max(1, len(letters)), 3)
|
| 46 |
+
info["legacy_score"] = round(legacy_text_score(text), 3); bad_font = any(LEGACY_FONTS.search(f) and not UNICODE_OK.search(f) for f in fonts)
|
| 47 |
+
if info["legacy_score"] > .15 or (bad_font and info["deva_share"] < .5):
|
| 48 |
+
info["reason"] = "legacy Nepali font encoding"; return False, tl, info
|
| 49 |
+
info["broken_mix"] = round(broken_mix_score(text), 3); info["ink_coverage"] = round(ink_coverage(gray, tl.lines, scale), 3); page_lines = [l.text for l in tl.lines]
|
| 50 |
+
if info["broken_mix"] > .02: info["reason"] = "partly broken font map"; return False, tl, info
|
| 51 |
+
if info["deva_share"] > .3 and not indic_page_ok(page_lines): info["reason"] = "invalid Devanagari syllables"; return False, tl, info
|
| 52 |
+
if info["ink_coverage"] < .4: info["reason"] = "text covers little of the page ink"; return False, tl, info
|
| 53 |
+
return True, tl, info
|
| 54 |
+
def route(path, dpi=100):
|
| 55 |
+
doc = pdfium.PdfDocument(str(path)); out = []
|
| 56 |
+
for i in range(len(doc)):
|
| 57 |
+
p = doc[i]; t0 = time.time(); g = np.asarray(p.render(scale=dpi / 72).to_pil().convert("L")); ok, tl, info = page_text_ok(p, g, dpi / 72)
|
| 58 |
+
out.append(dict(page=i + 1, route="text" if ok else "ocr", reason=info.get("reason", ""), lines=len(tl.lines), text="\n".join(l.text for l in tl.lines) if ok else "", info=info, ms=round((time.time() - t0) * 1000))); p.close()
|
| 59 |
+
doc.close(); return out
|
| 60 |
+
if __name__ == "__main__":
|
| 61 |
+
for s, want in (("g]kfn ;/sf/ sf7df8f}F", True), ("Government of Nepal, Kathmandu 2081", False), ("नेपाल सरकार", False), ("Email: a.b@c.org, www.x.np/a", False), ("and/or McDonald rock'n'roll well-known", False), ("sf/f]jf/ ug]{ JolQmsf] gfd", True)):
|
| 62 |
+
v = legacy_text_score(s); assert (v > .15) == want, (s, v); print("unit ok", s, round(v, 2))
|
| 63 |
+
a = argparse.ArgumentParser(); a.add_argument("pdfs", nargs="*"); x = a.parse_args()
|
| 64 |
+
for f in x.pdfs:
|
| 65 |
+
for r in route(f): print(Path(f).name, "p", r["page"], r["route"], "|", r["reason"], "| lines", r["lines"], "| deva", r["info"].get("deva_share"), "| legacy", r["info"].get("legacy_score"), "| mix", r["info"].get("broken_mix"), "| cover", r["info"].get("ink_coverage"), "|", r["ms"], "ms", "|", r["text"][:90].replace("\n", " / "))
|
v0.1.1/pdf_text.py
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Page text from a PDF text layer with geometry-checked word spaces.
|
| 2 |
+
pdfium inserts its own ("generated") spaces where it guesses a word break from glyph positions. In Devanagari the vowel sign ि is
|
| 3 |
+
drawn to the left of its consonant, so the position jumps back and pdfium guesses a break: मिति comes out as मि ति. Here a generated
|
| 4 |
+
space is kept only when the gap on the page between the ink before it and the ink after it is at least min_gap times the font
|
| 5 |
+
size. On a real government notice false spaces had gaps of 0.03-0.21 font sizes and real word spaces 0.27 or more.
|
| 6 |
+
Spaces written in the PDF itself are always kept, and so is a generated space between glyphs on different lines."""
|
| 7 |
+
import ctypes
|
| 8 |
+
import pypdfium2.raw as R
|
| 9 |
+
|
| 10 |
+
def page_text(page, min_gap=0.2):
|
| 11 |
+
"""Text of a pypdfium2 page in content order, lines joined by newlines. min_gap is the smallest ink gap, as a fraction of the
|
| 12 |
+
font size, that keeps a generated space."""
|
| 13 |
+
tp = page.get_textpage(); n = tp.count_chars(); raw = tp.raw
|
| 14 |
+
l, r_, b, t = (ctypes.c_double() for _ in range(4)); P = [ctypes.byref(v) for v in (l, r_, b, t)]
|
| 15 |
+
ch = []
|
| 16 |
+
for i in range(n):
|
| 17 |
+
c = chr(R.FPDFText_GetUnicode(raw, i)); g = bool(R.FPDFText_IsGenerated(raw, i))
|
| 18 |
+
box = (l.value, r_.value, b.value, t.value) if R.FPDFText_GetCharBox(raw, i, *P) else None
|
| 19 |
+
ch.append((c, g, box, R.FPDFText_GetFontSize(raw, i)))
|
| 20 |
+
tp.close()
|
| 21 |
+
out = []
|
| 22 |
+
for i, (c, g, box, fs) in enumerate(ch):
|
| 23 |
+
if c == "\x02": c = "-"
|
| 24 |
+
if c == " " and g:
|
| 25 |
+
prev = [(bx, f) for cc, _, bx, f in ch[max(0, i - 3):i] if bx and not cc.isspace()]
|
| 26 |
+
nxt = []
|
| 27 |
+
for cc, _, bx, _f in ch[i + 1:i + 5]:
|
| 28 |
+
if cc.isspace() or cc in "\r\n": break
|
| 29 |
+
if bx: nxt.append(bx)
|
| 30 |
+
if prev and nxt:
|
| 31 |
+
size = max(prev[-1][1], 1e-6)
|
| 32 |
+
pb, nb = max(bx[2] for bx, _ in prev), max(bx[2] for bx in nxt); pt, nt = min(bx[3] for bx, _ in prev), min(bx[3] for bx in nxt)
|
| 33 |
+
same_line = min(pt, nt) - max(pb, nb) > 0 # vertical overlap; across a line break the gap below is meaningless
|
| 34 |
+
gap = min(bx[0] for bx in nxt) - max(bx[1] for bx, _ in prev)
|
| 35 |
+
if same_line and gap < min_gap * size: continue # no visible gap: not a word break
|
| 36 |
+
out.append(c)
|
| 37 |
+
text = "".join(out).replace("\r\n", "\n").replace("\r", "\n")
|
| 38 |
+
return "\n".join(" ".join(line.split()) for line in text.split("\n") if line.strip())
|
v0.1.1/reading_order.py
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Reading order for line boxes [x0, y0, x1, y1]. No learned parameters.
|
| 2 |
+
rows: group into rows by vertical overlap, top to bottom, left to right (fails on multi-column pages: it interleaves the columns).
|
| 3 |
+
xycut: recursive XY-cut. At each region, split first at empty vertical strips (column gutters), reading columns left to right;
|
| 4 |
+
if there are none, split at empty horizontal strips (so a full-width heading is cut off above the columns); if neither exists, fall back to rows.
|
| 5 |
+
Tiny boxes (noise, stray marks) are left out when finding gaps so they cannot block a gutter, and are assigned by their centre."""
|
| 6 |
+
import numpy as np
|
| 7 |
+
|
| 8 |
+
def rows(bs):
|
| 9 |
+
bs = sorted(bs, key=lambda b: (b[1] + b[3]) / 2); R = []
|
| 10 |
+
for b in bs:
|
| 11 |
+
cy, h = (b[1] + b[3]) / 2, b[3] - b[1]
|
| 12 |
+
if R and abs(cy - R[-1][0]) < .5 * min(h, R[-1][1]): R[-1][2].append(b)
|
| 13 |
+
else: R.append([cy, h, [b]])
|
| 14 |
+
return [b for r in R for b in sorted(r[2], key=lambda b: b[0])]
|
| 15 |
+
|
| 16 |
+
def _gaps(iv, lo, hi, min_gap):
|
| 17 |
+
"""Empty stretches inside [lo, hi] not covered by any interval, at least min_gap long; returns cut positions (gap centres)."""
|
| 18 |
+
iv = sorted(iv); cuts = []; end = lo
|
| 19 |
+
for a, b in iv:
|
| 20 |
+
if a - end >= min_gap and end > lo: cuts.append((end + a) / 2)
|
| 21 |
+
end = max(end, b)
|
| 22 |
+
return cuts
|
| 23 |
+
|
| 24 |
+
def _split(bs, cuts, axis):
|
| 25 |
+
parts = [[] for _ in range(len(cuts) + 1)]
|
| 26 |
+
for b in bs:
|
| 27 |
+
c = (b[axis] + b[axis + 2]) / 2; parts[int(np.searchsorted(cuts, c))].append(b)
|
| 28 |
+
return [p for p in parts if p]
|
| 29 |
+
|
| 30 |
+
def _table(ps, mh):
|
| 31 |
+
"""Columns that are really a table or form: 2+ parts with 2+ lines each, whose lines pair up across neighbouring parts (centres within 0.3 line
|
| 32 |
+
heights), and rows are loosely spaced (median gap between consecutive lines >= 0.5 line heights), unlike running text in columns."""
|
| 33 |
+
ps = [p for p in ps if len(p) >= 2] # a single line beside a table (a centred heading) neither makes nor breaks it
|
| 34 |
+
if len(ps) < 2: return False
|
| 35 |
+
cy = [sorted((b[1] + b[3]) / 2 for b in p) for p in ps]
|
| 36 |
+
for a, b in zip(cy, cy[1:]):
|
| 37 |
+
small, big = (a, b) if len(a) <= len(b) else (b, a)
|
| 38 |
+
if sum(any(abs(y - z) < .3 * mh for z in big) for y in small) < .8 * len(small): return False
|
| 39 |
+
gaps = [d - mh for p in ps for d in np.diff(sorted(q[1] for q in p))] # line pitch minus line height = white space between rows
|
| 40 |
+
return float(np.median(gaps)) >= .5 * mh
|
| 41 |
+
|
| 42 |
+
def xycut(bs, depth=0, tables=False):
|
| 43 |
+
if len(bs) <= 1 or depth > 30: return list(bs)
|
| 44 |
+
hs = np.array([b[3] - b[1] for b in bs]); mh = float(np.median(hs))
|
| 45 |
+
big = [b for b in bs if (b[3] - b[1]) >= .4 * mh and (b[2] - b[0]) >= .6 * mh] or list(bs)
|
| 46 |
+
x0, x1 = min(b[0] for b in big), max(b[2] for b in big); y0, y1 = min(b[1] for b in big), max(b[3] for b in big)
|
| 47 |
+
vc = _gaps([(b[0], b[2]) for b in big], x0, x1, .3 * mh)
|
| 48 |
+
if vc:
|
| 49 |
+
ps = _split(bs, vc, 0)
|
| 50 |
+
if tables and _table(ps, mh): return rows(bs)
|
| 51 |
+
if len(ps) > 1: return [b for p in ps for b in xycut(p, depth + 1, tables)]
|
| 52 |
+
hc = _gaps([(b[1], b[3]) for b in big], y0, y1, 1e-6)
|
| 53 |
+
if hc:
|
| 54 |
+
ps = _split(bs, hc, 1)
|
| 55 |
+
if len(ps) > 1:
|
| 56 |
+
# Column lines often line up, so horizontal cuts can slice a two-column block into rows. Merge consecutive slices back together
|
| 57 |
+
# while the merged block still has a column gutter, so the columns are then read one after the other.
|
| 58 |
+
M = [ps[0]]
|
| 59 |
+
for p in ps[1:]:
|
| 60 |
+
if _vgap(M[-1] + p, mh): M[-1] = M[-1] + p
|
| 61 |
+
else: M.append(p)
|
| 62 |
+
return [b for p in (M if len(M) > 1 else ps) for b in xycut(p, depth + 1, tables)]
|
| 63 |
+
return rows(bs)
|
| 64 |
+
|
| 65 |
+
def _vgap(bs, mh):
|
| 66 |
+
big = [b for b in bs if (b[3] - b[1]) >= .4 * mh and (b[2] - b[0]) >= .6 * mh] or list(bs)
|
| 67 |
+
if len({round((b[1] + b[3]) / 2 / max(mh, 1)) for b in big}) < 2: return False # one row of boxes is not a column block
|
| 68 |
+
return bool(_gaps([(b[0], b[2]) for b in big], min(b[0] for b in big), max(b[2] for b in big), .3 * mh))
|
| 69 |
+
|
| 70 |
+
def xycut_shear(bs, max_deg=3.0, step=.25, tables=False):
|
| 71 |
+
"""XY-cut on a slightly rotated page: shear box x-positions by -tan(angle) * y-centre, pick the angle (within +-max_deg) that opens
|
| 72 |
+
the widest column gutter, order the sheared boxes, and return the original boxes in that order. Angle 0 wins ties."""
|
| 73 |
+
if len(bs) < 4: return xycut(bs, tables=tables)
|
| 74 |
+
hs = np.array([b[3] - b[1] for b in bs]); mh = float(np.median(hs))
|
| 75 |
+
def widest(t):
|
| 76 |
+
iv = sorted((b[0] - t * (b[1] + b[3]) / 2, b[2] - t * (b[1] + b[3]) / 2) for b in bs if (b[3] - b[1]) >= .4 * mh); end = None; g = 0.0
|
| 77 |
+
for a, b in iv:
|
| 78 |
+
if end is not None: g = max(g, a - end)
|
| 79 |
+
end = b if end is None else max(end, b)
|
| 80 |
+
return g
|
| 81 |
+
best = max((widest(np.tan(np.radians(d))) - 1e-3 * abs(d), d) for d in np.arange(-max_deg, max_deg + 1e-9, step))[1]
|
| 82 |
+
if best == 0: return xycut(bs, tables=tables)
|
| 83 |
+
t = np.tan(np.radians(best)); sh = [[b[0] - t * (b[1] + b[3]) / 2, b[1], b[2] - t * (b[1] + b[3]) / 2, b[3], i] for i, b in enumerate(bs)]
|
| 84 |
+
return [bs[int(b[4])] for b in xycut(sh, tables=tables)]
|
v0.1.1/requirements.txt
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
numpy
|
| 2 |
+
opencv-python-headless
|
| 3 |
+
onnxruntime
|
| 4 |
+
pypdfium2==4.30.0
|
| 5 |
+
regex
|
| 6 |
+
# optional, for PDFs with a text layer: poppler-utils (pdftotext) installed on the system
|
v0.1.1/third_party/indra_ocr/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.
|
v0.1.1/third_party/indra_ocr/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
"""Two modules from indra_ocr (Apache-2.0, see LICENSE): PDF text-layer reading and Indic syllable checks. Code only; no Indra model weights."""
|
v0.1.1/third_party/indra_ocr/textlayer.py
ADDED
|
@@ -0,0 +1,253 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Text-layer runs from a PDF page (pdfium), and checks that decide whether to
|
| 2 |
+
trust them.
|
| 3 |
+
|
| 4 |
+
A digital PDF already holds its text. When the text layer is sound, reading it
|
| 5 |
+
is faster than OCR and has no recognition errors. The checks follow the rules
|
| 6 |
+
that select the recognizer's own training labels:
|
| 7 |
+
|
| 8 |
+
- invisible text (render mode 3) marks an OCR layer over a scan;
|
| 9 |
+
- replacement, private-use or control characters mark a broken font map;
|
| 10 |
+
- a text run with no ink under it marks hidden or misplaced text.
|
| 11 |
+
|
| 12 |
+
A run is pdfium's own text segment between the line breaks it generates.
|
| 13 |
+
Coordinates are PDF points in the frame that pypdfium2 renders (crop box and
|
| 14 |
+
page rotation applied), with a top-left origin.
|
| 15 |
+
"""
|
| 16 |
+
|
| 17 |
+
from __future__ import annotations
|
| 18 |
+
|
| 19 |
+
import math
|
| 20 |
+
import unicodedata
|
| 21 |
+
from dataclasses import dataclass, field
|
| 22 |
+
|
| 23 |
+
import numpy as np
|
| 24 |
+
|
| 25 |
+
MAX_INVISIBLE_FRAC = 0.05
|
| 26 |
+
MAX_BAD_CHAR_FRAC = 0.005
|
| 27 |
+
MAX_NO_INK_LINE_FRAC = 0.03
|
| 28 |
+
DARK = 160 # grey level below which a pixel counts as ink
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def bad_char_count(text: str) -> int:
|
| 32 |
+
n = 0
|
| 33 |
+
for c in text:
|
| 34 |
+
cat = unicodedata.category(c)
|
| 35 |
+
if c == "�" or cat in ("Co", "Cs", "Cn") or (cat == "Cc" and c != "\t"):
|
| 36 |
+
n += 1
|
| 37 |
+
return n
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
BROKEN_FONT_MAP = "broken font map" # TextLayer.reason: the layer's codes are not text
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
@dataclass
|
| 44 |
+
class TextLine:
|
| 45 |
+
"""One text-layer run: its box, text, and characters with boxes."""
|
| 46 |
+
|
| 47 |
+
bbox: tuple[float, float, float, float]
|
| 48 |
+
text: str
|
| 49 |
+
chars: list = field(default_factory=list) # (char, bbox) in PDF order
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
@dataclass
|
| 53 |
+
class TextLayer:
|
| 54 |
+
lines: list[TextLine] # runs in PDF content order
|
| 55 |
+
size: tuple[float, float] # page width, height in points (as rendered)
|
| 56 |
+
trusted: bool
|
| 57 |
+
reason: str = "" # why the layer is not trusted
|
| 58 |
+
stats: dict = field(default_factory=dict)
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def _device_affine(page) -> np.ndarray:
|
| 62 |
+
"""[2, 3] map from PDF page space to the rendered frame (points, top-left
|
| 63 |
+
origin), from pdfium's own FPDF_PageToDevice."""
|
| 64 |
+
import ctypes
|
| 65 |
+
|
| 66 |
+
import pypdfium2.raw as R
|
| 67 |
+
|
| 68 |
+
W, H = page.get_size()
|
| 69 |
+
S = 1000 # device units per point: keeps the integer output precise
|
| 70 |
+
|
| 71 |
+
def dev(x, y):
|
| 72 |
+
dx, dy = ctypes.c_int(), ctypes.c_int()
|
| 73 |
+
R.FPDF_PageToDevice(page.raw, 0, 0, round(W * S), round(H * S), 0, x, y, dx, dy)
|
| 74 |
+
return np.array([dx.value, dy.value], float) / S
|
| 75 |
+
|
| 76 |
+
o, ex, ey = dev(0.0, 0.0), dev(1.0, 0.0), dev(0.0, 1.0)
|
| 77 |
+
return np.stack([ex - o, ey - o, o], 1)
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def extract_runs(page) -> tuple[list[TextLine], dict]:
|
| 81 |
+
"""Upright text runs of a pypdfium2 page, in content order."""
|
| 82 |
+
import ctypes
|
| 83 |
+
|
| 84 |
+
import pypdfium2
|
| 85 |
+
import pypdfium2.raw as R
|
| 86 |
+
|
| 87 |
+
tp = page.get_textpage()
|
| 88 |
+
try:
|
| 89 |
+
n = tp.count_chars()
|
| 90 |
+
# A character is upright on the rendered page when its baseline, mapped
|
| 91 |
+
# through the page-to-render transform, runs left to right (any /Rotate,
|
| 92 |
+
# any mirroring).
|
| 93 |
+
L = _device_affine(page)[:, :2]
|
| 94 |
+
# The loop below runs once per character: raw pdfium calls with reused
|
| 95 |
+
# buffers, and the upright and font-map tests cached per angle and per
|
| 96 |
+
# character (a page has few distinct ones).
|
| 97 |
+
get_unicode, get_angle = R.FPDFText_GetUnicode, R.FPDFText_GetCharAngle
|
| 98 |
+
get_box, raw_tp = R.FPDFText_GetCharBox, tp.raw
|
| 99 |
+
bl, br, bb, bt = (ctypes.c_double() for _ in range(4))
|
| 100 |
+
pl, pr, pb, pt = (ctypes.byref(v) for v in (bl, br, bb, bt))
|
| 101 |
+
upright: dict = {}
|
| 102 |
+
bad: dict = {}
|
| 103 |
+
chars, raw, breaks = [], [], [] # breaks: run ends after these positions
|
| 104 |
+
n_chars = n_rot = n_bad = 0
|
| 105 |
+
for i in range(n):
|
| 106 |
+
c = chr(get_unicode(raw_tp, i))
|
| 107 |
+
if c in "\r\n":
|
| 108 |
+
breaks.append(len(chars))
|
| 109 |
+
continue
|
| 110 |
+
if c == "\x02": # pdfium's mark for a hyphen at a line break
|
| 111 |
+
c = "-"
|
| 112 |
+
if not c.isspace():
|
| 113 |
+
n_chars += 1
|
| 114 |
+
k = bad.get(c)
|
| 115 |
+
if k is None:
|
| 116 |
+
k = bad[c] = bad_char_count(c)
|
| 117 |
+
n_bad += k
|
| 118 |
+
a = get_angle(raw_tp, i)
|
| 119 |
+
up = upright.get(a)
|
| 120 |
+
if up is None:
|
| 121 |
+
d = L @ np.array([math.cos(a), math.sin(a)])
|
| 122 |
+
up = upright[a] = not (
|
| 123 |
+
d[0] <= 0 or abs(d[1]) > 1e-3 * max(abs(d[0]), 1e-9)
|
| 124 |
+
)
|
| 125 |
+
if not up:
|
| 126 |
+
n_rot += 1 # not upright on the rendered page
|
| 127 |
+
breaks.append(len(chars))
|
| 128 |
+
continue
|
| 129 |
+
chars.append(c)
|
| 130 |
+
if not get_box(raw_tp, i, pl, pr, pb, pt): # yes, l r b t
|
| 131 |
+
raise pypdfium2.PdfiumError("Failed to get charbox.")
|
| 132 |
+
raw.append((bl.value, bb.value, br.value, bt.value)) # l, b, r, t
|
| 133 |
+
finally:
|
| 134 |
+
tp.close()
|
| 135 |
+
stats = {"chars": n_chars, "rotated": n_rot, "bad": n_bad}
|
| 136 |
+
if not chars:
|
| 137 |
+
return [], stats
|
| 138 |
+
# Page space -> rendered frame, all characters at once.
|
| 139 |
+
A = _device_affine(page)
|
| 140 |
+
b = np.asarray(raw, float)
|
| 141 |
+
xs = b[:, [0, 2, 0, 2]]
|
| 142 |
+
ys = b[:, [1, 1, 3, 3]]
|
| 143 |
+
px = A[0, 0] * xs + A[0, 1] * ys + A[0, 2]
|
| 144 |
+
py = A[1, 0] * xs + A[1, 1] * ys + A[1, 2]
|
| 145 |
+
boxes = np.stack([px.min(1), py.min(1), px.max(1), py.max(1)], 1)
|
| 146 |
+
# Characters outside the rendered frame (beyond a crop box) are not on the
|
| 147 |
+
# page: they are dropped, not read.
|
| 148 |
+
W, H = page.get_size()
|
| 149 |
+
cx, cy = (boxes[:, 0] + boxes[:, 2]) / 2, (boxes[:, 1] + boxes[:, 3]) / 2
|
| 150 |
+
visible = (cx >= 0) & (cx <= W) & (cy >= 0) & (cy <= H)
|
| 151 |
+
stats["off_page"] = int((~visible).sum())
|
| 152 |
+
runs: list[TextLine] = []
|
| 153 |
+
cuts = sorted(set(breaks + [len(chars)]))
|
| 154 |
+
start = 0
|
| 155 |
+
for end in cuts:
|
| 156 |
+
seg = [(chars[i], tuple(boxes[i])) for i in range(start, end) if visible[i]]
|
| 157 |
+
start = end
|
| 158 |
+
ink = [bx for c, bx in seg if not c.isspace()]
|
| 159 |
+
if not ink:
|
| 160 |
+
continue
|
| 161 |
+
box = (
|
| 162 |
+
min(v[0] for v in ink),
|
| 163 |
+
min(v[1] for v in ink),
|
| 164 |
+
max(v[2] for v in ink),
|
| 165 |
+
max(v[3] for v in ink),
|
| 166 |
+
)
|
| 167 |
+
runs.append(TextLine(box, " ".join("".join(c for c, _ in seg).split()), seg))
|
| 168 |
+
return runs, stats
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
def invisible_text_frac(page) -> float:
|
| 172 |
+
"""Share of text objects drawn invisibly (an OCR layer) on a pypdfium2 page."""
|
| 173 |
+
import pypdfium2.raw as R
|
| 174 |
+
|
| 175 |
+
n = inv = 0
|
| 176 |
+
for obj in page.get_objects(max_depth=4):
|
| 177 |
+
if obj.type == R.FPDF_PAGEOBJ_TEXT:
|
| 178 |
+
n += 1
|
| 179 |
+
inv += (
|
| 180 |
+
R.FPDFTextObj_GetTextRenderMode(obj.raw)
|
| 181 |
+
== R.FPDF_TEXTRENDERMODE_INVISIBLE
|
| 182 |
+
)
|
| 183 |
+
return inv / n if n else 0.0
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
def no_ink_frac(gray: np.ndarray, runs: list[TextLine], scale: float) -> float:
|
| 187 |
+
"""Share of runs whose box holds no dark pixel in ``gray`` (``scale`` px/pt)."""
|
| 188 |
+
ink = gray < DARK
|
| 189 |
+
H, W = ink.shape
|
| 190 |
+
empty = 0
|
| 191 |
+
for ln in runs:
|
| 192 |
+
x0, y0, x1, y1 = ln.bbox
|
| 193 |
+
r = slice(max(0, int(y0 * scale)), min(H, int(y1 * scale) + 1))
|
| 194 |
+
c = slice(max(0, int(x0 * scale)), min(W, int(x1 * scale) + 1))
|
| 195 |
+
if not ink[r, c].any():
|
| 196 |
+
empty += 1
|
| 197 |
+
return empty / max(len(runs), 1)
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
def read_text_layer(page, gray: np.ndarray, scale: float) -> TextLayer:
|
| 201 |
+
"""Text-layer runs of a page and the verdict on them.
|
| 202 |
+
|
| 203 |
+
``page`` is the open pypdfium2 page, ``gray`` a render of it at ``scale``
|
| 204 |
+
pixels per point (a low resolution is enough for the ink check)."""
|
| 205 |
+
size = page.get_size()
|
| 206 |
+
inv = invisible_text_frac(page)
|
| 207 |
+
if inv > MAX_INVISIBLE_FRAC:
|
| 208 |
+
return TextLayer([], size, False, f"invisible text {inv:.0%} (OCR layer)")
|
| 209 |
+
runs, st = extract_runs(page)
|
| 210 |
+
if not runs:
|
| 211 |
+
return TextLayer([], size, False, "no text layer", st)
|
| 212 |
+
if st["bad"] > MAX_BAD_CHAR_FRAC * max(st["chars"], 1):
|
| 213 |
+
return TextLayer(runs, size, False, BROKEN_FONT_MAP, st)
|
| 214 |
+
empty = no_ink_frac(gray, runs, scale)
|
| 215 |
+
st["no_ink"] = round(empty, 4)
|
| 216 |
+
if empty > MAX_NO_INK_LINE_FRAC:
|
| 217 |
+
return TextLayer(runs, size, False, f"{empty:.0%} of text runs have no ink", st)
|
| 218 |
+
return TextLayer(runs, size, True, "", st)
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
def order_backtracks(boxes: np.ndarray) -> int:
|
| 222 |
+
"""Moves upward in content order that do not go to a column on the right.
|
| 223 |
+
|
| 224 |
+
Reading goes down a column, then up to the top of the next column on the
|
| 225 |
+
right. Any other upward move means the content order is not reading order."""
|
| 226 |
+
if len(boxes) < 3:
|
| 227 |
+
return 0
|
| 228 |
+
h = float(np.median(boxes[:, 3] - boxes[:, 1]))
|
| 229 |
+
bt = 0
|
| 230 |
+
for a, b in zip(boxes[:-1], boxes[1:]):
|
| 231 |
+
if b[1] < a[1] - 0.5 * h and b[0] < a[2] - h:
|
| 232 |
+
bt += 1
|
| 233 |
+
return bt
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
MIN_MODEL_AGREEMENT = 0.85
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
def pdf_order_coherent(
|
| 240 |
+
boxes: np.ndarray, pair_logits: np.ndarray | None = None
|
| 241 |
+
) -> bool:
|
| 242 |
+
"""Is the content order a reading order?
|
| 243 |
+
|
| 244 |
+
Few upward moves that are not column changes, and (when the order model's
|
| 245 |
+
pairwise logits are given, ``a[i, j] > 0``: i before j) the model agrees with
|
| 246 |
+
most consecutive pairs. The second check catches two columns written line by
|
| 247 |
+
line across the gutter, which has no upward move at all."""
|
| 248 |
+
if order_backtracks(boxes) > max(1, int(0.02 * len(boxes))):
|
| 249 |
+
return False
|
| 250 |
+
if pair_logits is None or len(boxes) < 3:
|
| 251 |
+
return True
|
| 252 |
+
i = np.arange(len(boxes) - 1)
|
| 253 |
+
return float((pair_logits[i, i + 1] > 0).mean()) >= MIN_MODEL_AGREEMENT
|
v0.1.1/third_party/indra_ocr/vocab.py
ADDED
|
@@ -0,0 +1,289 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Token vocabulary for the line recognizer.
|
| 2 |
+
|
| 3 |
+
Class 0 is the CTC blank. Class i + 1 is ``tokens[i]``. A token is one
|
| 4 |
+
character, or one LaTeX command (``\\frac``, ``\\alpha``) inside math. Labels
|
| 5 |
+
are NFC normalized before encoding. A training line with a token outside the
|
| 6 |
+
vocabulary is dropped (``encode`` returns None), never silently altered.
|
| 7 |
+
|
| 8 |
+
``Vocab.latin()`` is the first recognizer's character set. ``Vocab.multi()``
|
| 9 |
+
adds Cyrillic, full Greek, Devanagari, Bengali and LaTeX command tokens; math
|
| 10 |
+
is written ``$...$`` in labels.
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
from __future__ import annotations
|
| 14 |
+
|
| 15 |
+
import json
|
| 16 |
+
import re
|
| 17 |
+
import unicodedata
|
| 18 |
+
|
| 19 |
+
# Label canonicalization. Each rule maps characters or runs that the image
|
| 20 |
+
# cannot tell apart to one form, so neither training targets nor the eval
|
| 21 |
+
# punish a reading that is visually correct.
|
| 22 |
+
_CANON = str.maketrans(
|
| 23 |
+
{
|
| 24 |
+
# Romanian comma-below and Turkish/legacy cedilla look the same in most fonts.
|
| 25 |
+
"\u0218": "\u015e", # Ș -> Ş
|
| 26 |
+
"\u0219": "\u015f", # ș -> ş
|
| 27 |
+
"\u021a": "\u0162", # Ț -> Ţ
|
| 28 |
+
"\u021b": "\u0163", # ț -> ţ
|
| 29 |
+
# Bullet look-alikes (the font decides the drawn shape).
|
| 30 |
+
"\u25aa": "\u2022", # ▪
|
| 31 |
+
"\u25cf": "\u2022", # ●
|
| 32 |
+
"\u2219": "\u2022", # ∙
|
| 33 |
+
"\u2023": "\u2022", # ‣
|
| 34 |
+
"\u2043": "\u2022", # ⁃
|
| 35 |
+
}
|
| 36 |
+
)
|
| 37 |
+
# Runs of 4+ leader / rule characters: the count cannot be read from the image.
|
| 38 |
+
_RUNS = re.compile(r"([._\-=·*~])\1{3,}")
|
| 39 |
+
_DOUBLE_SINGLE = re.compile(r"''|``")
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def canonical(text: str) -> str:
|
| 43 |
+
text = unicodedata.normalize("NFC", text).translate(_CANON)
|
| 44 |
+
text = _DOUBLE_SINGLE.sub('"', text)
|
| 45 |
+
return _RUNS.sub(lambda m: m.group(1) * 3, text)
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def _range(a: int, b: int) -> list[str]:
|
| 49 |
+
return [chr(c) for c in range(a, b + 1)]
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def _printable(chars) -> list[str]:
|
| 53 |
+
out = []
|
| 54 |
+
for c in chars:
|
| 55 |
+
cat = unicodedata.category(c)
|
| 56 |
+
if cat.startswith(("C", "Z")) and c != " ":
|
| 57 |
+
continue # control, format, unassigned, private, separators other than space
|
| 58 |
+
if cat == "Mn":
|
| 59 |
+
continue # combining marks: labels are NFC, marks come precomposed
|
| 60 |
+
out.append(c)
|
| 61 |
+
return out
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def _script_chars(a: int, b: int) -> list[str]:
|
| 65 |
+
"""Assigned letters, marks and digits of a script block (combining marks kept:
|
| 66 |
+
Indic vowel signs and virama are separate codepoints even after NFC)."""
|
| 67 |
+
out = []
|
| 68 |
+
for c in _range(a, b):
|
| 69 |
+
cat = unicodedata.category(c)
|
| 70 |
+
if cat == "Cn" or cat.startswith(("C", "Z")):
|
| 71 |
+
continue
|
| 72 |
+
out.append(c)
|
| 73 |
+
return out
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
# LaTeX commands the recognizer emits as single tokens inside $...$.
|
| 77 |
+
LATEX_COMMANDS = (
|
| 78 |
+
"alpha beta gamma delta epsilon varepsilon zeta eta theta vartheta iota kappa lambda mu nu xi "
|
| 79 |
+
"pi varpi rho varrho sigma varsigma tau upsilon phi varphi chi psi omega "
|
| 80 |
+
"Gamma Delta Theta Lambda Xi Pi Sigma Upsilon Phi Psi Omega "
|
| 81 |
+
"frac dfrac tfrac sqrt sum prod int iint oint lim limsup liminf sup inf max min arg det "
|
| 82 |
+
"sin cos tan cot sec csc arcsin arccos arctan sinh cosh tanh log ln exp "
|
| 83 |
+
"left right big Big bigg Bigg langle rangle lfloor rfloor lceil rceil "
|
| 84 |
+
"cdot cdots ldots dots vdots ddots times div pm mp ast star circ bullet "
|
| 85 |
+
"leq geq neq le ge ne ll gg approx sim simeq cong equiv propto "
|
| 86 |
+
"in notin ni subset supset subseteq supseteq cup cap cap setminus emptyset varnothing "
|
| 87 |
+
"forall exists neg land lor wedge vee oplus otimes "
|
| 88 |
+
"to rightarrow leftarrow Rightarrow Leftarrow leftrightarrow Leftrightarrow mapsto "
|
| 89 |
+
"implies iff uparrow downarrow longrightarrow "
|
| 90 |
+
"infty partial nabla hbar ell prime perp parallel mid top angle "
|
| 91 |
+
"hat bar tilde vec dot ddot widehat widetilde overline underline "
|
| 92 |
+
"mathbb mathcal mathbf mathrm mathit mathsf mathfrak boldsymbol operatorname text "
|
| 93 |
+
"quad qquad "
|
| 94 |
+
).split()
|
| 95 |
+
LATEX_TOKENS = ["\\" + c for c in LATEX_COMMANDS] + [
|
| 96 |
+
"\\{",
|
| 97 |
+
"\\}",
|
| 98 |
+
"\\|",
|
| 99 |
+
"\\,",
|
| 100 |
+
"\\;",
|
| 101 |
+
"\\!",
|
| 102 |
+
"\\ ",
|
| 103 |
+
]
|
| 104 |
+
_TOKEN_RE = re.compile(r"\\[A-Za-z]+|\\[{}|,;! ]|.", re.S)
|
| 105 |
+
# $...$ is math only when it holds LaTeX, so prices ("$5 or $10") stay text.
|
| 106 |
+
_MATH_SPAN = re.compile(r"\$[^$]*[\\^_{][^$]*\$")
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def build_latin_chars() -> list[str]:
|
| 110 |
+
chars: list[str] = []
|
| 111 |
+
chars += _range(0x20, 0x7E) # ASCII printable, with space
|
| 112 |
+
chars += _range(
|
| 113 |
+
0x00A1, 0x00FF
|
| 114 |
+
) # Latin-1 Supplement (letters, ¢ £ ¥ § © ° ± µ ¹²³ ½ ¼ ¾ × ÷ ...)
|
| 115 |
+
chars += _range(0x0100, 0x017F) # Latin Extended-A
|
| 116 |
+
chars += _range(
|
| 117 |
+
0x0180, 0x024F
|
| 118 |
+
) # Latin Extended-B (Ș ș Ț ț, Vietnamese Ơ ơ Ư ư, pinyin)
|
| 119 |
+
chars += _range(
|
| 120 |
+
0x1E00, 0x1EFF
|
| 121 |
+
) # Latin Extended Additional (Vietnamese precomposed)
|
| 122 |
+
chars += _range(0x0391, 0x03A9) + _range(0x03B1, 0x03C9) # basic Greek
|
| 123 |
+
chars += list("‐‑‒–—―‖‘’‚‛“”„‟†‡•‣…‰′″‹›⁄※")
|
| 124 |
+
chars += list("⁰⁴⁵⁶⁷⁸⁹⁺⁻⁽⁾ⁿ₀₁₂₃₄₅₆₇₈₉")
|
| 125 |
+
chars += list("€₹₽₩₺₪₱₫₴₦₡₸")
|
| 126 |
+
chars += list("™℃℉№ℓ℮⅓⅔⅛")
|
| 127 |
+
chars += list("←↑→↓↔⇒⇔↵")
|
| 128 |
+
chars += list("−∓∗∘∙√∞∝∠∧∨∩∪∫≈≠≡≤≥⊂⊃⊆⊇⊕⊗⊥⋅∂∆∇∈∉∋∏∑∀∃∅")
|
| 129 |
+
chars += list("■□▪▫▲△▶►▼▽◀◄◆◇○◦●★☆✓✔✗✘❖➢➤")
|
| 130 |
+
seen, out = set(), []
|
| 131 |
+
for c in _printable(chars):
|
| 132 |
+
if c not in seen and c != "": # soft hyphen is invisible
|
| 133 |
+
seen.add(c)
|
| 134 |
+
out.append(c)
|
| 135 |
+
return out
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def build_multi_tokens() -> list[str]:
|
| 139 |
+
out = build_latin_chars()
|
| 140 |
+
seen = set(out)
|
| 141 |
+
extra = (
|
| 142 |
+
_script_chars(0x0370, 0x03FF) # Greek and Coptic (accented Greek)
|
| 143 |
+
+ _script_chars(0x0400, 0x045F) # Cyrillic (Russian, Ukrainian, Serbian, ...)
|
| 144 |
+
+ _script_chars(
|
| 145 |
+
0x0490, 0x04FF
|
| 146 |
+
) # Cyrillic extended letters (Kazakh, Uzbek, ...)
|
| 147 |
+
+ _script_chars(0x0900, 0x097F) # Devanagari (Hindi, Marathi, Nepali)
|
| 148 |
+
+ _script_chars(0x0980, 0x09FF) # Bengali
|
| 149 |
+
+ list("।॥₹")
|
| 150 |
+
+ LATEX_TOKENS
|
| 151 |
+
)
|
| 152 |
+
for t in extra:
|
| 153 |
+
if t not in seen:
|
| 154 |
+
seen.add(t)
|
| 155 |
+
out.append(t)
|
| 156 |
+
return out
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
class Vocab:
|
| 160 |
+
def __init__(self, chars: list[str]):
|
| 161 |
+
self.chars = list(chars) # tokens: characters, or LaTeX commands
|
| 162 |
+
self.index = {c: i + 1 for i, c in enumerate(self.chars)}
|
| 163 |
+
self.has_commands = any(len(c) > 1 for c in self.chars)
|
| 164 |
+
|
| 165 |
+
@classmethod
|
| 166 |
+
def latin(cls) -> "Vocab":
|
| 167 |
+
return cls(build_latin_chars())
|
| 168 |
+
|
| 169 |
+
@classmethod
|
| 170 |
+
def multi(cls) -> "Vocab":
|
| 171 |
+
return cls(build_multi_tokens())
|
| 172 |
+
|
| 173 |
+
@classmethod
|
| 174 |
+
def named(cls, name: str) -> "Vocab":
|
| 175 |
+
if name not in ("latin", "multi"):
|
| 176 |
+
raise ValueError(f"unknown vocab {name!r}")
|
| 177 |
+
return cls.multi() if name == "multi" else cls.latin()
|
| 178 |
+
|
| 179 |
+
def tokenize(self, text: str) -> list[str]:
|
| 180 |
+
"""Characters, with a LaTeX command as one token when the vocab has it.
|
| 181 |
+
|
| 182 |
+
Inside a $...$ math span spaces are dropped: they are not visible in
|
| 183 |
+
rendered math. ``decode`` puts back the one space LaTeX needs, between a
|
| 184 |
+
command and a following letter."""
|
| 185 |
+
if not self.has_commands:
|
| 186 |
+
return list(text)
|
| 187 |
+
out: list[str] = []
|
| 188 |
+
pos = 0
|
| 189 |
+
for m in list(_MATH_SPAN.finditer(text)) + [None]:
|
| 190 |
+
end = m.start() if m else len(text)
|
| 191 |
+
out += self._tokens(text[pos:end], math=False)
|
| 192 |
+
if m:
|
| 193 |
+
out += self._tokens(m.group(0), math=True)
|
| 194 |
+
pos = m.end()
|
| 195 |
+
return out
|
| 196 |
+
|
| 197 |
+
def _tokens(self, text: str, math: bool) -> list[str]:
|
| 198 |
+
out = []
|
| 199 |
+
for t in _TOKEN_RE.findall(text):
|
| 200 |
+
if math and t.isspace():
|
| 201 |
+
continue
|
| 202 |
+
out.extend([t] if t in self.index or len(t) == 1 else list(t))
|
| 203 |
+
return out
|
| 204 |
+
|
| 205 |
+
@property
|
| 206 |
+
def n_classes(self) -> int:
|
| 207 |
+
return len(self.chars) + 1 # + blank
|
| 208 |
+
|
| 209 |
+
def normalize(self, text: str) -> str:
|
| 210 |
+
return canonical(text)
|
| 211 |
+
|
| 212 |
+
def encode(self, text: str) -> list[int] | None:
|
| 213 |
+
text = self.normalize(text)
|
| 214 |
+
ids = [self.index.get(c) for c in self.tokenize(text)]
|
| 215 |
+
if not ids or any(i is None for i in ids):
|
| 216 |
+
return None
|
| 217 |
+
return ids
|
| 218 |
+
|
| 219 |
+
def oov(self, text: str) -> set[str]:
|
| 220 |
+
return {c for c in self.tokenize(self.normalize(text)) if c not in self.index}
|
| 221 |
+
|
| 222 |
+
def decode(self, ids: list[int]) -> str:
|
| 223 |
+
toks = [self.chars[i - 1] for i in ids if 0 < i <= len(self.chars)]
|
| 224 |
+
if not self.has_commands:
|
| 225 |
+
return "".join(toks)
|
| 226 |
+
out = []
|
| 227 |
+
for k, t in enumerate(toks):
|
| 228 |
+
out.append(t)
|
| 229 |
+
# "\\alpha" + "x" must not read back as "\\alphax"
|
| 230 |
+
nxt = toks[k + 1] if k + 1 < len(toks) else ""
|
| 231 |
+
if len(t) > 2 and t[0] == "\\" and t[1:].isalpha() and nxt[:1].isalpha():
|
| 232 |
+
out.append(" ")
|
| 233 |
+
return "".join(out)
|
| 234 |
+
|
| 235 |
+
def to_json(self) -> str:
|
| 236 |
+
return json.dumps({"blank": 0, "chars": self.chars}, ensure_ascii=False)
|
| 237 |
+
|
| 238 |
+
@classmethod
|
| 239 |
+
def from_json(cls, s: str) -> "Vocab":
|
| 240 |
+
d = json.loads(s)
|
| 241 |
+
if d.get("blank", 0) != 0:
|
| 242 |
+
raise ValueError("only blank=0 vocabularies are supported")
|
| 243 |
+
return cls(d["chars"])
|
| 244 |
+
|
| 245 |
+
|
| 246 |
+
# Indic syllable structure. A broken font mapping (common in Nepali and Hindi
|
| 247 |
+
# PDFs converted from legacy fonts) leaves vowel signs with no consonant before
|
| 248 |
+
# them ("िामथ", "का ा") or two vowel signs in a row ("णािी"); valid text never does.
|
| 249 |
+
_INDIC_BLOCKS = ((0x0900, 0x097F), (0x0980, 0x09FF))
|
| 250 |
+
_VIRAMA = {0x094D, 0x09CD}
|
| 251 |
+
_NUKTA = {0x093C, 0x09BC}
|
| 252 |
+
_MODIFIERS = {0x0900, 0x0901, 0x0902, 0x0903, 0x0981, 0x0982, 0x0983}
|
| 253 |
+
|
| 254 |
+
|
| 255 |
+
def _indic(c: str) -> bool:
|
| 256 |
+
o = ord(c)
|
| 257 |
+
return any(a <= o <= b for a, b in _INDIC_BLOCKS)
|
| 258 |
+
|
| 259 |
+
|
| 260 |
+
def indic_valid(text: str) -> bool:
|
| 261 |
+
"""False when a Devanagari or Bengali mark has no base to attach to."""
|
| 262 |
+
prev = ""
|
| 263 |
+
for c in text:
|
| 264 |
+
if _indic(c) and unicodedata.category(c) in ("Mn", "Mc"):
|
| 265 |
+
o = ord(c)
|
| 266 |
+
p_ok = bool(prev) and _indic(prev)
|
| 267 |
+
p_cat = unicodedata.category(prev) if prev else ""
|
| 268 |
+
if (
|
| 269 |
+
o in _MODIFIERS
|
| 270 |
+
): # anusvara, candrabindu, visarga: after a letter or a vowel sign
|
| 271 |
+
if not p_ok:
|
| 272 |
+
return False
|
| 273 |
+
elif o in _VIRAMA or o in _NUKTA: # after a consonant (or nukta)
|
| 274 |
+
if not (p_ok and (p_cat == "Lo" or ord(prev) in _NUKTA)):
|
| 275 |
+
return False
|
| 276 |
+
else: # vowel sign: after a consonant, nukta, or nothing else
|
| 277 |
+
if not (p_ok and (p_cat == "Lo" or ord(prev) in _NUKTA)):
|
| 278 |
+
return False
|
| 279 |
+
prev = c
|
| 280 |
+
return True
|
| 281 |
+
|
| 282 |
+
|
| 283 |
+
def indic_page_ok(texts: list[str], max_bad: float = 0.05) -> bool:
|
| 284 |
+
"""A page whose Indic lines break syllable structure more than ``max_bad`` of
|
| 285 |
+
the time has a broken font mapping; its other lines are suspect too."""
|
| 286 |
+
ind = [t for t in texts if any(_indic(c) for c in t)]
|
| 287 |
+
if not ind:
|
| 288 |
+
return True
|
| 289 |
+
return sum(not indic_valid(t) for t in ind) <= max_bad * len(ind)
|
v0.1.1/upright.py
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Page upright correction, run before line finding (on by default; ocr.py --no-upright turns it off).
|
| 2 |
+
1. Skew modulo 180 deg from the ink projection profile: text lines give the sharpest row profile when horizontal.
|
| 3 |
+
2. Upright vs upside down: read the widest lines both ways and keep the side the line reader is more confident on.
|
| 4 |
+
Any rotation (0-360 deg) becomes upright; the page is left as it is unless the reader is clearly more confident on a turned copy."""
|
| 5 |
+
import numpy as np, cv2
|
| 6 |
+
import decode as D
|
| 7 |
+
from lines import prep
|
| 8 |
+
|
| 9 |
+
def rotate(g, deg):
|
| 10 |
+
"""Rotate counter-clockwise by deg on an enlarged white canvas (nothing is cut off)."""
|
| 11 |
+
if deg % 360 == 0: return g
|
| 12 |
+
if deg % 90 == 0: return np.ascontiguousarray(np.rot90(g, int(deg // 90) % 4))
|
| 13 |
+
h, w = g.shape; M = cv2.getRotationMatrix2D((w / 2, h / 2), deg, 1.0); c, s = abs(M[0, 0]), abs(M[0, 1])
|
| 14 |
+
nw, nh = int(h * s + w * c), int(h * c + w * s); M[0, 2] += nw / 2 - w / 2; M[1, 2] += nh / 2 - h / 2
|
| 15 |
+
return cv2.warpAffine(g, M, (nw, nh), flags=cv2.INTER_LINEAR, borderValue=255)
|
| 16 |
+
|
| 17 |
+
def skew(g, **kw):
|
| 18 |
+
"""Angle in [-90, 90) to rotate the page counter-clockwise so its text lines are horizontal."""
|
| 19 |
+
return skew_ratio(g, **kw)[0]
|
| 20 |
+
|
| 21 |
+
def skew_ratio(g, max_side=900, pts=40000):
|
| 22 |
+
"""(angle, sharpness at that angle / sharpness at 0 deg). A large ratio means the text really runs at that angle."""
|
| 23 |
+
sc = min(1.0, max_side / max(g.shape)); s = cv2.resize(g, None, fx=sc, fy=sc, interpolation=cv2.INTER_AREA) if sc < 1 else g
|
| 24 |
+
_, b = cv2.threshold(s, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)
|
| 25 |
+
ys, xs = np.nonzero(b)
|
| 26 |
+
if len(xs) < 200: return 0.0, 1.0
|
| 27 |
+
rng = np.random.default_rng(0)
|
| 28 |
+
if len(xs) > pts: i = rng.choice(len(xs), pts, replace=False); xs, ys = xs[i], ys[i]
|
| 29 |
+
xs = xs + rng.uniform(-.5, .5, len(xs)); ys = ys + rng.uniform(-.5, .5, len(ys)) # sub-pixel jitter: no pixel-grid aliasing at 45 deg
|
| 30 |
+
xs -= xs.mean(); ys -= ys.mean(); bins = int(np.hypot(*s.shape)) + 2
|
| 31 |
+
def score(a): # cv2 ccw rotation by a (image y points down): new y = -x sin a + y cos a
|
| 32 |
+
r = np.radians(a); y = -xs * np.sin(r) + ys * np.cos(r); h = np.bincount((y - y.min()).astype(int), minlength=bins).astype(np.float64)
|
| 33 |
+
return float((np.diff(h) ** 2).sum())
|
| 34 |
+
a0 = max(np.arange(-90, 90, 1.0), key=score); a1 = max(np.arange(a0 - 1, a0 + 1.01, .1), key=score)
|
| 35 |
+
return float(((a1 + 90) % 180) - 90), score(a1) / max(1e-9, score(0.0))
|
| 36 |
+
|
| 37 |
+
def evidence(o, g, probe=8):
|
| 38 |
+
"""Reader confidence on the widest lines of g, the line shape (median row of densest ink, 0 = top of line, 1 = bottom)
|
| 39 |
+
and whether the text read is mostly Latin."""
|
| 40 |
+
bx = sorted(o.detect(g), key=lambda b: -(b[2] - b[0]))[:probe]; cs, hl, txt = [], [], ""
|
| 41 |
+
for b in bx:
|
| 42 |
+
k = o.crop(g, b); x = prep(k, o.H, o.norm)[None, None].astype(np.float32); lg = o.rec.run(None, {"x": x})[0][0]
|
| 43 |
+
lp = lg - lg.max(1, keepdims=True); lp = lp - np.log(np.exp(lp).sum(1, keepdims=True)); t, c = D.greedy(lp, o.chars); cs.append(c); txt += t
|
| 44 |
+
_, bw = cv2.threshold(k, 0, 1, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU); pr = bw.sum(1).astype(float)
|
| 45 |
+
if pr.sum() > 0 and len(pr) >= 8: hl.append(float(np.argmax(pr) / (len(pr) - 1)))
|
| 46 |
+
letters = [ch for ch in txt if ch.isalpha()]; latin = sum(ch.isascii() for ch in letters) > .5 * max(1, len(letters))
|
| 47 |
+
return float(np.mean(cs)) if cs else 0.0, float(np.median(hl)) if hl else .5, latin
|
| 48 |
+
|
| 49 |
+
def fix(o, g, min_deg=1.5, trust_deg=30, side_ratio=2.0, margin=.02, flip_margin=.15):
|
| 50 |
+
"""Returns (page, applied ccw rotation in degrees, -180..180). A tilt of min_deg to trust_deg is levelled (smaller tilts are handled by the
|
| 51 |
+
per-line straightening, and resampling a small crop costs more than it gains); a larger one only if the line pattern is clearly sharper
|
| 52 |
+
there than at 0 deg (ratio over side_ratio) or the reader is clearly more confident. The levelled page is turned 180 deg only when two signals agree: the reader is
|
| 53 |
+
at least flip_margin more confident, and the line shape says so (Devanagari headline at the top of each line; Latin the reverse).
|
| 54 |
+
Thresholds were set on dev sets only."""
|
| 55 |
+
a, ratio = skew_ratio(g); best, deg = g, 0.0; c, h, _ = evidence(o, g)
|
| 56 |
+
if abs(a) >= min_deg:
|
| 57 |
+
lv = rotate(g, a); c2, h2, _ = evidence(o, lv)
|
| 58 |
+
if abs(a) <= trust_deg or ratio > side_ratio or c2 > c + margin: best, deg, c, h = lv, round(a, 1), c2, h2
|
| 59 |
+
# A moderate tilt is measured reliably. A larger one (sideways) must be clearly sharper than 0 deg, or convince the reader: tables
|
| 60 |
+
# and column rules can look like sideways text. The reader alone is not a fair judge of tilted or sideways pages: the line finder
|
| 61 |
+
# then returns short line pieces that read confidently.
|
| 62 |
+
fl = rotate(best, 180); c3, h3, lat = evidence(o, fl)
|
| 63 |
+
if c3 > c + flip_margin and ((h3 > h) if lat else (h3 < h)): return fl, round(((deg + 360) % 360) - 180, 1)
|
| 64 |
+
return best, deg
|
v0.1.1/upright_checks.json
ADDED
|
@@ -0,0 +1,170 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"A_test_print_sarvam_nepali": {
|
| 3 |
+
"mode": "print",
|
| 4 |
+
"n": 437,
|
| 5 |
+
"cer_off": 4.58,
|
| 6 |
+
"cer_on": 4.58,
|
| 7 |
+
"diff_ci": [
|
| 8 |
+
0.0,
|
| 9 |
+
0.0
|
| 10 |
+
],
|
| 11 |
+
"worse": 0,
|
| 12 |
+
"better": 0,
|
| 13 |
+
"ms_off": 57,
|
| 14 |
+
"ms_on": 98
|
| 15 |
+
},
|
| 16 |
+
"A_test_print_sarvam_english": {
|
| 17 |
+
"mode": "print",
|
| 18 |
+
"n": 299,
|
| 19 |
+
"cer_off": 6.73,
|
| 20 |
+
"cer_on": 6.73,
|
| 21 |
+
"diff_ci": [
|
| 22 |
+
-0.004,
|
| 23 |
+
0.004
|
| 24 |
+
],
|
| 25 |
+
"worse": 1,
|
| 26 |
+
"better": 1,
|
| 27 |
+
"ms_off": 68,
|
| 28 |
+
"ms_on": 112
|
| 29 |
+
},
|
| 30 |
+
"A_test_print_sarvam_hindi": {
|
| 31 |
+
"mode": "print",
|
| 32 |
+
"n": 228,
|
| 33 |
+
"cer_off": 20.85,
|
| 34 |
+
"cer_on": 20.97,
|
| 35 |
+
"diff_ci": [
|
| 36 |
+
-1.007,
|
| 37 |
+
1.518
|
| 38 |
+
],
|
| 39 |
+
"worse": 6,
|
| 40 |
+
"better": 7,
|
| 41 |
+
"ms_off": 208,
|
| 42 |
+
"ms_on": 310
|
| 43 |
+
},
|
| 44 |
+
"A_test_print_govpages": {
|
| 45 |
+
"mode": "print",
|
| 46 |
+
"n": 118,
|
| 47 |
+
"cer_off": 4.75,
|
| 48 |
+
"cer_on": 4.77,
|
| 49 |
+
"diff_ci": [
|
| 50 |
+
0.0,
|
| 51 |
+
0.069
|
| 52 |
+
],
|
| 53 |
+
"worse": 1,
|
| 54 |
+
"better": 0,
|
| 55 |
+
"ms_off": 322,
|
| 56 |
+
"ms_on": 678
|
| 57 |
+
},
|
| 58 |
+
"A_dev_hw_photo_d2": {
|
| 59 |
+
"mode": "handwriting",
|
| 60 |
+
"n": 308,
|
| 61 |
+
"cer_off": 44.9,
|
| 62 |
+
"cer_on": 44.06,
|
| 63 |
+
"diff_ci": [
|
| 64 |
+
-1.937,
|
| 65 |
+
0.122
|
| 66 |
+
],
|
| 67 |
+
"worse": 13,
|
| 68 |
+
"better": 15,
|
| 69 |
+
"ms_off": 13,
|
| 70 |
+
"ms_on": 26
|
| 71 |
+
},
|
| 72 |
+
"A_dev_hw1_lines_photo": {
|
| 73 |
+
"mode": "handwriting",
|
| 74 |
+
"n": 600,
|
| 75 |
+
"cer_off": 18.28,
|
| 76 |
+
"cer_on": 18.29,
|
| 77 |
+
"diff_ci": [
|
| 78 |
+
-0.091,
|
| 79 |
+
0.109
|
| 80 |
+
],
|
| 81 |
+
"worse": 3,
|
| 82 |
+
"better": 4,
|
| 83 |
+
"ms_off": 13,
|
| 84 |
+
"ms_on": 28
|
| 85 |
+
},
|
| 86 |
+
"B_test_print_sarvam_nepali_7": {
|
| 87 |
+
"mode": "print",
|
| 88 |
+
"n": 150,
|
| 89 |
+
"deg": 7,
|
| 90 |
+
"cer_off": 51.72,
|
| 91 |
+
"cer_on": 6.62
|
| 92 |
+
},
|
| 93 |
+
"B_test_print_sarvam_nepali_90": {
|
| 94 |
+
"mode": "print",
|
| 95 |
+
"n": 150,
|
| 96 |
+
"deg": 90,
|
| 97 |
+
"cer_off": 79.79,
|
| 98 |
+
"cer_on": 6.17
|
| 99 |
+
},
|
| 100 |
+
"B_test_print_sarvam_nepali_180": {
|
| 101 |
+
"mode": "print",
|
| 102 |
+
"n": 150,
|
| 103 |
+
"deg": 180,
|
| 104 |
+
"cer_off": 86.91,
|
| 105 |
+
"cer_on": 6.53
|
| 106 |
+
},
|
| 107 |
+
"B_test_print_sarvam_nepali_270": {
|
| 108 |
+
"mode": "print",
|
| 109 |
+
"n": 150,
|
| 110 |
+
"deg": 270,
|
| 111 |
+
"cer_off": 83.86,
|
| 112 |
+
"cer_on": 6.22
|
| 113 |
+
},
|
| 114 |
+
"B_test_print_govpages_7": {
|
| 115 |
+
"mode": "print",
|
| 116 |
+
"n": 118,
|
| 117 |
+
"deg": 7,
|
| 118 |
+
"cer_off": 40.33,
|
| 119 |
+
"cer_on": 5.9
|
| 120 |
+
},
|
| 121 |
+
"B_test_print_govpages_90": {
|
| 122 |
+
"mode": "print",
|
| 123 |
+
"n": 118,
|
| 124 |
+
"deg": 90,
|
| 125 |
+
"cer_off": 82.36,
|
| 126 |
+
"cer_on": 5.88
|
| 127 |
+
},
|
| 128 |
+
"B_test_print_govpages_180": {
|
| 129 |
+
"mode": "print",
|
| 130 |
+
"n": 118,
|
| 131 |
+
"deg": 180,
|
| 132 |
+
"cer_off": 82.98,
|
| 133 |
+
"cer_on": 4.9
|
| 134 |
+
},
|
| 135 |
+
"B_test_print_govpages_270": {
|
| 136 |
+
"mode": "print",
|
| 137 |
+
"n": 118,
|
| 138 |
+
"deg": 270,
|
| 139 |
+
"cer_off": 83.06,
|
| 140 |
+
"cer_on": 6.02
|
| 141 |
+
},
|
| 142 |
+
"B_dev_hw_photo_d2_7": {
|
| 143 |
+
"mode": "handwriting",
|
| 144 |
+
"n": 308,
|
| 145 |
+
"deg": 7,
|
| 146 |
+
"cer_off": 37.37,
|
| 147 |
+
"cer_on": 30.59
|
| 148 |
+
},
|
| 149 |
+
"B_dev_hw_photo_d2_90": {
|
| 150 |
+
"mode": "handwriting",
|
| 151 |
+
"n": 308,
|
| 152 |
+
"deg": 90,
|
| 153 |
+
"cer_off": 100.0,
|
| 154 |
+
"cer_on": 43.52
|
| 155 |
+
},
|
| 156 |
+
"B_dev_hw_photo_d2_180": {
|
| 157 |
+
"mode": "handwriting",
|
| 158 |
+
"n": 308,
|
| 159 |
+
"deg": 180,
|
| 160 |
+
"cer_off": 95.93,
|
| 161 |
+
"cer_on": 51.38
|
| 162 |
+
},
|
| 163 |
+
"B_dev_hw_photo_d2_270": {
|
| 164 |
+
"mode": "handwriting",
|
| 165 |
+
"n": 308,
|
| 166 |
+
"deg": 270,
|
| 167 |
+
"cer_off": 100.0,
|
| 168 |
+
"cer_on": 45.81
|
| 169 |
+
}
|
| 170 |
+
}
|