Skip to content
المشاريع

jenh/epub-ocr-and-translate

عرض على GitHub

حول

Toolkit to OCR/ingest PDFs & EPUBs, translate via local LLMs, OpenRouter, or Gemini (with cost caps and estimates), and build bilingual PDFs, EPUBs & JSONL.

الذكاء الاصطناعي وتعلّم الآلة

كيف تُقاس هذه الأرقام

ما يمكنك فعله

  • Run $0 against local models (llama-server, Ollama, LM Studio): Omit --backend and --model to auto-discover whatever model you're running locally (tuned for 8 GB RAM hosts with --reasoning-budget 0 and compact XML-tagged batches).
  • --dry-run cost & token estimates on every stage: Preview page/chunk/segment counts, estimated input/output tokens, live OpenRouter spend, vision-compatibility checks, and active --max-cost circuit breakers across ingest, glossary, and translate before spending a cent.
  • Built-in free & vision model search (eoat models): Browse OpenRouter's live catalog right from your CLI (eoat models --free, eoat models --vision --search flash) to spot $0 :free endpoints, image-capable VLM OCR models, context lengths, and per-1M token rates.
  • Archival-grade VLM OCR + script-mismatch detection: Automatically catches wrong-language legacy PDF text layers (such as Latin OCR over Armenian scans), falls back to page-checkpointed Vision LLM OCR when historical fonts/borders trip up Tesseract, and resumes mid-book after Ctrl+C or --max-cost.

النمو المقاس للنجوم

خلال 24 ساعة
جارٍ جمع السجل
خلال 7 أيام
جارٍ جمع السجل
خلال 15 يومًا
جارٍ جمع السجل
خلال شهر
جارٍ جمع السجل

تغيّر صافي النجوم خلال فترات متداخلة، وليس مجموعًا يوميًا. تبقى القياسات المفقودة فارغة. النجوم تقيس الاهتمام لا جودة البرمجيات.

README.md

الأصل

epub-ocr-and-translate (eoat v2)

Branch note: main is EOAT v2. The original 2018–2019 OpenNMT-py + bash v1 release remains preserved on master / v1-legacy (tag v1.0.0) and archived under legacy/.

Local-first, zero-cost-friendly toolkit to ingest scanned or digital PDFs/EPUBs, translate them with local LLMs (llama-server / Ollama), OpenRouter, offline NMT (ctranslate2), or Gemini, publish clean EPUB3 and Typst PDFs (including bilingual editions), and export structured JSONL / XML / golden-prompt datasets.

Cool New Features

  • Run $0 against local models (llama-server, Ollama, LM Studio): Omit --backend and --model to auto-discover whatever model you're running locally (tuned for 8 GB RAM hosts with --reasoning-budget 0 and compact XML-tagged batches).
  • --dry-run cost & token estimates on every stage: Preview page/chunk/segment counts, estimated input/output tokens, live OpenRouter spend, vision-compatibility checks, and active --max-cost circuit breakers across ingest, glossary, and translate before spending a cent.
  • Built-in free & vision model search (eoat models): Browse OpenRouter's live catalog right from your CLI (eoat models --free, eoat models --vision --search flash) to spot $0 :free endpoints, image-capable VLM OCR models, context lengths, and per-1M token rates.
  • Archival-grade VLM OCR + script-mismatch detection: Automatically catches wrong-language legacy PDF text layers (such as Latin OCR over Armenian scans), falls back to page-checkpointed Vision LLM OCR when historical fonts/borders trip up Tesseract, and resumes mid-book after Ctrl+C or --max-cost.
  • Target, bilingual, & --mode source publishing + eval exports: Compile clean EPUB3s and 6×9" Typst PDFs (interlinear, side-by-side, or re-typeset --mode source archival editions), A/B test models via --run <name>, and grab aligned lang:lang strings straight from .eoat/segments.jsonl or eoat export (golden-jsonl, chat-jsonl, tmx, xml).

