Metadata-Version: 2.4
Name: tlate
Version: 0.1.0
Summary: Deterministic extract/apply/QA engine so AI agents translate documents across languages without overwriting sources.
Author: Sendy
License-Expression: MIT
Project-URL: Homepage, https://github.com/sndiy/tlate
Project-URL: Repository, https://github.com/sndiy/tlate
Project-URL: Issues, https://github.com/sndiy/tlate/issues
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Programming Language :: Python :: 3.15
Classifier: Topic :: Text Processing :: Linguistic
Requires-Python: >=3.12
Description-Content-Type: text/markdown
License-File: LICENSE
License-File: THIRD_PARTY_NOTICES.md
Provides-Extra: office
Requires-Dist: lxml>=6.0; extra == "office"
Provides-Extra: yaml
Requires-Dist: PyYAML>=6.0.2; extra == "yaml"
Provides-Extra: pdf
Requires-Dist: pymupdf>=1.28.2; extra == "pdf"
Provides-Extra: compare
Requires-Dist: Pillow>=12.0; extra == "compare"
Provides-Extra: ocr
Requires-Dist: pypdfium2>=5.0; extra == "ocr"
Requires-Dist: Pillow>=12.0; extra == "ocr"
Requires-Dist: tesserocr>=2.13.0; extra == "ocr"
Provides-Extra: all
Requires-Dist: lxml>=6.0; extra == "all"
Requires-Dist: PyYAML>=6.0.2; extra == "all"
Requires-Dist: pymupdf>=1.28.2; extra == "all"
Requires-Dist: Pillow>=12.0; extra == "all"
Provides-Extra: dev
Requires-Dist: pytest>=9.0; extra == "dev"
Requires-Dist: ruff>=0.14; extra == "dev"
Requires-Dist: lxml>=6.0; extra == "dev"
Requires-Dist: PyYAML>=6.0.2; extra == "dev"
Requires-Dist: Pillow>=12.0; extra == "dev"
Requires-Dist: pypdfium2>=5.0; extra == "dev"
Dynamic: license-file

# tlate (`0.1.0`)

**Deterministic extract, OCR, apply, and QA plumbing so AI coding agents translate documents across any language pair without ever overwriting source files.**

`tlate` pairs an `agentskills.io`-compliant Agent Skill ([skills/tlate/SKILL.md](skills/tlate/SKILL.md)), a single-source agent ruleset ([AGENTS.md](AGENTS.md)) with thin runtime pointers (`CLAUDE.md`, `GEMINI.md`, `.cursor/rules/tlate.mdc`, `.github/copilot-instructions.md`), and a zero-dependency Python CLI (`tlate`) so AI agents (Codex, Claude Code, Cursor, Antigravity, GitHub Copilot) translate documents cleanly without writing throwaway parsing scripts. `tlate` performs **no LLM API calls** inside the CLI: translation quality depends on the AI agent's chosen model and human review.

Repository: https://github.com/sndiy/tlate

## Problem vs. Solution

| Problem when AI agents translate files directly | How `tlate` solves it |
|---|---|
| Agents rewrite fragile extraction/rewriting scripts every session, wasting tokens and breaking formatting. | **The model only translates segment text**; the deterministic `tlate` CLI handles inspection, extraction, OCR, token protection, rewriting, visual diffing, and QA. |
| Source files or previous outputs are accidentally overwritten. | Every write uses exclusive creation (`open(..., "xb")`) inside a fresh `tlate-output/<stem>_<LANG>_<timestamp>/` folder with SHA-256 verification (`tlate verify`). |
| Placeholders (`{name}`, `%1$s`), URLs, code spans, or Excel formulas get corrupted. | Protected tokens (`⟦P1⟧`, `⟦S1⟧…⟦/S1⟧`) are masked before translation and strictly validated before any output file is written. |
| Encrypted or DRM-protected files are mishandled. | Password-protected PDFs, OLE/RMS Office containers, encrypted ZIPs, and DRM-protected EPUBs are refused upfront (exit code `4`, even without optional extras); edit-restricted and signed inputs require explicit acknowledgment (`--allow-edit-restricted`, `--allow-signed`), with signatures neutralized + `provenance.json` recorded. `tlate` contains zero decryption or DRM-removal code. |
| Scanned PDFs fail text extraction or force copyleft PDF dependencies everywhere. | `tlate ocr` uses permissive `pypdfium2` + pluggable `OcrEngine` (`[ocr]` via `tesserocr` or system `tesseract` CLI) for per-page `text_layer` / `ocr` / `mixed` routing; PyMuPDF (`[pdf]`) remains strictly optional. |

