Metadata-Version: 2.4
Name: trueglyph
Version: 0.1.0
Summary: Tells AI agents when text extracted from a PDF cannot be trusted - for every script, not just Latin - and repairs it.
License-Expression: MIT
Project-URL: Homepage, https://github.com/jishnucz/TrueGlyph
Project-URL: Repository, https://github.com/jishnucz/TrueGlyph
Project-URL: Issues, https://github.com/jishnucz/TrueGlyph/issues
Keywords: pdf,text-extraction,ocr,rag,unicode,multilingual,mcp,ai-agents,llm,indic,arabic,cjk,data-quality
Classifier: Programming Language :: Python :: 3
Classifier: Operating System :: OS Independent
Classifier: Intended Audience :: Developers
Classifier: Topic :: Text Processing :: Linguistic
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Natural Language :: Hindi
Classifier: Natural Language :: Bengali
Classifier: Natural Language :: Arabic
Classifier: Natural Language :: Chinese (Simplified)
Classifier: Natural Language :: Japanese
Classifier: Natural Language :: Thai
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: pymupdf>=1.24
Provides-Extra: engines
Requires-Dist: pypdf>=5; extra == "engines"
Requires-Dist: pdfminer.six>=20240706; extra == "engines"
Requires-Dist: docling-parse>=4; extra == "engines"
Provides-Extra: lexicon
Requires-Dist: wordfreq>=3.1; extra == "lexicon"
Provides-Extra: mcp
Requires-Dist: mcp>=1.2; extra == "mcp"
Provides-Extra: all
Requires-Dist: trueglyph[engines,lexicon,mcp]; extra == "all"
Provides-Extra: dev
Requires-Dist: trueglyph[all]; extra == "dev"
Requires-Dist: pytest>=8; extra == "dev"
Dynamic: license-file

# TrueGlyph

<!-- mcp-name: io.github.jishnucz/trueglyph -->

