Skip to main content

txt2epub

An auditable Chinese TXT → EPUB 3 converter with multi-level navigation for KOReader, Kindle, and other EPUB readers.

The design goal is simple: never silently lose body text. Every source line gets a disposition in a line ledger, and conversion refuses to write an EPUB unless the source/output/dropped text multiset balances (unless you explicitly pass --allow-loss).

AI usage disclosure: Most of this codebase was written by AI coding agents. Human maintainers have verified behavior with automated tests and real-book conversions, but have not performed a rigorous line-by-line review. Review the source before relying on it in sensitive environments.

Features

  • Detects UTF-8 / UTF-8 BOM / UTF-16 / GB18030 / Big5 input, CRLF or LF.
  • Recognizes 卷 / 章 / 节 / special sections (序章, 前传, 番外, 终章, 后记, 完本感言, ...).
  • Handles common awkward formats:
    • 第一章活着 (no separator between number and title)
    • 第0001章 zero-padded numbers
    • 第一卷 卷名 第1章 章名 combined volume+chapter prefixes
    • 第104、105章 and 第1037章—第1038章 multi-number headings
    • indented headings (books where every heading starts with U+3000)
    • short indented volume names such as   第一卷,惊蛰。
  • Removes obvious site ads/watermarks, detects embedded TOC pages, reports duplicate chapter numbers and number gaps without renaming anything.
  • Generates nested EPUB 3 nav.xhtml and EPUB 2 toc.ncx, so old and new readers both get a proper multi-level TOC.
  • Batches multiple files; one failure does not stop the rest.

Install

Requires Python 3.11+.

# isolated CLI install (recommended)
uv tool install txt2epub-cli

# or install into the current environment
pip install txt2epub-cli

The distribution is named txt2epub-cli; the CLI command is txt2epub and the import package is txt2epub_cli. The separate import name avoids clashing with the unrelated PyPI package txt2epub.

From a source checkout:

git clone https://github.com/ak1ra-lab/txt2epub.git
cd txt2epub

# with uv (recommended for development)
uv sync --group dev
uv run txt2epub --help

# or install the working tree into the current environment
pip install -e .
txt2epub --help

python -m txt2epub_cli ... works as well. Shell completion is provided by argcomplete:

eval "$(register-python-argcomplete txt2epub)"

Usage

Inspect without writing files