## Quick Start (3 Steps)

```bash
# 1. Install from PyPI (Python >= 3.12; zero mandatory core dependencies)
pip install tlate

# Optional extras as needed:
pip install "tlate[office,yaml,compare]"   # DOCX/PPTX/XLSX, YAML, PNG comparison
pip install "tlate[ocr]"                   # Permissive hybrid OCR (pypdfium2 + Pillow + tesserocr>=2.13.0 MIT + local tessdata Apache-2.0)
pip install "tlate[pdf]"                   # Strictly optional PyMuPDF PDF rewrite backend (AGPL-3.0 / Artifex commercial)

# 2. Bootstrap an isolated workspace anywhere (no git clone needed)
tlate setup ./my-translations

# 3. Put files in ./my-translations/documents/ and open the folder in your AI agent
```

Ask your agent:
> Translate `documents/guide.docx` from English to Japanese (`--from en --to ja`) using the `tlate` skill and `AGENTS.md`. Stop after the glossary and after the pilot for my approval.

Manual CLI flow (`--to` is required; `--from` defaults to `auto`):
```bash
tlate init documents/guide.md --from en --to ja
tlate inspect documents/guide.md --to ja --json tlate-output/guide_JA_<timestamp>/reports/inventory.json
tlate extract documents/guide.md --result tlate-output/guide_JA_<timestamp>
# Or for scanned/mixed PDFs:
tlate ocr documents/scan.pdf --result tlate-output/scan_ID_<timestamp> --overlays

tlate batch tlate-output/guide_JA_<timestamp>/work/segments.jsonl --max-tokens 1500
# After translating work/translations/*.jsonl:
tlate apply --result tlate-output/guide_JA_<timestamp>
tlate qa documents/guide.md tlate-output/guide_JA_<timestamp>/output/guide_JA.md --from en --to ja --review-csv tlate-output/guide_JA_<timestamp>/reports/review_sheet.csv
tlate verify tlate-output/guide_JA_<timestamp>
```

See [docs/getting-started.md](docs/getting-started.md) for installation details, including local editable installs.

## Multi-Language & OCR Highlights

- **All languages (`--from auto` by default; `--to` required):** Any language pair works via `languages/` (`24` built-in packs verified by `tlate lang check`) or generic BCP-47 fallback (`sv-SE`, `ks-Arab`). Every built-in pack starts at `status: "draft"` until native-speaker review is recorded, and both `draft` packs and `generic` BCP-47 mode emit a stderr warning and list unchecked rules (stopwords, locale typography/quotation/spacing checks, spellcheck, pair-specific expansion overrides, and style-guide rules) in QA reports. See [docs/adding-a-language.md](docs/adding-a-language.md).
- **Format-aware language metadata:** updates DOCX (`w:lang`, `w:bidi` for RTL), PPTX (`lang`), HTML/EPUB (`lang`, `dir="rtl"`, `<dc:language>`), PO (`Language`, CLDR `Plural-Forms`), and ARB (`@@locale`).
- **Adaptive QA & human review sheet:** pair-specific length expansion bounds (including compact CJK ratios), language-aware subtitle limits (`12 CPS / 18 chars` for CJK vs. `17 CPS / 42 chars` for Latin/other), stopword/ASCII leftover checks, RTL script validation, and `--review-csv` / `tlate review-sheet` (100% of flagged segments + stratified unflagged sample).
- **Permissive hybrid OCR (`tlate ocr`):** per-page classification into `text_layer`, `ocr`, or `mixed` via `pypdfium2` + `Pillow` + `tesserocr>=2.13.0` (`MIT`, requires local `tessdata`, `Apache-2.0`) or system `tesseract` CLI, IoU/coverage deduplication of overlapping OCR boxes, `low_ocr_confidence` flagging, optional color-coded PNG bounding-box overlays (`--overlays`), flagged-only cropped previews (`--export-crops`, `150` DPI, `<= 512 px`), and explicit white-fill redaction (`ocr_overlay_replacement`) during `tlate apply`.
- **Adaptive PDF layout & bookmark preservation:** Layout adapts to translated text (font size, wrapping, box size) while preserving the document's structure, within measured metrics, with listed limitations. Page count matches source by default (`--allow-extra-pages` is strictly opt-in for trailing PDF overflow). See [docs/formats/pdf.md](docs/formats/pdf.md) and [docs/layout-metrics.md](docs/layout-metrics.md).
- **Streaming, safety limits & token efficiency:** incremental JSONL streaming (`--resume` checkpoints), zip-bomb/path-traversal/size/page/segment/pixel guards (`--max-file-mb`, `--max-pages`, `--max-segments`, exit `4`), strict `--budget-tokens` refusal without trimming (exit `7`), conservative `skip_rules`, exact dedup + TM, relevant-only `--glossary` batch injection, `stable-prefix.md`, optional `--wire-format compact` / `--fuzzy-tm`, `tlate pilot`, image `alt_text` round-tripping, and duplicate-consistency QA (`tlate qa --result`). See [docs/efficiency.md](docs/efficiency.md).
- **Agent consent & checkpoints:** [skills/tlate/SKILL.md](skills/tlate/SKILL.md) requires explicit user consent before any network access, model/package download, or writes outside `<result>`/target workspace, and enforces stops after glossary and pilot.

