translate-book Skill
使用并行子代理将书籍(PDF/DOCX/EPUB)翻译成任意语言。流程:输入 -> Markdown 分块 -> 翻译分块 -> HTML/DOCX/EPUB/PDF。
安装方式:把技能目录放入 ~/.claude/skills/(Claude Code)或在 claude.ai 设置中启用;也可复制右侧安装命令一键添加。
技能指令原文(SKILL.md)
Book Translation Skill
You are a book translation assistant. You translate entire books from one language to another by orchestrating a multi-step pipeline.
Workflow
1. Collect Parameters
Determine the following from the user's message:
- file_path: Path to the input file (PDF, DOCX, EPUB, or Markdown) — REQUIRED
- target_lang: Target language code (default:
zh) — e.g. zh, en, ja, ko, fr, de, es - concurrency: Number of parallel sub-agents per batch (default:
8) - temp_root: Optional directory under which
{filename}_temp/should be created - epub_cover: Optional explicit cover image path for EPUB output
- export_name: Optional filename stem for user-facing output aliases
- custom_instructions: Any additional translation instructions from the user (optional)
If the file path is not provided, ask the user.
2. Preprocess — Convert to Markdown Chunks
Run the conversion script to produce chunks:
python3 {baseDir}/scripts/convert.py "<file_path>" --olang "<target_lang>"
If the user provided temp_root, add --temp-root "". The temp
directory leaf name remains {filename}_temp/; only the parent directory
changes.
For PDFs, Calibre reflows text by coordinate heuristics, which shatters math
formulas, flattens tables, and interleaves multi-column layouts before
translation starts. If the PDF is an academic or technical document and a
layout-aware parser is already installed — or the user asks for one — extract
the PDF with it first, then pass the resulting Markdown file to convert.py
instead of the PDF. Markdown input (.md / .markdown) skips Calibre:
- MinerU >= 4:
mineru-kit parse "" -o ".md" - Marker:
marker_single "" --output_dir "", then use//.md
Keep the PDF's file name stem for the Markdown file, because the temp
directory is named after it. These CLIs change between versions; check the
parser's --help if a flag is rejected. Do not install a parser without the
user's consent, because they download large models. Images next to the
Markdown file and base64 images inlined in it are copied into the temp
directory. --strip-page-numbers does not apply to Markdown input.
Page-number lines are detected and dropped for PDF input only; EPUB and DOCX
keep every standalone number (chapter, verse or exercise numbers). If an EPUB
prints its page numbers as text and they show up in the chunks, delete the
temp directory before translating and re-run with --detect-page-numbers.
This creates a {filename}_temp/ directory containing:
input.html(Calibre input only),input.md— intermediate fileschunk0001.md,chunk0002.md, ... — source chunks for translationmanifest.json— chunk manifest for tracking and validationsource_fingerprint.json— SHA-256 identity of the source bytes this temp dir was built fromconfig.txt— pipeline configuration with metadata
If convert.py aborts because the temp dir was created from different source
bytes, do not reuse it — delete the temp directory or pass a fresh
--temp-root, then re-run. Temp dirs created before fingerprinting existed
are adopted with a warning and fingerprinted on the next successful run.
3. Discover Source Chunks
Use Glob to find all source chunks:
Glob: {filename}_temp/chunk*.md
Exclude output_chunk*.md from the source list. The selective re-translation
plan below decides which chunks actually need work.
3.5. Build Glossary (term consistency)
A separate sub-agent translates each chunk with a fresh context. Without shared state, the same proper noun can drift across multiple translations. The glossary makes every sub-agent see the same canonical translation for the terms that appear in its chunk.
If /glossary.json already exists, skip the rebuild — re-running the skill must not overwrite a hand-edited glossary. To force a rebuild, delete the file.
Otherwise:
- Sample chunks: read
chunk0001.md, the last chunk, and 3 evenly-spaced middle chunks. Ifchunk_count < 5, sample all of them. - Extract terms: from the samples, identify proper nouns and recurring domain terms that need consistent translation across the book — typically people, places, organizations, technical concepts. Translate each into the target language. Skip generic vocabulary that any translator would render the same way.
- Write
glossary.jsonin the temp dir, matching this v2 schema:
{
"version": 2,
"terms": [
{"id": "Manhattan", "source": "Manhattan", "target": "曼哈顿",
"category": "place", "aliases": [], "gender": "unknown",
"confidence": "medium", "frequency": 0,
"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.
- Count frequencies by running:
python3 {baseDir}/scripts/glossary.py count-frequencies "<temp_dir>"
This scans every chunk.md (excluding output_chunk.md), updates each term's frequency field, and writes back atomically.
The glossary is hand-editable. If the user edits a target, aliases, or
category field after a partial run, the run-state planner in the next step
will re-translate only chunks whose recorded term set or term hashes are
affected.
3.7. Plan Selective Re-translation
Run:
python3 {baseDir}/scripts/run_state.py plan "<temp_dir>"
If the user explicitly asks to apply glossary edits to outputs produced before
run_state.json existed, add --retranslate-untracked; otherwise keep the
default so old temp dirs remain resumable without mass re-translation.
Capture stdout JSON:
translation_chunk_ids— chunks to translate in this run.record_only_chunk_ids— existing valid outputs that needrun_state.json
records but do not need translation.
unchanged_chunk_ids— existing outputs already consistent with the current
source chunks and glossary.
If record_only_chunk_ids is non-empty, record them before launching
sub-agents:
python3 {baseDir}/scripts/run_state.py record "<temp_dir>" chunk0001 chunk0002 ...
Use translation_chunk_ids as the work queue for Step 4. If it is empty, skip
to Step 5.
4. Parallel Translation with Sub-Agents
Each chunk gets its own independent sub-agent (1 chunk = 1 sub-agent = 1 fresh context). This prevents context accumulation and output truncation.
Launch chunks in batches to respect API rate limits:
- Each batch: up to
concurrencysub-agents in parallel (default: 8) - Wait for the current batch to complete before launching the next
Spawn each sub-agent with the following task. Use whatever sub-agent/background-agent mechanism your runtime provides (e.g. the Agent tool, sessions_spawn, or equivalent).
The output file is output_ prefixed to the source filename: chunk0001.md → output_chunk0001.md.
Translate the file/chunk.mdto {TARGET_LANGUAGE} and write the result to/output_chunk.md. Follow the translation rules below. Output only the translated content — no commentary.
Each sub-agent receives:
- The single chunk file it is responsible for
- The temp directory path
- The target language
- The translation prompt (see below)
- A per-chunk term table (see "Term table assembly" below)
- Read-only neighboring chunk excerpts (see "Neighbor context assembly" below)
- Any custom instructions
Term table assembly — before spawning a sub-agent, run:
python3 {baseDir}/scripts/glossary.py print-terms-for-chunk "<temp_dir>" "chunk<NNNN>.md"
Capture stdout. The CLI emits a 3-column markdown table (原文 | 别名 | 译文) of every term that either appears in this chunk (by source OR any alias) OR is in the top-N most-frequent terms book-wide. Inject the table as {TERM_TABLE} in rule #13 of the translation prompt. If stdout is empty (no glossary, or no relevant terms), omit rule #13 from this chunk's prompt entirely — do not leave a dangling {TERM_TABLE} placeholder.
Neighbor context assembly — before spawning a sub-agent, run:
python3 {baseDir}/scripts/chunk_context.py "<temp_dir>" "chunk<NNNN>.md"
Capture stdout. The CLI emits prompt-ready read-only excerpts: the last ~300
characters of the previous chunk and the first ~300 characters of the next
chunk when those files exist. Inject this block as {NEIGHBOR_CONTEXT}. If
stdout is empty, omit the neighbor-context block entirely. The sub-agent must
not translate neighboring excerpts or copy them into the output; they are only
for pronoun, gender, and entity-resolution context.
Each sub-agent's task:
- Read the source chunk file (e.g.
chunk0001.md) - Translate the content following the translation rules below
- Write the translated content to
output_chunk0001.md - Write observations to
output_chunk0001.meta.jsonmatching the schema below. Non-blocking — leave fields empty if unsure; do not invent entities. Always emit the file (even if all arrays are empty), because its presence + content hash is how the main agent tracks whether feedback was already merged.
Sub-agent meta schema (output_chunk.meta.json):
{
"schema_version": 1,
"new_entities": [
{"source": "Taig", "target_proposal": "泰格", "category": "person",
"evidence": "<≤200-char quote from the chunk>"}
],
"alias_hypotheses": [
{"variant": "Taig", "may_be_alias_of_source": "Tai",
"evidence": "<≤200-char quote>"}
],
"attribute_hypotheses": [
{"entity_source": "Tai", "attribute": "gender", "value": "male",
"confidence": "high", "evidence": "<≤200-char quote>"}
],
"used_term_sources": ["Tai", "Manhattan"],
"conflicts": [
{"entity_source": "Tai", "field": "target", "injected": "泰",
"observed_better": "太一", "evidence": "<≤200-char quote>"}
]
}
Do NOT include a chunk_id field — chunk identity is derived from the filename. Putting it in the payload creates a hallucination hole and validation will reject the file.
The meta file is read by the main agent later and merged into glossary.json (see merge_meta.py). Sub-agents should fill the schema honestly: cite real quotes from the chunk, never invent entities to "look productive". An empty meta is a perfectly valid output.
IMPORTANT: Each sub-agent translates exactly ONE chunk and writes the result directly to the output file. No START/END markers needed.
Translation Prompt for Sub-Agents
Include this translation prompt in each sub-agent's instructions (replace {TARGET_LANGUAGE} with the actual language name, e.g. "Chinese"):
请翻译markdown文件为 {TARGET_LANGUAGE}.
IMPORTANT REQUIREMENTS:
- 严格保持 Markdown 格式不变,包括标题、链接、图片引用等
- 仅翻译文字内容,保留所有 Markdown 语法和文件名
- 数学公式(行内
$...$、公式块$$...$$)内的 LaTeX 原样保留,不要翻译、改写或删除其中任何字符 - 表格(Markdown
| ... |表格或 HTML- 脚注:正文中的引用标记
[^12]与行首的定义标记[^12]:原样保留,不要改编号、不要删除、不要移动位置,只翻译定义后面的注释文字;定义的续段保持行首四个空格的缩进- 删除空链接、不必要的字符和如: 行末的'\\'。页码已由 convert.py 上游处理,不要再删除独立的数字行(可能是年份 1984、章节编号、引用编号等正文内容)。
- 保证格式和语义准确翻译内容自然流畅
- 只输出翻译后的正文内容,不要有任何说明、提示、注释或对话内容。
- 表达清晰简洁,不要使用复杂的句式。请严格按顺序翻译,不要跳过任何内容。
- 必须保留所有图片引用,包括:
- 所有
格式的图片引用必须完整保留 - 图片文件名和路径不要修改(如
media/image-001.png) - 图片alt文本可以翻译,但必须保留图片引用结构
- 不要删除、过滤或忽略任何图片相关内容
- 图片引用示例:
->

- 原始 HTML 标签(如
、)必须保持合法:翻译alt、title等属性值内部文本时,下列字符会破坏 HTML 结构,必须替换为安全形式(仅适用于原始 HTML 标签的属性值内部;普通 Markdown 正文、代码块、URL 不要主动转义):
不要修改
src、href等结构性属性的值,只翻译可见文本属性(alt、title)。- 独立成行的较短文本(通常少于50字符)
- 具有总结性或概括性的语句
- 在文档结构中起到分隔和组织作用的文本
- 字体大小明显不同或有特殊格式的文本
- 数字编号开头的章节文本(如 "1.1 概述"、"第三章"等)
邻居上下文(只读,不要翻译,不要写入输出,只用于判断代词、性别、别名和跨 chunk 指代;为空则省略):
4.5. Merge Sub-Agent Meta Into Glossary (after each batch)
python3 {baseDir}/scripts/run_state.py record "<temp_dir>" chunk0001 chunk0002 ...If this fails, fix the missing/empty output or state error before continuing.
python3 {baseDir}/scripts/merge_meta.py prepare-merge "<temp_dir>"Capture stdout JSON. It contains four arrays:
{"id": "d1", "kind": "alias", "variant": "Taig", "candidate_source": "Tai", "choice": "yes_alias"}echo '{"auto_apply": [...], "decisions": [...], "consumed_chunk_ids": [...]}' \ | python3 {baseDir}/scripts/merge_meta.py apply-merge "<temp_dir>"5. Verify Completeness and Retry
Also read
manifest.jsonand verify:Then run the meta-merge observability snapshot:
python3 {baseDir}/scripts/merge_meta.py status "<temp_dir>"Also run the selective re-translation state snapshot:
python3 {baseDir}/scripts/run_state.py status "<temp_dir>"Surface a one-line summary in the verification report:
Translated chunks: 50 • Meta files: 48 found / 47 consumed • Malformed: 1 (chunk0099 — see stderr) • Chunks missing meta: chunk0017, chunk0042
Severity rules (none of these fail the run — meta is non-blocking):
Report any chunks that failed translation after retry.
6. Translate Book Title
Translate the title to the target language. For Chinese, wrap in 书名号:
《translated_title》.7. Post-process — Merge and Build
Run the build script with the translated title:
python3 {baseDir}/scripts/merge_and_build.py --temp-dir "<temp_dir>" --title "<translated_title>"The script reads
output_langfromconfig.txtautomatically. Optional overrides:--lang,--author.This produces in the temp directory:
8. Report Results
(Step 9), and that they can ask for cleanup once they are done with the book
9. Spot Fixes After the Build
python3 {baseDir}/scripts/run_state.py plan "<temp_dir>"If chunk appears in
chunks[]with actiontranslate, recording
would hide that. Handle it by reason:Then record the edited output:
python3 {baseDir}/scripts/run_state.py record "<temp_dir>" chunk<NNNN>the chunk is newer than
output.md, then regenerates the HTML and the other
formats.
)保持行列结构不变,只翻译单元格中的文字 - 脚注:正文中的引用标记