trueglyph 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
trueglyph/__init__.py ADDED
@@ -0,0 +1,8 @@
1
+ """TrueGlyph: tells AI agents when text extracted from a PDF cannot be trusted - in every script - and fixes it."""
2
+ __version__ = "0.1.0"
3
+
4
+ from .assess import assess # noqa: E402
5
+ from .guard import Reader, read # noqa: E402
6
+ from .repair import repair # noqa: E402
7
+
8
+ __all__ = ["read", "Reader", "assess", "repair", "__version__"]
trueglyph/assess.py ADDED
@@ -0,0 +1,177 @@
1
+ """Turn signals into issues, a trust level and a ranking score.
2
+
3
+ Trust levels (what an AI agent should do with the text):
4
+ high no damage signal fired; use it.
5
+ medium moderate signals (e.g. a few split words); usable, but quotes and exact matches may be off.
6
+ low severe damage (lost glyphs, wrong order, garbled script); do not quote or index without repair/OCR.
7
+ none the page shows content but has no usable text layer; OCR is required.
8
+ """
9
+ from dataclasses import dataclass, field
10
+
11
+ from .engines import PageInfo
12
+ from .signals import CLEAN_COVERAGE, T, Signals, measure
13
+ from . import lexicon
14
+ from .scripts import SCRIPTS
15
+
16
+ LEVELS = ["none", "low", "medium", "high"]
17
+
18
+
19
+ @dataclass
20
+ class Issue:
21
+ code: str
22
+ severity: str # "severe" | "moderate"
23
+ value: float
24
+ message: str
25
+ repairable: bool = True # False when the original characters are lost (repair cannot restore them)
26
+
27
+
28
+ @dataclass
29
+ class Assessment:
30
+ trust: str
31
+ score: float
32
+ script: str
33
+ lang: str | None
34
+ letters: int
35
+ issues: list = field(default_factory=list)
36
+ metrics: dict = field(default_factory=dict)
37
+ checks: str = "structural" # "structural+lexicon" when a word list was available
38
+
39
+
40
+ def issues_from(s: Signals) -> list[Issue]:
41
+ m, out = s.metrics, []
42
+
43
+ def add(code, cond, sev, value, msg, repairable=True):
44
+ if cond:
45
+ out.append(Issue(code, sev, round(value, 4), msg, repairable))
46
+
47
+ add("lost_glyphs", m.get("junk_per_k", 0) >= T.junk, "severe", m.get("junk_per_k", 0),
48
+ "Glyphs the extractor could not map (NUL/U+FFFD/private-use): characters are missing.", repairable=False)
49
+ add("symbol_garble", m.get("symbol_share", 0) >= 0.3 and m.get("symbols", 0) >= 20, "severe",
50
+ m.get("symbol_share", 0), "Symbols (dingbats, private-use codes) where letters should be: broken font.",
51
+ repairable=False)
52
+ add("presentation_forms", m.get("presentation_share", 0) >= T.presentation, "severe",
53
+ m.get("presentation_share", 0), "Arabic/Hebrew glyph codes instead of letters: search and quotes fail.")
54
+ add("orphan_marks", m.get("orphan_mark_share", 0) >= T.orphan_marks,
55
+ "severe" if m.get("orphan_mark_share", 0) >= 3 * T.orphan_marks else "moderate",
56
+ m.get("orphan_mark_share", 0), "Vowel signs or marks separated from their letters (words split).")
57
+ add("doubled_vowel_signs", m.get("doubled_sign_per_k", 0) >= T.doubled_signs,
58
+ "severe" if m.get("doubled_sign_per_k", 0) >= 5 * T.doubled_signs else "moderate",
59
+ m.get("doubled_sign_per_k", 0), "The same vowel sign repeated: words are misspelled.")
60
+ add("vowel_clash", m.get("vowel_clash_per_k", 0) >= T.vowel_clash, "severe", m.get("vowel_clash_per_k", 0),
61
+ "Two vowel signs on one consonant: glyphs were misread.", repairable=False)
62
+ add("impossible_clusters", m.get("cluster_errors_per_k", 0) >= T.cluster_errors, "severe",
63
+ m.get("cluster_errors_per_k", 0), "Vowels or tone marks without their consonant: not valid Thai/Lao "
64
+ "spelling (an extractor split marks from their letters, or an OCR model read another script).",
65
+ repairable=m.get("orphan_mark_share", 0) >= T.orphan_marks)
66
+ add("visual_order_vowels", m.get("prebase_misorder_per_k", 0) >= T.prebase_misorder, "severe",
67
+ m.get("prebase_misorder_per_k", 0), "Vowel signs in drawing order instead of reading order.")
68
+ add("mixed_script_garble", m.get("mixed_script_token_share", 0) >= T.mixed_script, "severe",
69
+ m.get("mixed_script_token_share", 0), "Latin letters inside non-Latin words: broken font mapping.",
70
+ repairable=False)
71
+ add("cjk_fragmented", m.get("cjk_short_line_share", 0) >= T.cjk_short_lines or
72
+ m.get("cjk_spaced_per_k", 0) >= T.cjk_spaced, "severe",
73
+ max(m.get("cjk_short_line_share", 0), m.get("cjk_spaced_per_k", 0) / 1000),
74
+ "CJK text split one character per line or by spaces (typical of vertical text).")
75
+ add("wrap_breaks", m.get("wrap_breaks_per_k", 0) >= T.wrap_breaks,
76
+ "severe" if m.get("wrap_breaks_per_k", 0) >= 25 * T.wrap_breaks else "moderate",
77
+ m.get("wrap_breaks_per_k", 0), "Line breaks inside words (script written without spaces).")
78
+ add("split_words", m.get("split_word_rate", 0) >= T.split_words,
79
+ "severe" if m.get("split_word_rate", 0) >= 3 * T.split_words else "moderate",
80
+ m.get("split_word_rate", 0), "Words split into fragments that only make sense when joined.")
81
+ gain = m.get("lexicon_validity_reversed", 0) - m.get("lexicon_validity", 0)
82
+ add("reversed_rtl", "lexicon_validity_reversed" in m and gain >= T.rtl_reversed, "severe", gain,
83
+ "Right-to-left lines extracted in reverse (visual) order.")
84
+ add("cjk_lookalikes", m.get("cjk_compat_per_k", 0) >= T.ligatures,
85
+ "severe" if m.get("cjk_compat_per_k", 0) >= 20 else "moderate", m.get("cjk_compat_per_k", 0),
86
+ "Kangxi radicals or vertical forms instead of normal characters (⼈ for 人): search and matching fail.")
87
+ add("ligatures", m.get("ligatures_per_k", 0) >= T.ligatures, "moderate", m.get("ligatures_per_k", 0),
88
+ "Ligature characters (fi fl ff) instead of letters: searching for 'financial' misses 'financial'.")
89
+ add("hidden_chars", m.get("hidden_chars_per_k", 0) >= T.hidden_chars, "moderate",
90
+ m.get("hidden_chars_per_k", 0), "Invisible characters (soft hyphens, zero-width spaces) inside words.")
91
+ add("hyphen_breaks", m.get("hyphen_break_rate", 0) >= T.hyphen_breaks, "moderate",
92
+ m.get("hyphen_break_rate", 0), "Words still hyphenated across line breaks ('infor- mation').")
93
+ add("glued_words", m.get("glued_word_rate", 0) >= T.glued_words,
94
+ "severe" if m.get("glued_word_rate", 0) >= 10 * T.glued_words else "moderate",
95
+ m.get("glued_word_rate", 0), "Words run together without spaces ('Thequickbrownfox').")
96
+ add("letter_spaced", m.get("letter_spaced_rate", 0) >= T.letter_spaced, "moderate",
97
+ m.get("letter_spaced_rate", 0), "Letter-spaced words ('S U M M A R Y') that indexes cannot match.")
98
+ if "lexicon_validity" in m and s.lang and m.get("letters", 0) >= 200: # too noisy on a few words
99
+ rel = m["lexicon_validity"] / CLEAN_COVERAGE.get(s.lang, 0.9)
100
+ # Confident OCR in a script that also writes languages without a word list (Marathi and Nepali next to
101
+ # Hindi) may simply be another language: measured, Marathi OCR at confidence 94 scored 0.31-0.39 as Hindi.
102
+ script = SCRIPTS.get(s.profile.main)
103
+ other_lang = script and any(not lexicon.supported(l) for l in script.languages)
104
+ sure_ocr = m.get("ocr_confidence", 0) >= T.ocr_confidence[1]
105
+ add("few_known_words", rel < T.known_words[1],
106
+ "severe" if rel < T.known_words[0] and not (other_lang and sure_ocr) else "moderate", rel,
107
+ f"Far fewer real {s.lang} words than correct text has: garbled, the wrong OCR model, or a language "
108
+ "without a word list.", repairable=False)
109
+ if "ocr_confidence" in m:
110
+ c = m["ocr_confidence"]
111
+ add("ocr_low_confidence", c < T.ocr_confidence[1], "severe" if c < T.ocr_confidence[0] else "moderate",
112
+ c, f"OCR is unsure of what it read (mean word confidence {c:.0f}/100).", repairable=False)
113
+ return out
114
+
115
+
116
+ # Issues that mean the glyphs themselves were misread outlive any repair: no repair brings the real letters back, and
117
+ # repairs can hide the evidence (lost-glyph markers are deleted; reordering vowel signs made a Tamil layer's vowel
118
+ # clashes vanish and the garbage passed as 'high'). Measurements a repair can truly fix are judged again (a Hindi page
119
+ # whose doubled vowel signs were all repaired kept a stale 'few known words' and was rated medium).
120
+ CARRIED = {"lost_glyphs", "vowel_clash", "mixed_script_garble", "symbol_garble"}
121
+
122
+
123
+ def assess(text: str, page: PageInfo | None = None, lang: str | None = None, *, lasting: list | None = None,
124
+ ocr_confidence: float | None = None) -> Assessment:
125
+ """Assess one page of extracted text. `lasting`: the issues found before repair; those whose evidence the repair
126
+ deletes (lost-glyph markers) are carried over, everything else is judged again on the repaired text;
127
+ `ocr_confidence` is Tesseract's mean word confidence when the text came from OCR."""
128
+ s = measure(text, page, lang)
129
+ m = s.metrics
130
+ if ocr_confidence is not None:
131
+ m["ocr_confidence"] = round(ocr_confidence, 1)
132
+ issues = issues_from(s) + [i for i in (lasting or []) if i.code in CARRIED]
133
+ # dedupe by code, keep the worst
134
+ seen = {}
135
+ for i in issues:
136
+ if i.code not in seen or (i.severity == "severe" and seen[i.code].severity != "severe"):
137
+ seen[i.code] = i
138
+ issues = list(seen.values())
139
+ has_content = page is not None and (page.images > 0 or page.drawings > 20)
140
+ if s.profile.letters < 20 and has_content:
141
+ trust = "none"
142
+ issues.append(Issue("no_text_layer", "severe", s.profile.letters,
143
+ "The page shows content but has (almost) no text layer: OCR is required.", False))
144
+ elif page is None and not text.strip(): # bare text to check, and nothing in it (a page knows if it is blank)
145
+ trust = "none"
146
+ issues.append(Issue("no_text", "severe", 0, "There is no text to check.", False))
147
+ elif any(i.severity == "severe" for i in issues):
148
+ trust = "low"
149
+ elif issues:
150
+ trust = "medium"
151
+ else:
152
+ trust = "high"
153
+ return Assessment(trust, quality(m, issues), s.profile.main, s.lang, s.profile.letters, issues, m,
154
+ "structural+lexicon" if "lexicon_validity" in m else "structural")
155
+
156
+
157
+ def quality(m: dict, issues: list) -> float:
158
+ """A 0..1 number to rank alternative readings of the same page (higher is better). Not a probability."""
159
+ if m.get("letters", 0) < 20:
160
+ return 0.0
161
+ # Only word lists with frequencies rank readings: the bundled dictionaries also hold word fragments, so a reading
162
+ # full of split words scored higher than the intact one (Kannada: 0.565 vs 0.531 known, and no split detected).
163
+ # The bundled lists still drive detection (issues, trust).
164
+ ranked = lexicon.has_frequencies(m.get("lang_used"))
165
+ pen = (m.get("junk_per_k", 0) / 20 + m.get("presentation_share", 0) * 3 + m.get("orphan_mark_share", 0) * 6
166
+ + m.get("doubled_sign_per_k", 0) / 40 + m.get("vowel_clash_per_k", 0) / 20
167
+ + m.get("cluster_errors_per_k", 0) / 20
168
+ + m.get("prebase_misorder_per_k", 0) / 30 + m.get("mixed_script_token_share", 0) * 4
169
+ + m.get("cjk_short_line_share", 0) + m.get("cjk_spaced_per_k", 0) / 400
170
+ + m.get("wrap_breaks_per_k", 0) / 150 + (m.get("split_word_rate", 0) * 4 if ranked else 0)
171
+ + max(0.0, m.get("lexicon_validity_reversed", 0) - m.get("lexicon_validity", 0)) * 2)
172
+ q = max(0.0, 1.0 - pen)
173
+ if "lexicon_validity" in m and ranked:
174
+ q *= 0.5 + 0.5 * min(1.0, m["lexicon_validity"] / CLEAN_COVERAGE.get(m.get("lang_used", ""), 0.9))
175
+ if "ocr_confidence" in m:
176
+ q *= 0.5 + 0.5 * m["ocr_confidence"] / 100
177
+ return round(q, 4)
trueglyph/cli.py ADDED
@@ -0,0 +1,115 @@
1
+ """Command line: trueglyph read FILE.pdf | trueglyph check [FILE|-]"""
2
+ import argparse
3
+ import json
4
+ import sys
5
+
6
+ from . import __version__
7
+ from .assess import assess
8
+ from .guard import Reader
9
+ from .repair import repair
10
+
11
+ ICON = {"high": "OK ", "medium": "WARN", "low": "BAD ", "none": "NONE"}
12
+
13
+
14
+ def _pages(spec):
15
+ out = set()
16
+ try:
17
+ for part in spec.split(","):
18
+ a, _, b = part.partition("-")
19
+ first, last = int(a), int(b or a)
20
+ if first < 1 or last < first:
21
+ raise ValueError
22
+ out.update(range(first, last + 1))
23
+ except ValueError:
24
+ raise argparse.ArgumentTypeError(f"'{spec}' is not a page list like 1,3-5 (pages start at 1)") from None
25
+ return sorted(out)
26
+
27
+
28
+ def cmd_read(args):
29
+ log = (lambda m: print(" " + m, file=sys.stderr)) if args.verbose else None
30
+ result = Reader(ocr=not args.no_ocr, lang=args.lang, log=log).read(args.pdf, args.pages)
31
+ if args.json:
32
+ print(json.dumps(result.to_dict(include_text=not args.no_text), ensure_ascii=False, indent=1))
33
+ return
34
+ if args.text:
35
+ print(result.text)
36
+ return
37
+ print(f"{args.pdf}: document trust {result.trust.upper()} "
38
+ + " ".join(f"{k}={v}" for k, v in result.summary.items() if v))
39
+ for p in result.pages:
40
+ extra = f" repairs: {', '.join(f'{k}={v}' for k, v in p.repairs.items())}" if p.repairs else ""
41
+ print(f" page {p.page:3} {ICON[p.trust]} {p.trust:6} {p.script:10} via {p.engine}{extra}")
42
+ for i in p.issues:
43
+ print(f" - {i['severity']}: {i['message']}")
44
+
45
+
46
+ def cmd_check(args):
47
+ # read bytes and decode as UTF-8: on Windows sys.stdin would use the console code page
48
+ raw = sys.stdin.buffer.read() if args.file in (None, "-") else open(args.file, "rb").read()
49
+ text = raw.decode("utf-8-sig", errors="replace")
50
+ a = assess(text, lang=args.lang)
51
+ out = {"trust": a.trust, "script": a.script, "lang": a.lang, "checks": a.checks,
52
+ "issues": [vars(i) for i in a.issues]}
53
+ if args.repair:
54
+ r = repair(text, args.lang)
55
+ out["repairs"] = r.applied
56
+ out["repaired_trust"] = assess(r.text, lang=args.lang, lasting=a.issues).trust
57
+ out["text"] = r.text
58
+ print(json.dumps(out, ensure_ascii=False, indent=1))
59
+
60
+
61
+ def cmd_demo(args):
62
+ """Show the problem and the fix on a bundled 4-page PDF (Hindi, Urdu, Thai, vertical Japanese)."""
63
+ from importlib.resources import files
64
+ from .engines import PyMuPDF, PyPDF
65
+ pdf = str(files("trueglyph") / "data" / "demo.pdf")
66
+ plain_name, plain_engine = ("pypdf", PyPDF()) if PyPDF().available() else ("pymupdf", PyMuPDF())
67
+ plain = plain_engine.pages(pdf)
68
+ result = Reader(ocr=not args.no_ocr).read(pdf)
69
+ names = ["Hindi", "Urdu", "Thai", "Japanese (vertical)"]
70
+ short = lambda t: " ".join(t.split())[:72] or "(no text)"
71
+ print("The same declaration, four scripts. Left: what a common extractor returns. Right: TrueGlyph.\n")
72
+ for p, name in zip(result.pages, names):
73
+ before = assess(plain[p.page - 1]).trust
74
+ print(f"{name}")
75
+ print(f" {plain_name:8} [{ICON[before].strip():4}] {short(plain[p.page - 1]).replace(chr(0), chr(0x2400))}")
76
+ print(f" {'TrueGlyph':8} [{ICON[p.trust].strip():4}] {short(p.text)}")
77
+ fixes = ", ".join(k.replace("_", " ") for k in p.repairs) or ("switched to " + p.engine)
78
+ print(f" {'':8} fixed: {fixes}\n")
79
+ print("Try it on your own files: trueglyph read your.pdf | echo TEXT | trueglyph check --repair")
80
+
81
+
82
+ def main(argv=None):
83
+ ap = argparse.ArgumentParser(prog="trueglyph", description="Can this PDF text be trusted? Checks and repairs "
84
+ "extracted text in every script, and falls back to OCR.")
85
+ ap.add_argument("--version", action="version", version=__version__)
86
+ sub = ap.add_subparsers(dest="cmd", required=True)
87
+ r = sub.add_parser("read", help="read a PDF page by page with a trust level per page")
88
+ r.add_argument("pdf")
89
+ r.add_argument("--lang", help="ISO 639-1 language hint, e.g. hi, ta, th, ar, ja")
90
+ r.add_argument("--pages", type=_pages, help="e.g. 1,3-5")
91
+ r.add_argument("--no-ocr", action="store_true", help="never run OCR")
92
+ r.add_argument("--json", action="store_true", help="full machine-readable result")
93
+ r.add_argument("--no-text", action="store_true", help="with --json: omit page text")
94
+ r.add_argument("--text", action="store_true", help="print only the best text")
95
+ r.add_argument("-v", "--verbose", action="store_true", help="show every decision")
96
+ r.set_defaults(func=cmd_read)
97
+ c = sub.add_parser("check", help="assess text extracted by any tool (file or stdin)")
98
+ c.add_argument("file", nargs="?")
99
+ c.add_argument("--lang")
100
+ c.add_argument("--repair", action="store_true", help="also return repaired text")
101
+ c.set_defaults(func=cmd_check)
102
+ d = sub.add_parser("demo", help="see the problem and the fix on a bundled 4-script PDF (no files needed)")
103
+ d.add_argument("--no-ocr", action="store_true")
104
+ d.set_defaults(func=cmd_demo)
105
+ args = ap.parse_args(argv)
106
+ if hasattr(sys.stdout, "reconfigure"):
107
+ sys.stdout.reconfigure(encoding="utf-8")
108
+ try:
109
+ args.func(args)
110
+ except (FileNotFoundError, ValueError) as e: # bad input, explained by Reader; real bugs keep their traceback
111
+ sys.exit(f"trueglyph: error: {e}")
112
+
113
+
114
+ if __name__ == "__main__":
115
+ main()
Binary file
trueglyph/engines.py ADDED
@@ -0,0 +1,245 @@
1
+ """Text extraction engines, page by page. Every engine is optional: TrueGlyph uses whatever is installed."""
2
+ import os
3
+ import shutil
4
+ import subprocess
5
+ import tempfile
6
+ from dataclasses import dataclass
7
+ from pathlib import Path
8
+
9
+ ROOT = Path(__file__).resolve().parents[2]
10
+
11
+
12
+ @dataclass
13
+ class PageInfo:
14
+ images: int # raster images drawn on the page
15
+ drawings: int # vector paths (text converted to outlines shows up here)
16
+ width: float
17
+ height: float
18
+
19
+
20
+ def _quiet_pdfminer():
21
+ import logging
22
+ logging.getLogger("pdfminer").setLevel(logging.ERROR)
23
+
24
+
25
+ class Engine:
26
+ name = ""
27
+ is_ocr = False
28
+
29
+ def available(self) -> bool:
30
+ raise NotImplementedError
31
+
32
+ def pages(self, path: str) -> list[str]:
33
+ raise NotImplementedError
34
+
35
+ def page(self, path: str, index: int) -> str:
36
+ """One page (0-based). Engines that are slow on a whole document override this."""
37
+ return self.pages(path)[index]
38
+
39
+
40
+ class PyMuPDF(Engine):
41
+ name = "pymupdf"
42
+
43
+ def available(self):
44
+ try:
45
+ import pymupdf # noqa: F401
46
+ return True
47
+ except ImportError:
48
+ return False
49
+
50
+ def pages(self, path):
51
+ import pymupdf
52
+ with pymupdf.open(path) as doc:
53
+ return [p.get_text() for p in doc]
54
+
55
+ @staticmethod
56
+ def info(path) -> list[PageInfo]:
57
+ import pymupdf
58
+ out = []
59
+ with pymupdf.open(path) as doc:
60
+ for p in doc:
61
+ try:
62
+ drawings = len(p.get_drawings())
63
+ except Exception:
64
+ drawings = 0
65
+ out.append(PageInfo(len(p.get_images(full=True)), drawings, p.rect.width, p.rect.height))
66
+ return out
67
+
68
+
69
+ class PyPDF(Engine):
70
+ name = "pypdf"
71
+
72
+ def available(self):
73
+ try:
74
+ import pypdf # noqa: F401
75
+ return True
76
+ except ImportError:
77
+ return False
78
+
79
+ def pages(self, path):
80
+ import pypdf
81
+ return [p.extract_text() or "" for p in pypdf.PdfReader(path).pages]
82
+
83
+ def page(self, path, index):
84
+ import pypdf
85
+ return pypdf.PdfReader(path).pages[index].extract_text() or ""
86
+
87
+
88
+ class PDFMiner(Engine):
89
+ name = "pdfminer"
90
+
91
+ def available(self):
92
+ try:
93
+ import pdfminer # noqa: F401
94
+ return True
95
+ except ImportError:
96
+ return False
97
+
98
+ def pages(self, path):
99
+ _quiet_pdfminer()
100
+ from pdfminer.high_level import extract_pages
101
+ from pdfminer.layout import LTTextContainer
102
+ return ["".join(el.get_text() for el in page if isinstance(el, LTTextContainer))
103
+ for page in extract_pages(path)]
104
+
105
+ def page(self, path, index):
106
+ _quiet_pdfminer()
107
+ from pdfminer.high_level import extract_pages
108
+ from pdfminer.layout import LTTextContainer
109
+ return "".join(el.get_text() for page in extract_pages(path, page_numbers=[index])
110
+ for el in page if isinstance(el, LTTextContainer))
111
+
112
+
113
+ class DoclingParse(Engine):
114
+ name = "docling-parse"
115
+
116
+ def available(self):
117
+ try:
118
+ import docling_parse # noqa: F401
119
+ return True
120
+ except ImportError:
121
+ return False
122
+
123
+ def pages(self, path):
124
+ from docling_core.types.doc.page import TextCellUnit
125
+ from docling_parse.pdf_parser import DoclingPdfParser
126
+ doc = DoclingPdfParser(loglevel="fatal").load(path_or_stream=str(path))
127
+ return ["\n".join(c.text for c in page.iterate_cells(unit_type=TextCellUnit.LINE))
128
+ for _, page in doc.iterate_pages()]
129
+
130
+ def page(self, path, index):
131
+ from docling_core.types.doc.page import TextCellUnit
132
+ from docling_parse.pdf_parser import DoclingPdfParser
133
+ doc = DoclingPdfParser(loglevel="fatal").load(path_or_stream=str(path))
134
+ return "\n".join(c.text for c in doc.get_page(index + 1).iterate_cells(unit_type=TextCellUnit.LINE))
135
+
136
+
137
+ class Tesseract(Engine):
138
+ """OCR: renders a page and runs Tesseract with the script's own model. Used when the text layer is missing or
139
+ untrustworthy. Models are looked up in TRUEGLYPH_TESSDATA, ./.tessdata, the source checkout's .tessdata, then
140
+ Tesseract's own folder."""
141
+ name = "tesseract"
142
+ is_ocr = True
143
+ DPI = 300
144
+
145
+ def __init__(self):
146
+ self.exe = (os.environ.get("TRUEGLYPH_TESSERACT") or shutil.which("tesseract")
147
+ or next((p for p in [r"C:\Program Files\Tesseract-OCR\tesseract.exe",
148
+ "/usr/bin/tesseract", "/opt/homebrew/bin/tesseract"] if Path(p).exists()),
149
+ None))
150
+ # ./.tessdata in the working directory, or the source checkout's (ROOT is site-packages' parent when installed)
151
+ tessdata = os.environ.get("TRUEGLYPH_TESSDATA") or next(
152
+ (p for p in (Path.cwd() / ".tessdata", ROOT / ".tessdata") if p.exists()), None)
153
+ self.tessdata = Path(tessdata) if tessdata and Path(tessdata).exists() else None
154
+
155
+ def available(self):
156
+ return bool(self.exe)
157
+
158
+ def models(self) -> set[str]:
159
+ """Installed models: from the configured folder, else ask Tesseract (Linux/macOS packages install them
160
+ under /usr/share/tesseract-ocr/... which is not next to the executable)."""
161
+ if self.tessdata:
162
+ return {p.stem for p in Path(self.tessdata).glob("*.traineddata")}
163
+ if not hasattr(self, "_models"):
164
+ try:
165
+ out = subprocess.run([self.exe, "--list-langs"], capture_output=True, timeout=60)
166
+ lines = out.stdout.decode("utf-8", "replace").splitlines()
167
+ self._models = {l.strip() for l in lines[1:] if l.strip() and " " not in l.strip()}
168
+ except Exception:
169
+ self._models = set()
170
+ return self._models
171
+
172
+ def page(self, path: str, index: int, langs: str, vertical: bool = False, dpi: int | None = None,
173
+ clip: tuple | None = None, psm: str | None = None) -> tuple[str, float]:
174
+ """OCR one page (or a clip of it, as fractions x0,y0,x1,y1). Returns (text, mean word confidence 0-100).
175
+ psm: Tesseract page segmentation mode (default 3, automatic; 5 for vertical text)."""
176
+ return tsv_text(self.tsv(path, index, langs, vertical, dpi, clip, psm))
177
+
178
+ def tsv(self, path, index, langs, vertical=False, dpi=None, clip=None, psm=None) -> str:
179
+ """Tesseract's raw TSV output (word boxes and confidences) for one page or clip."""
180
+ import pymupdf
181
+ have = self.models()
182
+ langs = "+".join(l for l in langs.split("+") if l in have) or "eng"
183
+ with pymupdf.open(path) as doc, tempfile.TemporaryDirectory() as tmp:
184
+ img = Path(tmp) / "page.png"
185
+ page = doc[index]
186
+ rect = None
187
+ if clip:
188
+ r = page.rect
189
+ rect = pymupdf.Rect(r.x0 + clip[0] * r.width, r.y0 + clip[1] * r.height,
190
+ r.x0 + clip[2] * r.width, r.y0 + clip[3] * r.height)
191
+ page.get_pixmap(dpi=dpi or self.DPI, clip=rect).save(img)
192
+ cmd = [self.exe, str(img), "stdout", "-l", langs, "--psm", psm or ("5" if vertical else "3"),
193
+ "-c", "tessedit_create_tsv=1"]
194
+ if self.tessdata:
195
+ cmd += ["--tessdata-dir", str(self.tessdata)]
196
+ return subprocess.run(cmd, capture_output=True, timeout=300).stdout.decode("utf-8", errors="replace")
197
+
198
+
199
+ def _unspaced(ch: str) -> bool:
200
+ from .scripts import SCRIPTS, script_of
201
+ s = SCRIPTS.get(script_of(ch) or "")
202
+ return bool(s) and not s.spaced
203
+
204
+
205
+ def tsv_text(tsv: str) -> tuple[str, float]:
206
+ """Rebuild text from Tesseract TSV (lines and paragraphs kept) and the length-weighted mean word confidence.
207
+ In scripts written without spaces (Thai, Khmer, Burmese, CJK) Tesseract's 'words' are clusters: they are joined
208
+ unless the gap between them is wide (measured on a Thai scan: <= 13 px inside words, >= 34 px between phrases,
209
+ line height 63 px)."""
210
+ lines, cur, total, weight = [], None, 0.0, 0
211
+ line_h, right = 0, 0
212
+ for row in tsv.splitlines()[1:]:
213
+ f = row.split("\t")
214
+ if len(f) < 12:
215
+ continue
216
+ if f[0] == "4":
217
+ line_h = int(f[9])
218
+ if f[0] != "5" or not f[11].strip():
219
+ continue
220
+ key = (f[2], f[3], f[4]) # block, paragraph, line
221
+ left = int(f[6])
222
+ if key != cur:
223
+ if cur and key[:2] != cur[:2]:
224
+ lines.append("")
225
+ lines.append(f[11])
226
+ cur = key
227
+ else:
228
+ tight = left - right < 0.3 * line_h
229
+ lines[-1] += ("" if tight and _unspaced(lines[-1][-1]) and _unspaced(f[11][0]) else " ") + f[11]
230
+ right = left + int(f[8])
231
+ conf = float(f[10])
232
+ if conf >= 0:
233
+ total += conf * len(f[11])
234
+ weight += len(f[11])
235
+ return "\n".join(lines), (total / weight if weight else 0.0)
236
+
237
+ def pages(self, path): # not used directly: OCR is chosen per page with a language
238
+ raise NotImplementedError
239
+
240
+
241
+ TEXT_ENGINES = [PyMuPDF(), PDFMiner(), DoclingParse(), PyPDF()]
242
+
243
+
244
+ def available_text_engines() -> list[Engine]:
245
+ return [e for e in TEXT_ENGINES if e.available()]