### Visual PDF Comparison (`tlate compare`)

Actual `tlate compare` output on a synthetic PDF fixture (preserving colored boxes, raster images, `{app_name}` placeholders, and URLs):

![Side-by-side comparison of source PDF and translated PDF](docs/demo/pdf-compare.png)

## Supported Formats (Beta)

| Format | Extensions | Status | Optional Extra | Notes & Docs |
|---|---|---|---|---|
| Markdown & plain text | `.md`, `.markdown`, `.txt` | **beta** | *(core, stdlib)* | Preserves fences, tables, BOM/CRLF ([docs/formats/markdown-text.md](docs/formats/markdown-text.md)) |
| Subtitles | `.srt`, `.vtt` | **beta** | *(core, stdlib)* | Keeps cues/timestamps; language-aware line/CPS QA ([docs/formats/subtitles.md](docs/formats/subtitles.md)) |
| i18n localization | `.json`, `.arb`, `.po`, `.pot`, Android `strings.xml` | **beta** | *(core, stdlib)* | Protects ICU plurals, escapes, CLDR `Plural-Forms` ([docs/formats/i18n.md](docs/formats/i18n.md)) |
| YAML | `.yaml`, `.yml` | **beta** | `[yaml]` (PyYAML) | In-place value edits, comments preserved ([docs/formats/i18n.md](docs/formats/i18n.md)) |
| Office OOXML | `.docx`, `.pptx`, `.xlsx` | **beta** | `[office]` (lxml) | Direct XML; formulas & OLE-encrypted refusal ([docs/formats/office.md](docs/formats/office.md)) |
| Web & e-book | `.html`, `.htm`, `.xhtml`, `.epub` | **beta** | *(core, stdlib)* | Refuses DRM; stores `mimetype` uncompressed; sets `dir="rtl"` ([docs/formats/html-epub.md](docs/formats/html-epub.md)) |
| PDF (text layer) | `.pdf` | **beta** | `[pdf]` (PyMuPDF) | Adaptive role-harmonized layout, bookmark translation, risky-layout flags ([docs/formats/pdf.md](docs/formats/pdf.md), [docs/layout-metrics.md](docs/layout-metrics.md)) |
| PDF (scanned / mixed) | `.pdf` | **beta** | `[ocr]` + `[pdf]` | `tlate ocr` via `pypdfium2` + pluggable `OcrEngine` ([docs/formats/ocr.md](docs/formats/ocr.md)) |
| Planned formats (`.doc`, `.ppt`, `.xls`, `.odt`, `.idml`, `.ass`, Apple `.strings`) | — | **planned** | — | Not yet supported |

## Architecture Overview

```mermaid
flowchart LR
  S["Source file<br/>(read-only, SHA-256)"] --> I["tlate init / inspect"]
  I --> E["tlate extract or tlate ocr<br/>+ protect ⟦Pn⟧ / ⟦Sn⟧"]
  E --> B["work/segments.jsonl<br/>+ tlate batch & TM"]
  B --> M["AI Agent / Model<br/>(translates text only)"]
  M --> T["work/translations/*.jsonl"]
  T --> A["tlate apply<br/>(exclusive write xb)"]
  A --> O["output/<stem>_<LANG>.<ext>"]
  O --> Q["tlate qa & compare"]
  O --> V["tlate verify<br/>(SHA-256 check)"]
```