txt2epub inspect book.txt
txt2epub inspect book.txt --json
txt2epub inspect examples/txt/*.txt --json > report.json

Human output includes encoding, line/char counts, front matter, heading counts, first/last heading, issue summary, coverage, and a short suspicious list. Add --verbose to show all warnings, or --limit 0 to hide the list.

Some books have genuine source-level numbering gaps, or many expected indented duplicate headings. Focus the human list without changing the JSON report:

# hide known source numbering gaps
txt2epub inspect book.txt --verbose --ignore-issue number_gap

# hide several codes (repeat the option or use commas)
txt2epub inspect book.txt --verbose \
  --ignore-issue number_gap,duplicate_number

# show only conflicts and gaps
txt2epub inspect book.txt --only-issue number_conflict,number_gap

# indented duplicate headings are severity=info; show them explicitly
txt2epub inspect book.txt --only-issue duplicate_indented

--ignore-issue / --only-issue affect only the human suspicious list; --json always contains the complete issue list.

Convert one or many files

# output next to the source file: book.epub
txt2epub convert book.txt

# batch into a directory
txt2epub convert *.txt -o out/

# parse and report only, no EPUB
txt2epub convert book.txt --dry-run

# write a JSON report for automation
txt2epub convert *.txt -o out/ --report out/report.json

# overwrite existing outputs non-interactively
txt2epub convert *.txt -o out/ --yes

# no first-line indent (indentation is CSS-driven, not literal spaces)
txt2epub convert book.txt --no-indent

# custom first-line indent in em
txt2epub convert book.txt --indent-em 1.5

# replace the built-in stylesheet entirely
txt2epub convert book.txt --css my-style.css

When an output file already exists, interactive runs ask before overwriting. Use --force or --yes in scripts.

Body paragraphs are stripped of their source leading/trailing spaces and tabs before being written to XHTML. Indentation is controlled by the EPUB stylesheet instead, so a source line beginning with two U+3000 spaces does not become a double indent on Kindle. The default stylesheet uses text-indent: 2em. --no-indent writes text-indent: 0; --css replaces the stylesheet and takes precedence over --indent-em.

Exit codes

code meaning
0 success
1 parse / write / input error
2 coverage or validation failure
3 rule/config error

For a batch, processing continues after a failure; the final exit code reflects whether any file failed.

Rules and profiles

Built-in profiles:

profile behavior
auto (default) common web-novel formats, allows indented headings
zxs auto plus 知轩藏书-style site noise cleanup
strict column-zero headings only, separator required, 40-char limit
loose indented headings, longer titles, pure-number headings

Select with --profile, and/or override with a TOML file:

txt2epub inspect book.txt --profile strict --rules my-rules.toml

Example my-rules.toml:

[heading]
max_length = 50
allow_indented_headings = true
volume_suffix_special_suffixes = ["序", "章", "篇", "传", "记", "录"]

[patterns]
# Additional patterns are appended to the built-ins.
chapter = '^第(?P<num>[0-9零〇一二三四五六七八九十百千万两]+)[章节回集幕](?:[\s ::]*(?P<title>.*))?$'
# Set replace_patterns = true to replace the built-in lists instead of appending.
replace_patterns = false

[exclude]
volume_suffixes = ["门", "队", "属", "分", "件", "落"]

[noise]
patterns = ["免费阅读", "百度搜索", "请务必保存好书签", "为您提供大神", "秒更", "br>"]

Rules are plain single-line regular expressions. Invalid regexes and unknown TOML keys produce a configuration error instead of a traceback.

Coverage

inspect and convert both report:

Coverage:   100.00% (source 1,234,567 / output 1,234,567 / dropped 0)
  • source counts normalized text units from every non-blank source line.
  • output counts heading titles, front matter, and body paragraphs.
  • dropped counts noise / duplicate headings / embedded TOC lines that were intentionally removed, so the totals still balance.
  • If the multiset does not balance, convert exits with code 2 and does not write a file. Use --allow-loss only when you understand why.

--keep-noise keeps site ads as body text. --keep-toc keeps an embedded TOC page as front matter instead of deleting it.

Duplicate numbers and optional dedupe

By default, duplicate chapter numbers are reported, not renumbered. If two headings have the same number and same title, the later heading is merged into the first occurrence and its body is preserved. Same number + different title is reported as number_conflict and both chapters are kept.

Indented duplicate headings that merely echo an existing column-zero chapter (e.g. a repeated title with a site suffix) are recorded as duplicate_indented with severity info; they do not flood the warning list.

Optional content dedupe:

txt2epub convert book.txt --dedupe exact    # identical title+body hash
txt2epub convert book.txt --dedupe similar  # near-identical body (>= 0.9)

Both are off by default.

Output layout

mimetype
META-INF/container.xml
OEBPS/content.opf
OEBPS/nav.xhtml
OEBPS/toc.ncx
OEBPS/style.css
OEBPS/text/front-matter.xhtml
OEBPS/text/part-0001.xhtml
OEBPS/text/chapter-0001.xhtml
...

Volume/special parent nodes always get a real XHTML page, so every nav/NCX entry has a valid link. Chapters larger than --split-size (default 256 KiB) are split at paragraph boundaries; only the first fragment appears in the TOC.

Documentation

User documentation lives in docs/ and is published at https://ak1ra-lab.github.io/txt2epub/. It is written in English and Simplified Chinese (*.md plus *.zh.md). Build it locally with:

just docs-build
just docs-serve

Development

uv sync --group dev
uv run pre-commit install

just lint
just typecheck
just test
just coverage
just build

# optional local sample smoke (samples are gitignored)
TXT2EPUB_LOCAL_SAMPLES=1 uv run pytest -m local

Committed tests use synthetic placeholder fixtures only. Local samples under examples/txt/ or examples/epub/ are never committed.

The project was scaffolded from copier-pyproject; .copier-answers.yml records the template revision and the distribution, command, and import names separately. Verify a copier update with --pretend before applying it.

Known limitations

  • MVP keeps one source line per paragraph; it does not reflow or re-paragraph.
  • No cover image generation; a future option can accept an external cover.
  • No AI rewriting or automatic chapter-title generation.
  • Big5 detection is best-effort; GB18030 is tried first because most simplified Chinese samples are GB18030.
  • No MOBI/AZW3 output, no GUI, no KOReader plugin.
  • DRM-free input only.

License

GPL-3.0-only. See LICENSE.

Metadata

Release files for txt2epub-cli 0.1.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for txt2epub-cli 0.1.0
File Size Uploaded Provenance Actions
txt2epub_cli-0.1.0.tar.gz 145.0 kB With provenance Details for txt2epub_cli-0.1.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for txt2epub-cli 0.1.0
File Interpreter ABI Platform Actions
txt2epub_cli-0.1.0-py3-none-any.whl Python 3 none any Details for txt2epub_cli-0.1.0-py3-none-any.whl

Total release size: 202.0 kB

Release files / txt2epub_cli-0.1.0.tar.gz

Download URL txt2epub_cli-0.1.0.tar.gz
Size 145.0 kB
Tags Source
SHA-256 checksum
How to use checksums
9c797151ea94ae62c168cbb15f5a436b2b0b0d93ccefd13b66f491dad53e1aad
BLAKE2b-256 checksum
How to use checksums
6c7a8a831ac0a5dae889ee2e6bae92381cc26125820464bf24263113bb7ba1f5
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 19, 2026.

Transparency log

Release files / txt2epub_cli-0.1.0-py3-none-any.whl

Download URL txt2epub_cli-0.1.0-py3-none-any.whl
Size 57.0 kB
Tags Python 3
SHA-256 checksum
How to use checksums
c4f69b0e691c96fb8ac4e3f9d0146d18de4a5c4891484791dce896f98d34a91c
BLAKE2b-256 checksum
How to use checksums
c6d045cfd2a5dc46398a4692594d9751a9417f97e74183c9b31f199b96bd3ac6
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 19, 2026.

Transparency log

Security for txt2epub-cli 0.1.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for txt2epub_cli-0.1.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 19, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.1.0 This release

2 release files Full provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page