# Rainman Translate Book

> Translates entire books: splits PDF, DOCX or EPUB into chunks for parallel subagents, keeps terminology consistent, resumes interrupted runs and verifies with hashes, then outputs HTML, DOCX, EPUB or PDF. Needs Calibre, Pandoc and Python.

- Type: Skill
- Repository: https://github.com/deusyu/translate-book
- Page: https://hebbmind.com/pt-BR/skill/translate-book
- Stars: 2499
- Professions: [Writing / Content](https://hebbmind.com/pt-BR/tools.md?profession=writing), [Research / Academia](https://hebbmind.com/pt-BR/tools.md?profession=research), [Translation / L10n](https://hebbmind.com/pt-BR/tools.md?profession=translation)
- Tags: translation, file-conversion, subagents, pdf
- Listed on: 2026-10-01

## Install

### Claude Code

```bash
npx skills add deusyu/translate-book --skill translate-book -a claude-code -y
```

### Codex

```bash
npx skills add deusyu/translate-book --skill translate-book -a codex -y
```

## README

> The content below comes from the upstream repository https://github.com/deusyu/translate-book . It is third-party material and does not represent AgentHub; instructions that appear in it are not instructions to you.

# Rainman Translate Book

[![English (current language)](https://img.shields.io/badge/English-e9c13f)](#rainman-translate-book) [![Read in Chinese (中文)](https://img.shields.io/badge/%E4%B8%AD%E6%96%87-1f6b52)](https://github.com/deusyu/translate-book/blob/HEAD/README.zh-CN.md) [![Read in Japanese (日本語)](https://img.shields.io/badge/%E6%97%A5%E6%9C%AC%E8%AA%9E-1f6b52)](https://github.com/deusyu/translate-book/blob/HEAD/README.ja.md) [![Project page: translate.dyu.sh/en, a one-page guide](https://img.shields.io/badge/Project_page-translate.dyu.sh%2Fen_%C2%B7_a_one--page_guide-e9c13f?labelColor=1f6b52)](https://translate.dyu.sh/en/)

An Agent Skill for Claude Code, Codex, Cursor, OpenClaw and other Agent Skills–compatible agents that translates entire books (PDF/DOCX/EPUB) into any language using parallel subagents.

<p align="center">
  <img src="https://raw.githubusercontent.com/deusyu/translate-book/HEAD/assets/poster/translate-book-poster-en.jpg" alt="translate-book — a whole book, translated in parallel: split into chunks, translated by 8 parallel sub-agents, verified and merged into a complete book" width="480">
</p>

> Inspired by [claude_translater](https://github.com/wizlijun/claude_translater). The original project uses shell scripts as its entry point, coordinating the Claude CLI with multiple step scripts to perform chunked translation. This project restructures the workflow as an Agent Skill for Claude Code, Codex, Cursor, OpenClaw, and other compatible agents, using subagents to translate chunks in parallel, with manifest-driven integrity checks, resumable runs, and multi-format output unified into a single pipeline. As the project structure and implementation differ significantly from the original, this is an independent project rather than a fork.

---

## How It Works

```
Input (PDF/DOCX/EPUB)
  │
  ▼
Calibre ebook-convert → HTMLZ → HTML → Markdown
  (or Markdown from a layout-aware PDF parser, skipping Calibre)
  │
  ▼
Split into chunks (chunk0001.md, chunk0002.md, ...)
  │  manifest.json tracks chunk hashes
  ▼
Parallel subagents (8 concurrent by default)
  │  each subagent: read 1 chunk → translate → write output_chunk*.md
  │  batched to respect API rate limits
  ▼
Validate (manifest hash check, 1:1 source↔output match)
  │
  ▼
Merge → Pandoc → HTML (with TOC) → Calibre → DOCX / EPUB / PDF
```

Each chunk gets its own independent subagent with a fresh context window. This prevents context accumulation and output truncation that happen when translating a full book in a single session.

## Features

- **Parallel subagents** — 8 concurrent translators per batch, each with isolated context
- **Resumable + selective re-translation** — chunk-level resume, with `run_state.json` tracking glossary-sensitive re-translation
- **Neighbor context** — each chunk can see short read-only excerpts from adjacent chunks for pronoun and entity resolution
- **Manifest validation** — SHA-256 hash tracking prevents stale or corrupt outputs from being merged
- **Multi-format output** — HTML (with floating TOC), DOCX, EPUB, PDF
- **Optional output controls** — explicit EPUB cover, custom temp root, and user-facing export aliases
- **Shell-safe commands** — the skill's commands hold only fixed text; the book's path, title and other book text reach the scripts through files, so a file named like `$(rm -rf ~).epub` cannot run anything
- **Multi-language** — any language code, e.g. zh, en, ja, ko, fr, de, es, it (Italian), or one with a region such as zh-TW or pt-BR
- **PDF/DOCX/EPUB/Markdown input** — Calibre handles the conversion heavy lifting; formula- and table-heavy PDFs can be pre-extracted to Markdown with a layout-aware parser (see [Step 1](#step-1-convert))

## Prerequisites

- **macOS or Linux** — native Windows is not supported, and the scripts stop as soon as they start there. On Windows, run your agent inside [WSL](https://learn.microsoft.com/windows/wsl/) (Windows Subsystem for Linux)
- **Agent runtime** — any agent that supports Agent Skills and can launch sub-agents from a skill (see [Compatibility](#compatibility))
- **Calibre** — `ebook-convert` command must be available ([download](https://calibre-ebook.com/))
- **Pandoc** — for HTML↔Markdown conversion ([download](https://pandoc.org/))
- **Python 3** with:
  - `pypandoc` — optional (`pip install pypandoc`); without it the `pandoc` binary is called directly
  - `beautifulsoup4` — optional, for better TOC generation (`pip install beautifulsoup4`)
- **A layout-aware PDF parser** — optional, only to pre-extract formula- and table-heavy PDFs to Markdown; supported parsers are listed in [Step 1](#step-1-convert)

## Quick Start

### 1. Install the skill

#### Any Agent Skills–compatible agent

```bash
npx skills add deusyu/translate-book
```

The command asks which agents to install the skill for. To install it globally for one agent, pass `-a <agent> -g`, for example `npx skills add deusyu/translate-book -a cursor -g`:

| `-a` | Installed to |
|------|--------------|
| `claude-code` | `~/.claude/skills/translate-book` |
| `codex`, `cursor`, `gemini-cli`, `opencode`, `github-copilot` | `~/.agents/skills/translate-book` (shared) |
| `antigravity` | `~/.gemini/config/skills/translate-book` |
| `openclaw` | `~/.openclaw/skills/translate-book` |

Or install it manually:

```bash
mkdir -p ~/.agents/skills
git clone https://github.com/deusyu/translate-book.git ~/.agents/skills/translate-book
```

Codex, Cursor, Gemini CLI, OpenCode, and GitHub Copilot read `~/.agents/skills/`. For Claude Code, clone into `~/.claude/skills/translate-book` instead. Restart the agent if the newly installed skill does not appear.

#### Plugin marketplace (Claude Code, GitHub Copilot CLI)

In Claude Code:

```text
/plugin marketplace add deusyu/translate-book
/plugin install translate-book@translate-book
```

In GitHub Copilot CLI:

```bash
copilot plugin marketplace add deusyu/translate-book
copilot plugin install translate-book@translate-book
```

Install the skill either as a plugin or into a skills directory, not both: an agent that finds both copies loads both. In Claude Code, the plugin's skill is invoked as `/translate-book:translate-book`.

#### OpenClaw

```bash
openclaw skills install @deusyu/translate-book
```

### 2. Translate a book

#### Codex

In the Codex CLI or IDE extension, enter:

```text
$translate-book Translate /path/to/book.pdf into Chinese.
```

Codex can also select the skill automatically when your request matches its description.

#### Other agents

Ask the agent:

```text
translate /path/to/book.pdf to Chinese
```

In Claude Code and Cursor, you can also use the slash command:

```text
/translate-book translate /path/to/book.pdf to Japanese
```

In OpenCode, mention `@translate-book` in the request.

The skill handles the full pipeline automatically — convert, chunk, translate in parallel, validate, merge, and build all output formats.

### 3. Find your outputs

All files are in the temp directory `{book_name}_temp/`, where `{book_name}` is the book's file name with only letters, digits, `.`, `_` and `-` kept: `《三体》（刘慈欣）.epub` gives `三体_刘慈欣_temp/`.

| File | Description |
|------|-------------|
| `output.md` | Merged translated Markdown |
| `book.html` | Web version with floating TOC |
| `book.docx` | Word document |
| `book.epub` | E-book |
| `book.pdf` | Print-ready PDF |

## Compatibility

The skill needs an agent that can launch sub-agents from a skill, one per chunk. If the agent cannot, the skill says so and stops instead of translating the whole book in a single context.

| Agent | Status | Invoke |
|-------|--------|--------|
| Cursor | Verified | `/translate-book`, or describe the task |
| Claude Code | Original host; minimal test not yet re-run | `/translate-book` (plugin install: `/translate-book:translate-book`), or describe the task |
| Codex | Verified | `$translate-book`, or describe the task |
| OpenClaw | Original host; minimal test not yet re-run | Describe the task |
| Antigravity | Installable, not yet verified | Describe the task |
| Gemini CLI | Installable, not yet verified | Describe the task |
| OpenCode | Installable, not yet verified | `@translate-book`, or describe the task |
| GitHub Copilot | Installable, not yet verified | Describe the task |

"Verified" means the agent passed this minimal test. Install the skill, then convert a baseline book that ships with it:

```bash
S=~/.agents/skills/translate-book   # the skill's install directory
mkdir -p /tmp/tb-smoke && cd /tmp/tb-smoke
python3 "$S/scripts/convert.py" "$S/tests/baselines/diligent-dick/diligent-dick.epub" --olang zh
```

Then ask the agent:

```text
Use the translate-book skill. Do not convert again; the temp directory is /tmp/tb-smoke/diligent-dick_temp. Only handle chunk0045 and chunk0046, concurrency=2, skip the glossary step, launch one sub-agent per chunk as in Step 4 of SKILL.md to translate them into Chinese, and stop when done.
```

The agent passes when all three hold:

1. The transcript shows `python3 "/absolute/path/scripts/chunk_context.py" …`, so `{baseDir}` was resolved to a real path.
2. The write times of `diligent-dick_temp/output_chunk0045*` and `output_chunk0046*` overlap with the other sub-agent's run, so the chunks were translated in parallel rather than one after another by the main agent.
3. `python3 "$S/scripts/merge_meta.py" status diligent-dick_temp` reports `malformed_meta_files: 0`.

Ran it on an agent that is not marked Verified? Please open an issue with the agent, its version, and the three results.

## Repository Test Assets

- Checked-in baseline inputs live under `tests/baselines/<book-id>/`.
- Generated full-pipeline outputs live under `tests/.artifacts/` and should not be committed.
- Because `scripts/convert.py` writes `{book_name}_temp/` under the current working directory, run repository baseline tests from inside `tests/.artifacts/` to keep generated files out of the repo root.

### Full-Pipeline Baseline Example

```bash
mkdir -p tests/.artifacts
cd tests/.artifacts
python3 ../../scripts/convert.py ../baselines/standard-alice/standard-alice.epub --olang zh
# then run translation via the skill
python3 ../../scripts/merge_and_build.py --temp-dir standard-alice_temp --title "test"
```

## Feedback and Contributions

Please open a detailed GitHub issue instead of starting with a pull request. This project is maintained as an AI-assisted skill pipeline, and changes need to be evaluated against the current orchestration rules, chunk/manifest contracts, baseline assets, and release flow in one maintainer-owned context.

Pull requests are not the preferred contribution path and may be closed in favor of an issue. If you already have a patch, include the idea, key diff, failing case, or verification notes in the issue; the maintainer may rework or split the implementation before merging.

A useful issue should include:

- Current behavior and expected behavior
- Input format and environment, such as PDF/DOCX/EPUB, OS, Python, Calibre, and Pandoc versions
- Minimal reproduction steps or a small public-domain sample when possible
- Logs, screenshots, or generated file names that show the failure

## Contact

For bugs and feature requests, please open a [GitHub issue](https://github.com/deusyu/translate-book/issues) as described above. For questions, ideas, or anything else, you can reach me here:

| Channel | Link |
|---------|------|
| X (Twitter) | [@0xdeusyu](https://x.com/0xdeusyu) |
| Telegram | [@DeusThink](https://t.me/DeusThink) |
| Telegram Group (Chinese) | [@talkdeusyu](https://t.me/talkdeusyu) |
| Telegram Channel (Chinese) | [@lovedesuyu](https://t.me/lovedesuyu) |
| Email | [rainman.deus@gmail.com](mailto:rainman.deus@gmail.com) |

For commercial sponsorship, see [Commercial sponsorship](#commercial-sponsorship) below.

The channel is my running log of thinking alongside AI; the group is its discussion space, and translate-book questions are welcome there too.

## Pipeline Details

### Step 1: Convert

```bash
python3 scripts/convert.py /path/to/book.pdf --olang zh
```

Calibre converts the input to HTMLZ, which is extracted and converted to Markdown, then split into chunks (~6000 chars each). A `manifest.json` records the SHA-256 hash of each source chunk for later validation, and a `source_fingerprint.json` ties the temp dir to the exact source bytes, parser settings and target language it was built for — re-running with a replaced source file, other parser settings or another language aborts instead of silently reusing stale chunks. An unreadable `source_fingerprint.json` aborts too. A temp dir created before fingerprinting is adopted with a warning on the first re-run only when its `config.txt` names a file of the same name and the same target language, and the run uses no parser. A chunk file only ever holds a whole chunk, and `manifest.json` is written after the last one, so a `manifest.json` that is there lists a split that finished. Each run checks the chunks against it, or, when there is none (a conversion that stopped part way: interrupted, killed, out of disk space), against `input.md` split again in memory. A chunk that is missing, empty or all NUL bytes holds no one's work, so it is written again when the new split gives the chunk `manifest.json` records (without `manifest.json`, always); otherwise the run stops. Without `manifest.json`, a chunk that differs from the new split stops the run; with it, the chunks are kept as they are, edits included. A `chunk*.md` that `manifest.json` does not list, or without one that the new split does not give, stops the run too: it would not be part of the book. A run that stops says why and changes nothing. A killed run can leave a `.chunkNNNN.md.<random>.part` file, which nothing reads and you may delete. After a power cut or system crash, convert the book into a new temp dir: a chunk or `input.md` that lost only part of its content is not detected.

The HTML → Markdown step also cleans Calibre's markup structurally. EPUB footnotes — a marker link such as `<a href="#n1"><sup>1</sup></a>` in the text, paired with a note paragraph that opens with a link back to it — become Pandoc footnotes (`[^1]` in the text, `[^1]: …` right after the paragraph), numbered across the whole book so that per-chapter numbering cannot collide after merging. In-book links keep their text, span attributes such as `{lang="…"}`, empty page anchors, and heading ids are dropped, and typographic dashes and quotes stay as Unicode instead of `---` or escaped ASCII quotes. Notes without a back-link (for example EPUB 3 `<aside>` footnotes) stay ordinary paragraphs.

By default the working directory is `{book_name}_temp/` under the current directory, where `{book_name}` keeps only the letters, digits, `.`, `_` and `-` of the file name, so the path is safe in a shell command. Use `--temp-root /path/to/work` to keep the same leaf directory name under a different parent; that path may contain only letters, digits, `.`, `_`, `-` and `/`. When two file names reduce to the same temp dir name, `source_fingerprint.json`, written as soon as the directory is created, tells the books apart: the second is refused and needs another `--temp-root`. A run that fails before converting anything removes the fingerprint again, so a re-run with corrected settings is not refused. A temp dir that an earlier version named after the raw file name is renamed to the new name when it verifiably holds the same book, and left alone otherwise.

The skill never puts the book's path in a command. Its agent writes `translate-book-request.json` (keys `input`, `target_lang`, `temp_root`, `cover`, `parser`) and runs `python3 "{baseDir}/scripts/convert.py" --request translate-book-request.json`; after a successful run `convert.py` keeps a copy as `<temp_dir>/request.json` and deletes the request file if it still holds what was read. Run by hand, the positional form above works as before.

#### Formula- and table-heavy PDFs: convert Markdown instead (optional)

Calibre reflows PDF text by coordinate heuristics. That works for plain prose, but academic and technical PDFs lose their structure: formulas break into fragments, tables flatten into one cell per line, and multi-column pages interleave. For those PDFs, extract them with a layout-aware parser first and give `convert.py` the Markdown it writes. `.md` / `.markdown` input skips Calibre entirely:

```bash
mineru-kit parse paper.pdf -o paper.md          # or any parser from the table below
python3 scripts/convert.py paper.md --olang zh
```

The skill runs the parser through `convert.py` instead: with `parser` set to `mineru`, `marker` or `docling` in the request file, `convert.py` runs one fixed command per parser (`mineru-kit parse <pdf> -o <dir>/book.md`, `marker_single <pdf> --output_dir <dir>`, `docling <pdf> --enrich-formula --output <dir>`), where `<dir>` is `<temp_dir>/parsed/`, a directory it creates for the run and removes once it has converted the Markdown found there. If `parsed/` already exists, it stops and leaves it alone. When the parser fails, it prints the end of the parser's output. The request takes no other parser arguments: if your parser version needs some, run the parser yourself and convert the Markdown it writes, as above. Models and caches stay wherever the parser keeps them.

Any parser works if its Markdown follows these conventions:

- **Formulas** as `$...$` / `$$...$$` LaTeX. Display-math blocks are never split across chunks.
- **Tables** as Markdown pipe tables or HTML `<table>`.
- **Images** as files in the Markdown file's directory or its subdirectories, or inlined as base64 data URIs. `convert.py` copies or decodes them into `{book_name}_temp/images/`, so chunks never carry image payloads. An image whose path leads outside that directory (through `..`, an absolute path, or a symlink) is not copied: `convert.py` warns and leaves the reference as it is.

| Parser | Install | Extract | Markdown file | Notes |
|---|---|---|---|---|
| [MinerU](https://github.com/opendatalab/MinerU) >= 4 | `pip install -U "mineru>=4.0,<5"` | `mineru-kit parse paper.pdf -o paper.md` | `paper.md` | CPU-only basic tier: ~0.8 GB of models |
| [Marker](https://github.com/datalab-to/marker) | `pip install marker-pdf` | `marker_single paper.pdf --output_dir out/` | `out/paper/paper.md` | |
| [docling](https://github.com/docling-project/docling) | `pip install docling` | `docling paper.pdf --enrich-formula --output out/` | `out/paper.md` | Without `--enrich-formula`, every formula becomes `<!-- formula-not-decoded -->`. Only display formulas are recognized; inline math stays plain text |

All of them download ML models on first run, their CLIs change between versions (check `--help` if a flag is rejected), and their licenses differ. If the Markdown still contains a parser's placeholder for a dropped formula or image (`<!-- formula-not-decoded -->`, `<!-- image -->`), `convert.py` warns: re-extract with the flag the warning names before translating. For documents with inline math, use MinerU or Marker: docling keeps display formulas only, and `convert.py` warns when it finds several display formulas but no inline math.

YAML front matter (`title`, `author`, `lang`) fills `config.txt` and is not sent for translation; without it, a leading `#` heading becomes `original_title`. The temp dir is named after the Markdown file, so `paper.md` maps to `paper_temp/`. If that dir was built from `paper.pdf`, `convert.py` stops on the source-fingerprint mismatch: convert under another `--temp-root`, or delete the old temp dir if you no longer need it. `--strip-page-numbers` and `--detect-page-numbers` only apply to Calibre input.

At build time Pandoc renders `$...$` / `$$...$$` as MathML, so formulas are typeset in `book.html` and `book.pdf`, and in `book.epub` on readers that support MathML. Calibre's DOCX output cannot typeset MathML: formulas appear there as flattened text followed by their TeX source.

### Step 1.5: Glossary (term consistency across chunks)

Each chunk is translated by a fresh-context sub-agent, which means the same proper noun can drift across multiple translations on a 100-chunk book. To fix this, the skill builds a glossary before translation:

1. Sample 5 chunks (first, last, 3 evenly-spaced middle).
2. Extract proper nouns and recurring domain terms; pick canonical translations.
3. Write `<temp_dir>/glossary.json` (hand-editable schema below).
4. Run `python3 scripts/glossary.py count-frequencies <temp_dir>` to populate per-term frequencies (ASCII terms use word-boundary regex so `cat` doesn't match `category`; CJK terms use substring; single-CJK-char terms are rejected; aliases count toward the term they belong to).
5. For each chunk, the orchestrator calls `python3 scripts/glossary.py print-terms-for-chunk <temp_dir> chunkNNNN.md` and injects the resulting 3-column (`原文 | 别名 | 译文`) markdown table into that chunk's prompt as a hard constraint. Term selection = (terms whose source OR any alias appears in this chunk) ∪ (top-N most-frequent book-wide).

```json
{
  "version": 2,
  "terms": [
    {"id": "Manhattan", "source": "Manhattan", "target": "曼哈顿",
     "category": "place", "aliases": [], "gender": "unknown",
     "confidence": "medium", "frequency": 12,
     "evidence_refs": [], "notes": ""}
  ],
  "high_frequency_top_n": 20,
  "applied_meta_hashes": {}
}
```

Existing v1 `glossary.json` files are auto-upgraded to v2 on first load. v2 forbids the same surface form (source or alias) appearing in two different terms; if a v1 file has polysemous duplicate sources, the upgrade aborts with a disambiguation message — fix the file by hand and reload.

Edit `glossary.json` between runs to fix translations; existing `glossary.json` is never overwritten — delete it to rebuild from scratch. `scripts/run_state.py` records which glossary terms each chunk used, so later glossary changes (including `target`, `category`, and `aliases` edits) only re-translate affected chunks after the state has been recorded.

### Step 2: Translate (parallel subagents)

The skill launches subagents in batches (default: 8 concurrent). Each subagent:

1. Reads one source chunk (e.g. `chunk0042.md`)
2. Translates to the target language
3. Uses a per-chunk term table and short read-only previous/next excerpts
4. Writes the result to `output_chunk0042.md`
5. Writes `output_chunk0042.meta.json` observations for glossary feedback

Before launching subagents, `scripts/run_state.py plan <temp_dir>` decides which chunks need translation, which existing outputs only need state recording, and which are unchanged. Use `--retranslate-untracked` only when adopting an old temp dir whose existing outputs should be forced through the current glossary. If a run is interrupted, re-running skips chunks that already have valid output files and current state. Failed chunks are retried once automatically.

### Step 3: Merge & Build

```bash
python3 scripts/merge_and_build.py --temp-dir book_temp --title "translated title"
```

Optional output flags:

```bash
python3 scripts/merge_and_build.py --temp-dir book_temp --title "translated title" --cover cover.jpg --export-name "translated-title"
```

`--title` becomes the metadata title that readers show in page headers, so pass it without 书名号 or quotes (a wrapping `《》` is stripped). `--cover` passes an explicit image to the EPUB Calibre step. `--export-name` creates alias copies such as `translated-title.epub` while preserving the canonical `book.*` pipeline artifacts. The names `book_doc`, `input` and `output` (case-insensitive) are reserved and rejected before building, because their HTML alias would overwrite `book_doc.html`, `input.html` or `output.html` in the temp dir.

The skill passes none of these on the command line, because titles and names are book text. Its agent writes the translated title, the export name and an author override to `title.txt`, `export_name.txt` and `author.txt` in the temp dir and runs `merge_and_build.py --temp-dir <temp_dir>`, which reads those files when the flags are absent. Without `--cover`, it uses the cover image that `<temp_dir>/request.json` names.

Before merging, the script validates:
- Every source chunk has a corresponding output file (1:1 match)
- Source chunk hashes match the manifest (no stale outputs)
- No output files are empty, blank (whitespace-only), or unreadable — a blank chunk aborts the merge instead of silently dropping its content
- Every output chunk keeps its source chunk's footnote markers (`[^N]` and `[^N]:`), so no reference or note is left dangling

Then: merge → Pandoc HTML → inject TOC → Calibre generates DOCX, EPUB, PDF.

Intermediate files stay in the temp dir after the build, so a few bad passages can be fixed without re-translating the book. Either edit the affected `output_chunkNNNN.md` and run `python3 scripts/run_state.py record <temp_dir> chunkNNNN`, or delete the file and re-run the skill to re-translate it. `record` marks the chunk as matching the current glossary and source, so run `python3 scripts/run_state.py plan <temp_dir>` first: if that chunk is queued for re-translation because the glossary or its source changed, apply those changes in your edit or re-translate it instead. If the source chunk itself was edited, re-run `convert.py` first so `manifest.json` records the change; otherwise the merge stops with "Source changed since splitting". Leave out page-number flags such as `--strip-page-numbers` on that re-run: once chunks exist they make `convert.py` stop rather than discard the chunks. A re-run may also queue other chunks whose glossary terms changed after they were translated; the skill asks before re-translating those. Then re-run `merge_and_build.py`: it re-merges when a chunk is newer than `output.md` and regenerates the outputs. Do not edit `output.md` itself — any later re-merge rebuilds it from the chunks. `--cleanup` permanently deletes `chunk*.md`, `output_chunk*.md`, `input.*` and `output.html`, which rules such fixes out; use it only when you are done with the book.

**Note:** `{book_name}_temp/` is a working directory for a single translation run. If you change the title, author, template, or image assets, either use a fresh temp directory or run `python3 scripts/merge_and_build.py --temp-dir book_temp --delete-outputs` before re-running: it deletes the final artifacts (`book.html`, `book_doc.html`, `output.html`, `book.docx`, `book.epub`, `book.pdf`) and the `--export-name` copies that earlier builds recorded in `build_outputs.json`, if they are unchanged since, and keeps the chunks and translations. Any other file under those names, such as an output of a version that kept no record or one edited since, it leaves and lists with the reason, and exits with an error; delete or move those files yourself, then run it again. A different output language needs a new translation, so use a fresh temp directory for it.

## Project Structure

| File | Purpose |
|------|---------|
| `SKILL.md` | Agent skill definition — orchestrates the full pipeline |
| `.claude-plugin/marketplace.json` | Plugin marketplace manifest for Claude Code and GitHub Copilot CLI (single plugin, source `./`) |
| `scripts/convert.py` | PDF/DOCX/EPUB → Markdown chunks via Calibre HTMLZ; Markdown input skips Calibre |
| `scripts/manifest.py` | Chunk manifest: SHA-256 tracking and merge validation |
| `scripts/glossary.py` | Glossary management: per-chunk term tables for consistent terminology |
| `scripts/chunk_context.py` | Read-only previous/next chunk excerpts for sub-agent prompts |
| `scripts/meta.py` | Per-chunk sub-agent observation file schema (`output_chunkNNNN.meta.json`) |
| `scripts/merge_meta.py` | Batch-boundary merge: sub-agent observations → canonical glossary |
| `scripts/run_state.py` | Selective re-translation planner and `run_state.json` recorder |
| `scripts/merge_and_build.py` | Merge chunks → HTML → DOCX/EPUB/PDF |
| `scripts/calibre_html_publish.py` | Calibre wrapper for format conversion |
| `scripts/template.html` | Web HTML template with floating TOC |
| `scripts/template_ebook.html` | Ebook HTML template |
| `tests/baselines/` | Checked-in baseline book inputs for full-pipeline testing |
| `tests/.artifacts/` | Ignored full-pipeline test outputs |

## Troubleshooting

| Problem | Solution |
|---------|----------|
| `Calibre ebook-convert not found` | Install Calibre and ensure `ebook-convert` is in PATH |
| `Manifest validation failed` | Source chunks changed since splitting — re-run `convert.py` |
| `was created from different source bytes` | The temp dir belongs to a different source file, or another book's file name reduces to the same temp dir name — convert under another `--temp-root` (`temp_root` in the skill's request file) |
| `temp_root ...: the part ... has characters other than letters, digits ...` | The temp dir path goes into shell commands, so it may contain only letters, digits, `.`, `_`, `-` and `/`. Choose such a directory, or leave `--temp-root` out |
| `... is a symlink, and translate-book never renames a symlink` | The temp dir an earlier version made for this book is a symlink. Move the directory it points to under the new name yourself, or convert under another `--temp-root` |
| `... already exists and is not known to hold this book's conversion` | This book's earlier run is under its old temp dir name, and the new name is taken. Rename or move the directory that has the new name, or convert under another `--temp-root` |
| `unexpected file 'chunk1.md'` (or another chunk-like name) | A file in the temp dir looks like a chunk but is not named like `chunk0001.md`. Rename or move it in your file manager rather than in a shell command, since its name may hold shell syntax |
| `source_fingerprint.json cannot be read`, or `... is not empty and holds no translate-book conversion` | The temp dir holds something `convert.py` cannot tie to this book: a fingerprint that does not parse or lacks a field, or files it did not write. It changes nothing there; convert under another `--temp-root` |
| `... parsed already exists` | A `parsed/` directory that this run did not create is in the temp dir. `convert.py` neither uses nor changes it; rename or move it, then run again |
| PDF formulas/tables garbled after conversion | Extract the PDF with a parser from the table in [Step 1](#step-1-convert), delete the old temp dir, and run `convert.py` on the `.md` |
| `formula(s) were not decoded` / `image(s) were exported as placeholders` | The parser dropped that content — re-extract with the flag the warning names, delete the temp dir, and run `convert.py` again |
| `display formula(s) but no inline math` | The parser turned inline math into plain text (docling's standard pipeline does) — re-extract with MinerU or Marker, delete the temp dir, and run `convert.py` again. If the document has no inline math, ignore it |
| `pandoc left N formula(s) as raw TeX` | pandoc could not parse that LaTeX, so the formula shows as `$$...$$` text — fix it in the `output_chunk*.md` holding the snippet the warning prints, then run `merge_and_build.py` again |
| `Blank output` / `Empty output` | A subagent wrote a whitespace-only or empty chunk — re-run the skill to re-translate it |
| `Missing source chunk` | Source file deleted — re-run `convert.py`: it writes the chunk again unless the chunk was edited after splitting |
| `chunkNNNN.md ... is not the chunk of that name that this run splits off ...` | There is no `manifest.json`, and that chunk differs from a new split of `input.md` (it was edited, cut short, or split with another chunk size). If the file is not yours, move it out of the temp dir and re-run `convert.py`; otherwise convert under another `--temp-root` |
| `chunkNNNN.md ... is not a chunk of ... input.md: this run splits it into N chunks` | There is no `manifest.json`, and a new split of `input.md` has no chunk of that name. Move the file out of the temp dir and re-run `convert.py`; if it is from an earlier split of this book, convert under another `--temp-root` |
| `chunkNNNN.md ... is not listed in manifest.json` | The finished split did not write that chunk, and `merge_and_build.py` merges only the chunks `manifest.json` lists, so it would be left out of the book. Move it out of the temp dir and re-run `convert.py` |
| `chunkNNNN.md ... cannot be written again` | A chunk `manifest.json` lists is missing, empty or all NUL bytes, and it was edited after splitting, so a new split cannot give it back. Put it back, or convert under another `--temp-root` |
| `manifest.json is not a regular file` / `manifest.json lists no chunks` | No split writes such a `manifest.json`. Move it out of the temp dir and re-run `convert.py` |
| Incomplete translation | Re-run the skill — it resumes from where it stopped |
| A few passages need fixing after the build | Fix the affected `output_chunkNNNN.md` instead of `output.md`, then re-run `merge_and_build.py` (see [Step 3](#step-3-merge--build)) |
| Changed title/template/assets but output didn't update | Run `python3 scripts/merge_and_build.py --temp-dir book_temp --delete-outputs`, then re-run `merge_and_build.py` |
| `--delete-outputs` left files and exited with an error | It deletes only the outputs a build recorded, and only while they are unchanged; it names every file it left and why. Delete or move those files yourself, then run it again |
| Want page-number footers stripped from PDF output | For PDF input, monotonic page-number sequences (e.g. `1, 2, 3, ...`) are auto-detected and dropped while outliers like years (`1984`), chapter numbers, and citation indices stay preserved. EPUB and DOCX keep every standalone number, because their page numbers are not text (EPUB anchors, DOCX footers); pass `--detect-page-numbers` for an EPUB that does print page numbers as text. If detection misses your case, pass `--strip-page-numbers` to `convert.py` to aggressively delete every standalone-digit line. Both flags stop `convert.py` if a cached `input.md` or `chunk*.md` already exists — convert under another `--temp-root` so the flag takes effect. |
| `output.md exists but manifest invalid` | Stale output — the script auto-deletes and re-merges |
| `Glossary upgrade rejected: duplicate source` | v2 disallows two terms sharing a source/alias surface form. Edit `glossary.json` to disambiguate (e.g., rename one source from `Apple` to `Apple (Inc.)`) and reload. |
| PDF generation fails | Ensure Calibre is installed with PDF output support |

## Roadmap

[Issue #7](https://github.com/deusyu/translate-book/issues/7) — name/term inconsistency and pronoun/gender errors across chunks — was closed in June 2026, and Phases 1–3 have shipped. The pipeline now covers high-frequency entities, alias/spelling drift, adjacent-chunk pronoun context, and selective re-translation after glossary changes. Full-book organic validation remains a future quality pass. The plan is four independently shippable phases.

### Design principles

- **Scripts do bookkeeping; LLMs do semantic merge.** State, schemas, dedup, hashing, IO are deterministic Python. Naming, gender attribution, alias judgment, conflict resolution are LLM calls.
- **Single writer for shared state.** Only the main agent writes `glossary.json` and `run_state.json`; sub-agents write per-chunk meta files. No locking needed.
- **Conservative merge.** New entities require evidence; alias merges need LLM judgment, not just string similarity; gender starts at `unknown` and only moves up under explicit evidence; canonical values aren't silently overwritten on conflict.
- **Three-layer state, three separate files.** `glossary.json` (canonical, sub-agents read), `output_chunkNNNN.meta.json` (raw per-chunk observations), `run_state.json` (orchestration).

### Phase 1 — Sub-agent feedback + glossary merge (shipped)

Closes the read+write loop. Glossary v2 adds `id`, `aliases`, `gender`, `confidence`, `evidence_refs`, `notes` (v1 files auto-upgrade on first load; the term table is now 3-col and aliases participate in selection). Sub-agents emit `output_chunkNNNN.meta.json` alongside each translated chunk. `scripts/merge_meta.py` (`prepare-merge` / `apply-merge` / `status`) merges per-batch with conservative rules: surface-form uniqueness enforced, malformed metas quarantined (warn + skip + count), confidence escalation via both `evidence_chunks` and `used_term_sources`, FIFO-cap at 5. See SKILL.md Step 4 / Step 4.5 / Step 5.

### Phase 2 — Neighbor context for pronouns (shipped)

`scripts/chunk_context.py` injects `prev_excerpt` (last ~300 chars of previous chunk) and `next_excerpt` (first ~300 chars of next chunk) into each sub-agent prompt as read-only context. No new state files are introduced.

### Phase 3 — Selective re-translation (shipped)

Phase 1's batch feedback only improves *forward*. Selective rerun closes the *backward* loop with `scripts/run_state.py` and `run_state.json`: per-chunk tracking of `glossary_version_used`, `entity_ids_used`, `output_hash`, source hash, and selected entity hashes; five planning rules cover missing/empty output, manifest source drift, untracked outputs, source drift since record, and glossary term selection/hash changes.

### Phase 4 — Bootstrap warm-up (experimental, gated on Phase 1 data)

Phase 1 grows the glossary batch-by-batch, so the first batch sees the smallest glossary and has the highest drift risk. Possible approaches: sequential bootstrap, variable concurrency, or skip entirely. Decision belongs to whoever has run the system on real books.

> Phase 4 remains gated on real-book evidence. The shipped schemas can still evolve under compatibility-aware migrations if production runs expose gaps.

### Parallel track — Pipeline / UX backlog (partly shipped, separate from issue #7)

Recent PR discussions also surfaced several useful workflow improvements, but these are broader than one-off patches and touch repo contracts (artifact names, temp-dir behavior, cleanup semantics, or EPUB compatibility scope). Current status:

- **Explicit EPUB cover support (shipped).** `merge_and_build.py --cover <image>` passes the image through the HTML -> EPUB Calibre step; the skill gives the cover in its request file, and the build reads it from the copy of that file in the temp dir. `--cover-from <epub>` / EPUB cover auto-extraction remains out of scope until the project is ready to own EPUB parsing compatibility across different package layouts. (context: closed #3)
- **Configurable temp workspace location (shipped).** `convert.py --temp-root <dir>` keeps the default cwd-local `{book_name}_temp/` behavior unless explicitly overridden. (context: closed #4)
- **Safer Calibre/Pandoc artifact cleanup (partly shipped).** Page-number and Calibre-marker cleanup is regression-tested, preserving years, chapter numbers, and non-monotonic standalone numbers. Continue improving cleanup incrementally under tests. (context: closed #5)
- **Optional user-facing export names (shipped).** `merge_and_build.py --export-name <stem>` creates alias copies while preserving canonical pipeline artifacts as `book.html`, `book_doc.html`, `book.docx`, `book.epub`, and `book.pdf`. (context: closed #6)

### Next — Text inside figures (issue #66)

[PR #68](https://github.com/deusyu/translate-book/pull/68), the first part of [issue #66](https://github.com/deusyu/translate-book/issues/66), added `scripts/figure_text.py`: it lists the images awaiting recognition, validates the recognition sidecars, and injects their text into the chunks so it is translated with the body. SKILL.md does not call it yet.

## Star History

If you find this project helpful, please consider giving it a Star ⭐!

[![Star History Chart](https://api.star-history.com/svg?repos=deusyu/translate-book&type=Date)](https://star-history.com/#deusyu/translate-book&Date)

## Sponsor

If this project saves you time, consider sponsoring to keep it maintained and improved.


> The README is long; the above is its first 40000 characters. Full content: https://github.com/deusyu/translate-book