See [docs/architecture.md](docs/architecture.md) for the `tlate/segments@1` contract, `PdfEngine`/`OcrEngine` abstractions, and CLI exit codes (`0`–`7`).

## License & PyMuPDF Notice

- This repository is licensed under the **MIT License** (see [LICENSE](LICENSE)). The core `tlate` package has **zero mandatory third-party dependencies**.
- The default PDF rewriting backend uses **PyMuPDF** as an **optional** extra (`[pdf]`), **never vendored** in this repository. PyMuPDF is dual-licensed under **GNU AGPL-3.0** or an **Artifex commercial license**. Users who install, distribute, or run the `[pdf]` extra (including as a network service) are solely responsible for complying with PyMuPDF's license terms. See [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md) and [docs/security-and-copyright.md](docs/security-and-copyright.md).

## Honest Limitations

- **Does not guarantee error-free translations.** `tlate qa` is heuristic; manual visual inspection and back-translation sampling remain essential.
- **Scanned/mixed PDF OCR fidelity is lower:** original raster fonts, textured/colored backgrounds behind OCR boxes (replaced by solid white fill `(1, 1, 1)`), kerning, skewed/handwritten text, and complex multi-column tables are not preserved verbatim. See [docs/formats/ocr.md](docs/formats/ocr.md).
- **Text inside raster images (non-OCR flows), OOXML chart titles, and SmartArt:** not edited automatically.
- **Dense PDF overflow & risky layouts:** when translated text still exceeds a box after per-role font sizing, line-height tightening, and collision-free expansion, it is never truncated — `tlate` renders it in the safest available box and flags `overflow_after_adaptive_fit` in `review_flags` (and `inspect` flags `multi_column`, `text_over_image`, `rotated_or_vertical_text`, `form_fields`, and `fixed_table_cells`). Arabic (`ar`) PDF text extraction emits ToUnicode CMap ligature artifacts (`LIMITED_FOR_PDF`); see [docs/layout-metrics.md](docs/layout-metrics.md).
- **RTL visual verification:** `tlate` sets `dir="rtl"` / `w:bidi` and verifies RTL script presence, but bidirectional punctuation/number ordering requires manual visual review.
- **No built-in LLM API client:** `tlate` intentionally contains no `translate` command that calls remote LLM APIs, keeping document processing strictly local and deterministic; translation quality depends on the AI agent's chosen model and human review.
- **Estimated token budgets & unmeasured provider caching:** `cost_preview` and `--budget-tokens` use an approximate `~4 chars/token` Latin heuristic rather than provider-specific tokenizers; prompt-cache hit rates on `stable-prefix.md` and multimodal image token costs vary by model/agent and are not measured by `tlate`. See [docs/efficiency.md](docs/efficiency.md).
- **Protected files & legal disclaimers:** `tlate` never decrypts password-protected files, never removes DRM, refuses `apply` on edit-restricted PDFs (to avoid stripping `/Encrypt`), and never produces certified/sworn legal translations. See [docs/protected-files.md](docs/protected-files.md) for the full detected vs. unhandled list.

## Related Documentation

- [Getting Started](docs/getting-started.md) · [Architecture](docs/architecture.md) · [Glossary Guide](docs/glossary-howto.md)
- [Adding a Language Pack](docs/adding-a-language.md) · [Indonesian Pack Guide](languages/id/style-guide.md) · [QA Guide](docs/qa.md) · [Troubleshooting](docs/troubleshooting.md)
- [Evaluations (33/33)](docs/evals.md) · [PDF Layout Metrics](docs/layout-metrics.md) · [Efficiency & Benchmarks](docs/efficiency.md) · [Known Issues](docs/known-issues.md)
- [Security, Privacy & Licensing](docs/security-and-copyright.md) · [Protected Files](docs/protected-files.md) · [Password Mode Design](docs/design-password-mode.md) · [Python Support](docs/python-support.md) · [Dependencies Audit](docs/dependencies.md) · [Claims Map](docs/claims.md) · [Credits](docs/credits.md)
- [Contributing](CONTRIBUTING.md) · [Code of Conduct](CODE_OF_CONDUCT.md) · [Security Policy](SECURITY.md) · [Changelog](CHANGELOG.md)