[![CI](https://github.com/jishnucz/TrueGlyph/actions/workflows/ci.yml/badge.svg)](https://github.com/jishnucz/TrueGlyph/actions/workflows/ci.yml) [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/jishnucz/TrueGlyph/blob/main/LICENSE) ![Python 3.10+](https://img.shields.io/badge/python-3.10%2B-blue.svg)

**Know when the text you pulled out of a PDF is wrong — in any script — and get the right text instead.**

AI agents and RAG pipelines read PDFs with extractors such as pypdf, PyMuPDF, pdfminer or docling. For English that
mostly works. For Hindi, Bengali, Tamil, Thai, Khmer, Burmese, Arabic, Urdu, Persian, Hebrew, Chinese or vertical
Japanese, those tools often return **damaged text without any error**: vowel signs in the wrong order, letters
doubled, words split, glyph codes instead of letters, right-to-left lines reversed, or nothing at all from a scanned
page. Even English PDFs come out with words broken by hyphenation and symbols lost. The agent then indexes, quotes
and reasons over text that is wrong, and nobody notices.

TrueGlyph checks every page, repairs what it safely can, switches extractor or falls back to OCR when it must, and
gives each page a **trust level** so your code or agent knows what it may use. It runs locally: no API keys, no
cloud, no LLM.

```text
$ trueglyph demo
Hindi
  pypdf    [BAD ] इसी घोषणा का सरकारी पाठ संयुक्त रा␀␀ों की इन पांच भाषाओं म␀ प्राप्य हैः—
  TrueGlyph [OK  ] इसी घोषणा का सरकारी पाठ संयुक्त राष्ट्रों की इन पांच भाषाओं में प्राप्य
Urdu
  pypdf    [BAD ] ﺗﻣﮩﯾد ﭼوﻧﮑہ ﮨر اﻧﺳﺎن ﮐﯽ ذاﺗﯽ ﻋزت اور ﺣرﻣت        <- glyph codes, not letters
  TrueGlyph [OK  ] تمہید چونکہ ہر انسان کی ذاتی عزت اور حرمت
Thai
  pypdf    [BAD ] โดยที␀การยอมรับนับถือเกียรติศักดิ␀ประจําตัว     <- tone marks lost
  TrueGlyph [WARN] โดยที่การยอมรับนับถือเกียรติศักดิ์ประจำตัว
Japanese (vertical)
  pypdf    [BAD ] ︿ 前 ⽂ ﹀ ⼈ 類 社 会 の す べ て         <- radicals (⼈ is not 人), one character at a time
  TrueGlyph [OK  ] 〈前文〉人類社会のすべての構成員の固有の尊厳と平等で
```

**Contents:** [Quick start](#quick-start) · [Trust levels](#trust-levels) · [Use it from your tools](#use-it-from-your-tools)
· [How it works](#how-it-works) · [Results](#results) · [Limitations](#limitations) ·
[Configuration](#configuration) · [Development](#development) · [Contributing](#contributing)

## Quick start

Python 3.10 or newer.

```bash
pip install "trueglyph[all] @ git+https://github.com/jishnucz/TrueGlyph"   # PyMuPDF + other extractors, word lists, MCP server
trueglyph demo                    # see the problem and the fix, no files needed
trueglyph read report.pdf         # check your own PDF
```

Once the PyPI release is out this becomes `pip install "trueglyph[all]"`. Without git, download the wheel from
[Releases](https://github.com/jishnucz/TrueGlyph/releases) and run `pip install "trueglyph-0.1.0-py3-none-any.whl[all]"`.
Installing without `[all]` gives PyMuPDF only: fewer checks and no MCP server.

Nothing to install at all, with [uv](https://docs.astral.sh/uv/):

```bash
uvx --from "trueglyph[all] @ git+https://github.com/jishnucz/TrueGlyph" trueglyph demo
```

**Scanned pages need Tesseract** (optional; without it, scanned pages are reported as `none` instead of read):

| System | Install |
|---|---|
| Windows | `winget install UB-Mannheim.TesseractOCR` |
| macOS | `brew install tesseract tesseract-lang` |
| Debian / Ubuntu | `sudo apt install tesseract-ocr tesseract-ocr-hin tesseract-ocr-tha ...` (one package per language) |

For the best accuracy, download the models for your scripts from
[tessdata_best](https://github.com/tesseract-ocr/tessdata_best) into a `.tessdata` folder in your working directory,
or point `TRUEGLYPH_TESSDATA` at them.

## Trust levels

Every page gets one level. The document's level is its worst page.

| Trust | Meaning | What to do |
|---|---|---|
| `high` | no sign of damage | use the text |
| `medium` | minor issues, or checked by script rules only | usable; double-check exact quotes, names and numbers |
| `low` | damaged: letters lost, garbled, or OCR unsure | do not quote or index it as exact text; say the page could not be read reliably |
| `none` | no usable text (scan without OCR, or nothing readable) | do not guess |

What a reading looks like:

```text
$ trueglyph read demo.pdf
demo.pdf: document trust MEDIUM  high=3  medium=1
  page   1 OK   high   Devanagari via pymupdf  repairs: collapsed_repeated_marks=8, merged_split_words=2
  page   2 OK   high   Arabic     via pypdf  repairs: presentation_forms_to_letters=220
  page   3 WARN medium Thai       via pymupdf  repairs: joined_wrapped_lines=5
           - moderate: Line breaks inside words (script written without spaces).
  page   4 OK   high   Kana       via pymupdf  repairs: joined_wrapped_lines=149
```

## Use it from your tools

### Command line

```bash
trueglyph read report.pdf                 # per-page trust, issues and repairs
trueglyph read report.pdf --text          # only the best text
trueglyph read report.pdf --json          # everything, machine-readable (add --no-text to omit the text)
trueglyph read report.pdf --pages 1,3-5   # some pages only
trueglyph read report.pdf --lang hi       # language hint (ISO 639-1); helps OCR pick its model
trueglyph read report.pdf -v              # show every decision: engines tried, OCR model contest, ...
echo "ﺍﻟﺴﻼﻡ ﻋﻠﻴﻜﻢ" | trueglyph check --repair   # check text that came from ANY other tool
```

### Python

```python
from trueglyph import read, assess, repair

doc = read("report.pdf")                  # also: lang="hi", ocr=False, pages=[1, 2]
print(doc.trust, doc.summary)             # 'medium', {'high': 3, 'medium': 1, 'low': 0, 'none': 0}
for page in doc.pages:                    # page.text, .trust, .script, .lang, .engine, .issues, .repairs
    if page.trust in ("high", "medium"):
        index(page.text)
    else:
        print(page.page, page.trust, [i["message"] for i in page.issues])

assess(chunk_from_any_tool).trust         # check text you already have
repair(chunk_from_any_tool).text          # and repair it (only what was detected)
```

### AI agents (MCP server)

Two tools: `read_pdf(path, lang?, pages?, ocr?)` and `check_text(text, lang?, repair_text?)`. The server tells the
agent what each trust level means.

```bash
claude mcp add trueglyph -- trueglyph-mcp     # Claude Code, if you pip-installed it
# nothing installed? let uvx fetch it:
claude mcp add trueglyph -- uvx --from "trueglyph[all] @ git+https://github.com/jishnucz/TrueGlyph" trueglyph-mcp
```

Claude Desktop, Cursor and other MCP clients (`mcpServers` config):

```json
{ "trueglyph": { "command": "uvx",
                 "args": ["--from", "trueglyph[all] @ git+https://github.com/jishnucz/TrueGlyph", "trueglyph-mcp"] } }
```

After the PyPI release, `"trueglyph[all]"` alone is enough in place of the `git+` form.

### RAG frameworks

```python
from trueglyph.integrations import TrueGlyphLoader, TrueGlyphReader

docs = TrueGlyphLoader("report.pdf", min_trust="medium").load()       # LangChain: one Document per page
docs = TrueGlyphReader(min_trust="medium").load_data("report.pdf")    # LlamaIndex: one Document per page
```

Pages below `min_trust` are skipped (or kept with `keep_untrusted=True`). Each document's metadata carries `trust`,
`script`, `lang`, `extractor`, `issues` and `repairs`, so you can filter or flag at query time.

### Elsewhere

| Where | How |
|---|---|
| Claude Code plugin | `/plugin marketplace add jishnucz/TrueGlyph`, then `/plugin install trueglyph@trueglyph` (MCP server + skill) |
| VS Code, Cursor | download `trueglyph-0.1.0.vsix` from [Releases](https://github.com/jishnucz/TrueGlyph/releases), then `code --install-extension trueglyph-0.1.0.vsix`. Right-click a PDF → *Check PDF*; select text → *Check Selected Text*; registers the MCP server for Copilot agent mode |
| Agent skill (Claude, OpenClaw/ClawHub, Codex) | `skills/read-pdf-faithfully/SKILL.md`: when to use TrueGlyph and how to act on trust levels |
| Browser | `pip install gradio && python space/app.py`: drop a PDF and compare plain extraction with TrueGlyph page by page |

## How it works

For each page TrueGlyph:

1. **Measures** reference-free signs of damage: patterns that correctly encoded text in that script never
   contains (a Devanagari vowel sign before its consonant, a Thai tone mark with no letter under it, Arabic
   presentation-form codes, one Chinese character per line, a hyphenated word that is one known word...).
2. **Repairs** only what it detected, and only in ways that are checked (a split word is joined only if the result
   is a known word). It never hides what is lost: removed placeholders for missing letters keep the page `low`.
3. **Compares** the extractors and keeps the most faithful reading; for English, the first clean reading is enough.
4. **Falls back to OCR** when the text layer is missing or unusable. It picks the Tesseract model from the page's
   own script, from Tesseract's script detection when a test read confirms it, or by a contest between models
   scored on what they read. If layout analysis shreds a page (Burmese), the page is read again as one block.
5. **Reasons about the whole document:** a page whose text layer is only a typed title over a scan is OCR'd, and
   when the font is broken on most pages, the remaining pages are OCR'd too.
6. **Reports** the trust level, the issues found and the repairs made.

### What it detects and repairs

| Issue | Typical source | Repair |
|---|---|---|
| `lost_glyphs`: NUL, U+FFFD, private-use or `(cid:N)` for unmapped glyphs | pypdf, pdfminer (Indic, Burmese, Khmer, math) | none possible: switch extractor or OCR; never hidden |
| `visual_order_vowels`: pre-base vowel signs (ि, ে, ெ…) before their consonant | pypdf, pdfminer | reorder into reading order |
| `doubled_vowel_signs`: a letter's marks repeated (ाा, ംം) | PyMuPDF | collapse the repeat |
| `orphan_marks`: vowel signs separated from their letter | docling-parse, pdfminer | rejoin |
| `presentation_forms`: Arabic/Hebrew glyph codes instead of letters | pypdf, pdfminer | map to letters |
| `reversed_rtl`: right-to-left lines in visual order | pdfminer | reverse, only if that makes real words |
| `cjk_fragmented`, `cjk_lookalikes`: one character per line, spaces between characters, Kangxi radicals (⼈ for 人) | vertical text, pypdf | rejoin; map to standard characters |
| `wrap_breaks`: line breaks inside words in scripts without spaces | all extractors | join full-width lines only |
| `split_words`: fragments that only form a word when joined | docling-parse | join into known words only |
| `impossible_clusters`: Thai/Lao vowels or tone marks without their consonant | pdfminer; an OCR model reading another script | rejoin split marks; otherwise switch OCR model |
| `mixed_script_garble`, `vowel_clash`, `symbol_garble`: broken font mappings | pre-Unicode fonts | none possible: OCR |
| `hyphen_breaks`, `glued_words`, `letter_spaced`: `infor- mation`, `Achainofthought`, `S U M M A R Y` | all extractors | join or split into known words only; compounds in German, Dutch or Finnish are never split |
| `ligatures`, `hidden_chars`: ﬁ ﬂ, soft hyphens, zero-width characters | many tools | expand / remove |
| `few_known_words`, `ocr_low_confidence`: garbled text or the wrong OCR model | legacy fonts, OCR | try other models; report |
| `no_text_layer`, `engine_returned_nothing` | scans; an extractor that fails silently | OCR; use another extractor |

Thresholds come from calibration: on clean text in **388 languages** (`bench/calibrate.py`) the structural signals
stay at zero.

## Results

Every number here is produced by the benchmark in `bench/` and can be reproduced ([Development](#development)).
Quality is the share of the text a search index would see intact: word F1 for scripts written with spaces,
adjacent-character F1 for scripts without (Thai, Lao, Khmer, Burmese, Chinese, Japanese).

### Real PDFs: 29 documents from the UN Human Rights Office

The Universal Declaration of Human Rights as published by OHCHR, in PDFs made over decades with about 20 different
tools; 11 are scans without a text layer and several use pre-Unicode fonts.

| Reader | Mean quality | Documents ≥ 0.90 |
|---|---|---|
| pypdf / pdfminer / docling-parse / PyMuPDF | 0.34–0.35 | 8/29 |
| the same, plus TrueGlyph's repairs | 0.37–0.38 | 9/29 |
| **TrueGlyph** (repair + extractor choice + OCR) | **0.782** | **14/29** |

| Document | Best plain extractor | **TrueGlyph** | Trust | How |
|---|---|---|---|---|
| Vietnamese (legacy font) | 0.004 | **0.998** | high | OCR with the Vietnamese model, chosen by contest |
| Chinese (a space between all characters) | 0.155 | **0.979** | high | text layer, spaces removed |
| Hebrew (dingbat font) | 0.000 | **0.976** | high | OCR |
| Georgian (legacy font) | 0.002 | **0.958** | high | OCR |
| Hindi | 0.000 | **0.957** | high | OCR |
| Marathi | 0.549 | **0.947** | high | OCR, checked against the bundled Marathi word list |
| Khmer (legacy font) | 0.000 | **0.837** | low | OCR with the Khmer model, chosen by contest |
| Bengali (typed title over a scanned page) | 0.000 | **0.795** | high | OCR under the title |
| Thai (scan) | 0.000 | **0.778** | medium | OCR |
| Burmese (pre-Unicode font) | 0.000 | **0.749** | low | OCR, page re-read as one block |
| English, French, German, Spanish, Russian, Greek, Japanese, Korean | 0.94–0.99 | unchanged | high | text layer, untouched |

Not recovered, and reported as such:

| Document | TrueGlyph | Trust | Why |
|---|---|---|---|
| Urdu (Nastaliq scan) | 0.083 | low | no Tesseract model reads Nastaliq at this quality |
| Malayalam | 0.259 | low | scanned at about 60 dpi in the old Malayalam script |
| Tamil | 0.327 | high | the OCR text is clean; the benchmark's reference is a different Tamil translation |
| Armenian | 0.640 | high | same for every reader; the reference is a different translation |

**Are the trust levels honest?** Each raw extractor reading (116) was judged without the reference: of 84 damaged
readings, **80 were flagged**, including all 73 badly damaged ones; the 4 misses are the Armenian translation
mismatch. 4 of 32 intact readings were flagged `medium` (Japanese with line breaks inside words).

### Synthetic set: known text, 30 documents, 24 scripts

The same declaration in 30 languages rendered to PDF by Chromium, including vertical Japanese and Chinese and four
right-to-left languages.

| Reader | Mean quality | Worst document | Documents ≥ 0.90 |
|---|---|---|---|
| pypdf | 0.673 | 0.000 | 13/30 |
| pdfminer | 0.610 | 0.000 | 11/30 |
| docling-parse | 0.814 | 0.000 | 16/30 |
| PyMuPDF (best single extractor) | 0.875 | 0.000 | 23/30 |
| **TrueGlyph** | **0.978** | **0.714** | **29/30** |

| Trust assigned (120 raw readings) | Readings | Mean true quality | Actually damaged (< 0.90) |
|---|---|---|---|
| high | 41 | 0.985 | 2% |
| medium | 15 | 0.925 | 27% |
| low | 64 | 0.545 | 81% |

All 24 badly damaged readings were flagged; 56 of 57 damaged readings were flagged.

### English: 24 recent arXiv papers (628 pages)

Every paper had words split by line-break hyphenation (about 119 per paper: `imple- mentation`), and PyMuPDF or
pdfminer left placeholders for unmapped symbols in 21–22 of them. TrueGlyph joins hyphenated words only into real
words (`well-known`, `k-means` stay as they are) and raises **no false alarms**: reference lists full of names and
code listings stay `high`; the 4 pages it flags really lost characters. A clean 26-page paper is checked in under a
second.

## Limitations

- **OCR quality is Tesseract's.** TrueGlyph reports OCR confidence and marks unsure pages `low`; it does not hide
  OCR errors. Two scans are beyond it. Both were also tried with every available Tesseract model, other page
  segmentations, image upscaling and a second OCR engine (EasyOCR: worse on the Urdu, no Malayalam model): Urdu
  printed in Nastaliq, and Malayalam scanned at about 60 dpi in the old script. Both stay `low`: flagged, not
  recovered.
- **Word lists.** Words are checked with frequency lists (wordfreq) for about 40 languages and with dictionaries
  taken from Tesseract's models for 17 more: Marathi, Nepali, Malayalam, Kannada, Telugu, Sinhala, Gujarati,
  Punjabi, Odia, Assamese, Amharic, Georgian and Armenian, plus Thai, Lao, Khmer and Burmese, whose text is first
  split into dictionary words because they are written without spaces. Those dictionaries have no frequencies and
  include word fragments, so they flag garbled text and split words but do not rank readings. Chinese, Japanese and
  Korean are checked by script rules only (`checks: structural`).
- **Trust levels are calibrated heuristics, not probabilities.** Measured honesty is shown above.
- **Speed:** text-layer pages take milliseconds to a fraction of a second. OCR with Tesseract's best models takes
  seconds per page (pages run in parallel). When the script of a scan is unclear, a model contest adds a one-off
  cost per document; it tries the likeliest script first and stops at a clear winner.
- **Not a layout tool:** TrueGlyph checks and fixes text, not reading order of columns, tables or figures.
- Benchmark references are not perfect: some UDHR translations differ from the UN PDFs (Tamil, Armenian), and real
  PDFs include headers and page numbers, so compare readers with each other rather than with 1.0.

## Configuration

| Setting | Purpose |
|---|---|
| `TRUEGLYPH_TESSDATA` | folder with Tesseract models (`*.traineddata`); default `./.tessdata`, then Tesseract's own |
| `TRUEGLYPH_TESSERACT` | path to the `tesseract` executable if it is not on `PATH` |
| `--lang` / `lang=` | ISO 639-1 language hint: picks the OCR model and word list directly |
| `--no-ocr` / `ocr=False` | never run OCR (scanned pages then come back as `none`) |

Bad input gets a plain message, not a stack trace: a missing, empty, damaged or password-protected PDF, or a page
number that does not exist (`trueglyph: error: report.pdf has 3 page(s); there is no page 5.`).

## Development

```bash
git clone https://github.com/jishnucz/TrueGlyph && cd TrueGlyph
pip install -e ".[dev]"            # editable install with pytest
pytest                             # 47 tests, including an end-to-end MCP session and OCR when Tesseract is present
```

Reproduce the benchmark:

```bash
python bench/build.py              # synthetic PDFs (needs Microsoft Edge to render)
python bench/realset.py            # real PDFs from the UN Human Rights Office
python bench/extract_all.py && python bench/extract_all.py real
python bench/run.py                # -> bench/results/RESULTS_synthetic.md
python bench/run.py real --ocr     # -> bench/results/RESULTS_real.md
python bench/calibrate.py          # signal behaviour on clean text in 388 languages
```

## Why this exists

| Evidence | Source |
|---|---|
| docling's own check for broken text layers "look[s] at Latin letters only, so text in other scripts cannot be flagged" | [docling PR #4654](https://github.com/docling-project/docling/pull/4654) |
| Open extraction bugs for Vietnamese, Thai, Hindi (words split at vowel signs) and vertical Japanese (a space between every character) | [docling #3170](https://github.com/docling-project/docling/issues/3170), [#4672](https://github.com/docling-project/docling/issues/4672) |
| A government problem statement: thousands of pages a day "in both English and Malayalam, sometimes in bilingual hybrids" | Smart India Hackathon 2025, SIH25080 (Kochi Metro) |
| Measured here: the same text through four extractors, 24 scripts | [Results](#results) |

TrueGlyph came out of a search for an unmet need in the AI-agent ecosystem across more than 60 candidate areas. This
one was found by testing extractors and measuring where they fail, then confirmed by the independent sources above.

## Contributing

The most useful contribution is a PDF that TrueGlyph reads wrong or rates wrongly: open an
[issue](https://github.com/jishnucz/TrueGlyph/issues) with the file (or a link), the language, and what the page
really says. Pull requests are welcome; run `pytest` first. Each new check needs calibration on clean text
(`bench/calibrate.py`) so it does not raise false alarms.

## License

MIT. The bundled word lists in `src/trueglyph/wordlists/` come from the Tesseract OCR models (Apache-2.0; see the
NOTICE file there). Benchmark PDFs are derived from the Universal Declaration of Human Rights (public domain / UN)
and OHCHR publications.