What Changed in v2

  • No ImageMagick / policy.xml / Poppler / GNU sed hacks: PyMuPDF extracts native PDF text layers directly, detects garbled legacy OCR layers automatically, applies fast grayscale/contrast cleanup (--preprocess), auto-maps Tesseract language codes from source_lang, and checkpoints pages so ingest is resumable.
  • No multi-GB TeX Live install required: Typst compiles 6×9" print-ready PDFs (and bilingual side-by-side / interlinear editions) in milliseconds via a single bundled binary.
  • No langdetect guesswork: Aligned segments live in .eoat/segments.jsonl (with XML/TMX & dataset exports), making translation runs resumable and bilingual builds trivial.
  • Smart whole-book glossary mining: Skips Table of Contents & copyright boilerplate, prioritizes Dramatis Personae / Glossary sections, mines dispersed proper nouns across all chapters locally in Python before calling the LLM (--strategy auto), and saves after every chunk.
  • Built for constrained hardware (8 GB RAM) + safe cloud access: Interruptible & resumable across ingest, glossary, and translate (Ctrl+C anytime, --chapters, --max-batches), XML-tagged batching tuned for small models (llama-server --reasoning-budget 0), built-in eoat models discovery (--free, --vision, --search) with live OpenRouter pricing, auto-loaded .env keys, confirmation prompts, and --max-cost spend circuit breakers.

Install

Requires Python 3.11+ (and tesseract only if OCR-ing scanned PDFs—eoat init --install-ocr checks, installs/downloads lightweight language packs, and verifies Tesseract automatically).

Supported Platforms

  • macOS: Supported natively (brew install tesseract).
  • Linux (Debian / Ubuntu & RHEL / CentOS / Fedora): Supported natively (sudo apt-get install -y tesseract-ocr on Debian/Ubuntu; sudo dnf install -y tesseract or yum + EPEL on RHEL/CentOS). Missing language packs are downloaded user-locally to ~/.local/share/eoat/tessdata/ with no sudo needed.
  • Windows: Use the Ubuntu shell via WSL2 (wsl --install -d Ubuntu) and follow the Debian/Ubuntu instructions.

Clone the repo (main is v2; for the archived 2018 v1 scripts check out v1-legacy or tag v1.0.0):

git clone https://github.com/jenh/epub-ocr-and-translate
cd epub-ocr-and-translate

Option A: Global CLI with pipx or uv (Recommended)

Installing via pipx or uv puts eoat on your PATH so you can run it from any separate book working directory (not inside the git repo):

# Using pipx (run `pipx ensurepath` once if ~/.local/bin isn't in PATH):
pipx install -e .

# Or using uv:
uv tool install -e .

# Optional extras (e.g., direct Gemini SDK, offline CTranslate2, or Cloud MT):
# pipx install -e ".[gemini]"
# pipx install -e ".[nmt]"
# pipx install -e ".[cloud]"

Option B: Local .venv inside the repo

If you prefer a repo-local virtualenv instead of pipx/uv:

python3 -m venv .venv
source .venv/bin/activate
pip install -e .

When using Option B, either keep that virtualenv activated before cding into your book folder, or invoke /path/to/epub-ocr-and-translate/.venv/bin/eoat directly from your book folder.


Tutorials


Choosing Local vs. Cloud (OpenRouter / Gemini)

  • OpenRouter (Fastest, Pennies per Book): Calling hosted models via OPENROUTER_API_KEY is usually much faster — an entire 13-page archival pamphlet runs end-to-end (VLM OCR + glossary + translation) for around $0.02–$0.03 on cheap models like google/gemini-3.5-flash-lite (less than a tenth of a cent per batch/page!), or $0.00 on :free models (subject to rate limits).
  • 100% Local (llama-server + Tesseract + Typst): Runs completely offline with zero API spend and total privacy — ideal if you have the hardware, time, and want everything local.

Quickstart 1: Zero-Cost Local (llama-server + Typst + EPUB)

Start your local OpenAI-compatible model server (e.g., llama.cpp's llama-server, Ollama, or LM Studio). On an 8 GB RAM machine, -c 4096 or -c 8192 avoids KV-cache swap while comfortably fitting EOAT's 3,000-char batches:

llama-server --models-dir ~/models --models-max 1 \
  -c 8192 --jinja --reasoning-budget 0 --port 8080

Tip: When running a local LLM on http://localhost:8080/v1, omit --backend and --model on eoat glossary and eoat translate — EOAT defaults to llama-server and auto-discovers your active model via /v1/models (or pass --base-url http://localhost:11434/v1 --model <name> for Ollama).

Create a separate working directory for your book (so eoat.toml, .eoat/, and dist/ don't live inside the git repo), copy your input PDF/EPUB/text file there, and run:

mkdir ~/my-book && cd ~/my-book
cp /path/to/input.pdf .

# 1. Initialize eoat.toml in this book directory (also checks/installs Tesseract + language pack if needed)
eoat init --source-lang ru --target-lang en --title "My Book" --author "Author Name" --install-ocr

# 2. Ingest PDF / EPUB / MD / TXT (auto-detects native text, garbled OCR layers, scanned pages, and OCR language)
eoat ingest input.pdf

# 3. Inspect detected sections/chapters (optional)
eoat status --chapters

# 4. Optional: extract recurring character/term glossary (skips TOC; Ctrl+C saves partial progress)
eoat glossary

# 5. Preview chunk count and $0.00 dry-run report, then translate (Ctrl+C anytime to pause & resume!)
eoat translate --dry-run
eoat translate --chapters 1     # Or omit --chapters to translate everything

# 6. Build target EPUB3 + Typst PDF, a bilingual study edition, or a re-typeset source edition
eoat build --mode target --format both
eoat build --mode bilingual --layout side-by-side --format both
eoat build --mode source --format both   # Clean EPUB/PDF of the recovered source text (great for proofing OCR!)

Deliverables are written to dist/ (book_en.epub, book_en.pdf, book_bilingual.epub, book_bilingual.pdf, book_source.epub, book_source.pdf).


Quickstart 2: OpenRouter (Free Models, Gemini, Claude, etc.) with Spend Guardrails

One OPENROUTER_API_KEY unlocks :free models as well as Gemini, Claude, Qwen, and DeepSeek, with live pricing lookup before you spend a cent. Putting the key in a local .env file (gitignored automatically) keeps secrets out of your shell history:

# Recommended: put OPENROUTER_API_KEY=... in .env using an editor (avoids saving secrets in shell history)
nano .env   # or: python3 -c "import getpass; open('.env','a').write('OPENROUTER_API_KEY='+getpass.getpass()+'\n')"
chmod 600 .env

# Discover current `:free`, vision-capable, or low-cost OpenRouter models & live prices
eoat models --free
eoat models --free --vision
eoat models --vision --search flash

# Check live token & cost estimate first
eoat translate --backend openrouter --model "google/gemini-3.8-flash" --dry-run

# Run with a hard $2.00 circuit breaker (checkpoints every batch to .eoat/segments.jsonl)
eoat translate --backend openrouter --model "google/gemini-3.8-flash" --max-cost 2.00

# Or use a free-tier model:
eoat translate --backend openrouter --model "google/gemma-4-31b-it:free"

Models whose endpoints require reasoning (such as google/gemini-3.5-flash-lite) automatically fall back cleanly from --reasoning-budget 0 with a one-time warning instead of failing with HTTP 400.

For direct Gemini PDF understanding (native multimodal PDF transcription) or Gemini translation, install the optional [gemini] extra first (pip install -e ".[gemini]"):

# Add GEMINI_API_KEY=... inside .env using your editor (keeps secrets out of shell history)
nano .env
eoat ingest scanned_book.pdf --backend gemini --max-cost 1.00
eoat translate --backend gemini --model gemini-4-hydrogen --max-cost 5.00

When Tesseract Isn't Giving Good Results (VLM / LLM OCR)

Tesseract is free and fast on modern prints, but struggles on 19th-century/archival typefaces, italic scripts, ornate page borders, low-DPI scans, dense diacritics, or mixed-script pages. eoat ingest automatically flags wrong-script legacy OCR layers on scanned PDFs and prints a tip if Tesseract output still looks noisy; when that happens, switch to a multimodal Vision LLM with a --max-cost cap:

# Option A: Page-by-page VLM OCR via OpenRouter (uses .env or OPENROUTER_API_KEY; resumes per page!)
eoat ingest scanned_book.pdf --backend openrouter --vision-model "google/gemini-3.5-flash-lite" --max-cost 0.50 --force
# Browse other vision models & live prices (`:free` tiers vary in accuracy/rate limits): `eoat models --vision`

# Option B: Full-PDF transcription in one call via direct Gemini SDK (`pip install -e ".[gemini]"`)
eoat ingest scanned_book.pdf --backend gemini --max-cost 1.00 --force

OpenRouter VLM OCR checkpoints each completed page in .eoat/ingest_pages.jsonl, so if --max-cost stops partway through or you hit Ctrl+C, re-running eoat ingest (without --force) resumes from the next page without re-paying for completed pages. (--backend gemini uploads the whole PDF in one call.)


Quickstart 3: A/B Model Testing & Eval Datasets (--run, JSONL, XML/TMX)

Ingest and build your glossary once, then compare multiple models side-by-side inside the same directory using --run <name> (isolating .eoat/runs/<name>/ and dist/<name>/ while sharing eoat.toml, .eoat/glossary.json, and ingested source segments; pass --run <name> to eoat glossary as well if you want per-run glossaries):

# Run two models in parallel against the same ingested book & glossary
eoat translate --run local-qwen --chapters 1
eoat translate --run gemini-flash --backend openrouter --model "google/gemini-3.8-flash" --chapters 1 --max-cost 0.50

# Compare completion, tokens, and spend side-by-side
eoat status

# Build separate deliverables (written to dist/<run>/)
eoat build --run gemini-flash --mode bilingual --layout side-by-side --format both

# Export aligned source/target pairs for evals, golden prompts, fine-tuning, or CAT tools
eoat export dist/eval_flash.jsonl --run gemini-flash --format golden-jsonl --min-chars 20
eoat export dist/tuning_chat.jsonl --format chat-jsonl
eoat export dist/memory.tmx --format tmx
eoat export dist/book.xml --format xml --include-untranslated

Where Your lang:lang Pairs Live (.eoat/segments.jsonl)

If you primarily want the aligned source/target strings for evals, benchmarks, or fine-tuning, every ingested and translated segment is stored directly as one JSON object per line in .eoat/segments.jsonl (and .eoat/runs/<name>/segments.jsonl for --run <name> runs):

{"id":"ch002-p0001","chapter_index":2,"chapter_title":"...","seq":1,"kind":"paragraph","page":1,"source":"...","source_lang":"hy","target":"...","target_lang":"en","backend":"openrouter","model":"google/gemini-3.5-flash-lite","input_tokens":90,"output_tokens":45,"cost_usd":0.00014}

You can inspect or filter those source / target (source_lang → target_lang) pairs straight from .eoat/segments.jsonl with Python/jq, or use eoat export above to convert them into golden-jsonl, chat-jsonl, tmx, xml, or csv.


Commands Overview

Command Purpose
eoat init Create starter eoat.toml project config (with optional --install-ocr check/download/smoke-test)
eoat ingest <file> Extract/OCR PDF, EPUB, MD, or TXT with script/garble detection, contrast cleanup, VLM OCR (--backend openrouter|gemini), --max-cost, and page checkpoints
eoat glossary Mine & extract character/term glossary (--strategy, --run, --max-cost, --dry-run, saves every chunk)
eoat translate Translate pending segments (--run, --chapters, --max-batches, --timeout, --dry-run, --max-cost, Ctrl+C resume)
eoat build Compile Typst PDF and/or EPUB3 (--run, --mode target|source|bilingual where source typesets recovered OCR text cleanly, --format, --layout, --markdown-dir)
eoat export <file> Export --run or default segments to jsonl, chat-jsonl, golden-jsonl, json, csv, xml, or tmx
eoat status Show chapter/segment completion (--chapters), named A/B runs comparison, glossary count, and spend
eoat models Browse OpenRouter models & live pricing (--vision, --free, --search, --limit, --refresh)

Docker (Slim Image, No TeX Live)

docker build -t eoat:v2 .
# Optional: include the direct Gemini SDK extra in the image
# docker build --build-arg EXTRAS="[gemini]" -t eoat:v2 .

# Run from inside an initialized book working directory (run `eoat init` first so `source_lang` is set):
docker run --rm -v "$PWD:/books" \
  -e OPENROUTER_API_KEY \
  eoat:v2 translate --backend openrouter --model "google/gemini-3.8-flash" --dry-run

# Quick OCR preflight on any mounted folder:
docker run --rm -v "$PWD:/books" eoat:v2 ingest input.pdf --dry-run

# Connecting to a local llama-server running on the host:
# - Linux: pass `--network host`
# - macOS / Windows Docker Desktop: pass `--base-url http://host.docker.internal:8080/v1`

Helper Scripts (llm-helpers/)

  • llm-helpers/gemini-process.py: Query a PDF directly using google-genai (gemini-4-hydrogen) with native PDF upload.
  • llm-helpers/create-dataset.py: CLI wrapper around eoat export for golden-prompt / tuning dataset generation.

استكشف مشاريع مشابهة ومرتبطة

جارٍ التحميل…