Skip to main content

EPUB Dual Language

Plugin and package verification

EPUB Dual Language icon

EPUB Dual Language provides two ways to create a separate bilingual ebook: a command-line interface (CLI) and a Calibre desktop plugin. Both interfaces normalize books through the same EPUB translation core, so the output behavior is designed to remain consistent.

Choose an interface

CLI - overview

Use the epub-dual-language command when you want a scriptable or terminal-based workflow. It accepts any input and output format supported by an installed Calibre, supports dry runs and detailed translation options, and writes a separate output book. EPUB-to-EPUB works without Calibre. The CLI uses your selected provider credentials from the shell or a local .env file. See the CLI installation, CLI usage for installation, configuration, and usage.

Calibre plugin - overview

Use the Calibre plugin when your books are already in a Calibre library. Select one book, choose Dual Language from the toolbar or book context menu, and start the translation from the GUI. The plugin runs inside Calibre's bundled Python runtime, performs work in the background, and adds the completed bilingual book as a separate Calibre book by default. It does not replace the original book, support batch translation, or require a separate Python installation for normal use. See the Calibre plugin guide for installation, configuration, and usage.

These are two interfaces to one shared core, not two different translation products.

Features

  • Accepts Calibre-supported input and output formats through an EPUB pivot.
  • Translates with OpenRouter, OpenAI, or custom OpenAI-compatible services.
  • Preserves the original EPUB container and stylesheet links.
  • Produces a separate dual-language edition with updated title and EPUB identifiers.
  • Supports paragraph or sentence interleaving.
  • Supports chapter-based or token-budget chunking.
  • Can translate only the beginning of a book for quick tests.
  • Can add rare bracketed translator notes for important cultural or archaic references.
  • Recovers completed items from truncated JSON responses instead of retranslating them.
  • Isolates model-filtered passages by splitting failed batches.
  • Retries temporary network, rate-limit, and server failures with backoff.
  • Can use a fallback model for a passage rejected by the primary model.

Example of a generated dual-language EPUB (left) vs. original (right) opened in Calibre:

example

Installation

Install from PyPI:

pip install epub-dual-language

Python 3.10 or newer is required.

For development, clone the repository and install it into a Python environment:

pip install -e ".[dev]"

OpenRouter API Key

The CLI reads OPENROUTER_API_KEY from the environment. You can pass it directly when you run the command.

macOS/Linux:

OPENROUTER_API_KEY=your_openrouter_key epub-dual-language "path/to/book.epub" "English"

PowerShell:

$env:OPENROUTER_API_KEY="your_openrouter_key"; epub-dual-language "path/to/book.epub" "English"

Windows cmd:

set OPENROUTER_API_KEY=your_openrouter_key && epub-dual-language "path/to/book.epub" "English"

You can also create a .env file in the directory where you run the command:

OPENROUTER_API_KEY=your_openrouter_key

When you call epub-dual-language, it loads .env from the current working directory. An environment variable already set in your shell takes priority over the .env value. The repository's own .env is ignored by git.

Basic Usage

epub-dual-language "path/to/book.epub" "English"

Write to a specific output path:

epub-dual-language "path/to/book.epub" "English" --output "output/book.dual.epub"

Translate only a small beginning sample:

epub-dual-language "path/to/book.epub" "English" --limit-units 30 --output "output/sample.dual.epub"

Run without calling OpenRouter, for testing:

epub-dual-language "path/to/book.epub" "English" --dry-run --limit-units 20

Options

epub-dual-language INPUT_EPUB TARGET_LANGUAGE \
  --source-language German \
  --model google/gemini-3-flash-preview \
  --fallback-model provider/fallback-model \
  --api-attempts 3 \
  --api-timeout 120 \
  --chunking tokens \
  --max-tokens 4000 \
  --max-concurrency 3 \
  --layout paragraph \
  --sentences-per-unit 5 \
  --translation-style italic-muted \
  --translator-notes / --no-translator-notes \
  --limit-units 30 \
  --output output/sample.dual.epub

Important options:

  • --model: primary OpenRouter model.
  • --fallback-model: optional model used only when one isolated passage fails with the primary model.
  • --api-attempts: attempts for temporary connection, timeout, HTTP 408/429, or HTTP 5xx failures. Default: 3.
  • --api-timeout: timeout in seconds for each API request. Default: 120.
  • --max-tokens: estimated input budget for each initial translation batch. Default: 4000.
  • --max-concurrency: maximum model requests sent in parallel. Default: 3; use 1 for sequential requests if a provider rate-limits the run.
  • --chunking: tokens or chapters. Default: tokens.
  • --layout: paragraph or sentence. Default: paragraph.
  • --sentences-per-unit: with --layout paragraph, splits long paragraphs into groups of N consecutive sentences and interleaves each original group with its translation. Default: 5.
  • --translation-style: italic, muted, italic-muted, or plain. Default: italic-muted.
  • --translator-notes / --no-translator-notes: permits rare, short translator notes. Default: enabled.
  • --limit-units: translates only the first N extracted units.
  • --dry-run: creates a sample EPUB without calling OpenRouter.

Model choice and approximate book cost

google/gemini-3-flash-preview remains the quality-oriented default. The much cheaper openai/gpt-5.6-luna is a strong economy option: local matched-passage tests across seven German and French literary EPUBs found broadly comparable quality, but neither model won every passage. Luna was often smoother, while Gemini was more precise on several idioms and ambiguous constructions.

The Calibre run dialog searches OpenRouter's live text-model catalog as you type a model ID and fills its current input/output prices automatically. The model and prices remain editable, including when the catalog is unavailable. Pricing returned by the catalog is per token and is displayed as US dollars per million tokens.

Before an EPUB translation starts, the dialog performs a local, zero-cost analysis and shows:

  • translation-unit count;
  • minimum, median, 90th-percentile, and maximum estimated tokens per unit;
  • estimated API request count and parallel request waves;
  • estimated input and output tokens; and
  • estimated total cost using the editable prices.

The estimate assumes translated output is approximately the same token length as the source and adds 300 input tokens of prompt/JSON overhead per request. Actual billing can differ because languages have different token densities, models vary their output, retries add requests, and provider prices can change. The OpenRouter response remains the authoritative source for actual usage and cost.

Representative whole-book estimates from the local test library, using the current defaults and catalog prices at the time of testing:

Book Units Gemini estimate Luna estimate
Die Verwandlung 179 $0.079 $0.016
L'Etranger 504 $0.154 $0.031
Trotzdem Ja zum Leben sagen 1,139 $0.251 $0.050
Momo 2,194 $0.300 $0.060
Madame Bovary 3,246 $0.552 $0.110

These are planning estimates, not spending guarantees. Check the values shown in the run dialog immediately before starting a whole-book translation.

Metadata

The generated book is marked as a separate dual-language edition. Translation always uses an EPUB internally:

input format -> temporary EPUB -> bilingual EPUB -> requested output format

The command prints the exact route before starting. A non-EPUB input or output requires Calibre's ebook-convert on PATH; alternatively pass --calibre-path or set EPUB_TRANSLATOR_CALIBRE_PATH. Compatibility is determined by the installed Calibre version. Use --dry-run to exercise the complete route without an API key or paid request.

DRM-protected books cannot be converted. PDF and image-heavy inputs are best effort: scanned books need OCR, and fixed-layout conversions may lose reading order or styling. EPUB is therefore the recommended output when fidelity matters.

For example, an input title like:

Original Title

becomes:

Original Title (Dual English)

The OPF unique identifier is also replaced with a new deterministic dual-edition UUID. This reduces the chance that Calibre or an e-reader treats the translated edition as the same book as the source.

Chunking

--chunking tokens is the default. It walks the EPUB in reading order and packs paragraphs or sentences into model requests until the estimated --max-tokens budget is reached. Small samples can therefore fit into a single API call even if they cross EPUB file boundaries.

Up to three chunks are translated concurrently by default. Results are retained in reading order even when requests finish out of order. Set --max-concurrency 1 for sequential requests, or lower concurrency if a provider returns rate-limit errors.

--chunking chapters sends one EPUB spine document at a time. Many EPUBs store chapters as separate XHTML files, so this often approximates chapter-by-chapter translation. It is simple, but very long chapters can create large requests.

Token counts are estimates based on text-like tokens, not provider billing tokens.

Smaller values reduce the chance of truncated model output but create more API calls. A value around 3000–4000 is a practical starting point for paragraph translation.

API Failure Handling

The translator distinguishes between temporary service failures, malformed model output, content filtering, and fatal API configuration errors.

Failure Behavior
Connection error or timeout Retry the same batch with exponential backoff.
HTTP 408, 429, 500, 502, 503, or 504 Retry the same batch with exponential backoff.
Truncated or malformed translation JSON Keep every complete translation object that can be recovered, then request only unresolved items.
content_filter, model error, or unusable model output Split the unresolved batch in half immediately and continue recursively.
One isolated passage still fails Try --fallback-model when configured; otherwise insert an error placeholder and continue the EPUB.
Authentication, permission, invalid model, or other non-retryable HTTP error Stop the run because splitting would not repair the request.
Temporary API failure after all configured attempts Stop the run rather than fill the book with misleading placeholders.

The placeholder written for an irreducible passage is:

[TRANSLATION ERROR: This passage could not be translated.]

This behavior is designed for cases where a specific literary passage triggers a model or provider filter. Successful passages are retained in their original order, and one rejected passage does not prevent the rest of the EPUB from being generated.

--api-attempts applies only to failures likely to be temporary. Model-output failures are not retried unchanged: they are recovered or split immediately.

Example using a fallback model:

epub-dual-language "book.epub" "Spanish" \
  --source-language French \
  --model google/gemini-3-flash-preview \
  --fallback-model provider/fallback-model \
  --chunking tokens \
  --max-tokens 4000

If a malformed response contains valid items 0 through 6 and truncates during item 7, the translator keeps items 0 through 6 and requests only item 7 and the remaining unresolved items. It does not pay to translate the successful prefix again.

Layouts

--layout paragraph --sentences-per-unit 5 is the default and recommended mode for reading long literary paragraphs:

Original sentence group
Translated sentence group
Original sentence group
Translated sentence group

If a paragraph fits into one sentence group, the output remains simple paragraph alignment.

--layout sentence alternates original and translated sentences inside each paragraph. It can be useful for language study, but it is less pleasant for uninterrupted reading.

For very long paragraphs, use --sentences-per-unit N with --layout paragraph to translate smaller groups of consecutive sentences and render them as original group, translated group, original group, translated group:

epub-dual-language "book.epub" "Spanish" --layout paragraph --sentences-per-unit 5

Translation Styling

Translated text is italic by default so it is easy to distinguish from the original without changing the book too aggressively.

epub-dual-language "path/to/book.epub" "English" --translation-style italic

Available styles:

  • italic
  • muted
  • italic-muted
  • plain

Translator Notes

Translator notes are enabled by default. This lets the model add rare, short notes in square brackets for genuinely important archaic, historical, or culturally specific references:

epub-dual-language "path/to/book.epub" "English" --translator-notes

Disable them with --no-translator-notes.

The prompt explicitly asks the model not to explain ordinary lines or add notes everywhere.

Calibre plugin

The repository also contains a focused Calibre InterfaceAction plugin. It creates a separate dual-language book from one selected Calibre book and uses the same conversion pipeline, EPUB processor, and provider client as the CLI. The original book is never modified. The run dialog offers the formats stored for the selected book, output formats exposed by Calibre, and a visible conversion route. For EPUB inputs it also shows the detected translation-unit count, token-size distribution, estimated request count, and an editable cost estimate before starting. OpenRouter users get a searchable model list with catalog prices filled automatically when available; the model and price fields remain editable if the catalog cannot be reached. The common estimate stays compact, while token/pricing details and advanced translation controls are genuinely collapsible. Batch translation remains out of scope.

Paragraph detection is semantic rather than tied to one book or Calibre class name. The EPUB processor translates standard paragraph/list/heading/table elements and text-bearing leaf div blocks, while excluding structural wrapper div elements that would duplicate their descendants. This behavior was checked against every EPUB in the repository's launch configuration.

Plugin installation and updating

Calibre plugin 1

Calibre plugin 2

The easiest installation source is the ZIP built by GitHub:

  1. Download epub_dual_language_calibre_plugin.zip from the latest GitHub release.

  2. In Calibre, choose Preferences → Plugins → Load plugin from file, select the plugin ZIP, approve the third-party-plugin warning, and restart Calibre if requested. Updating uses the same process with the newer ZIP. Plugin settings are stored in Calibre's plugin configuration and are not reset by rebuilding or replacing the ZIP.


Every push and pull request automatically runs the Python tests, builds and validates the Python package, builds and inspects the plugin ZIP, and uploads the ZIP/checksum as a workflow artifact. CI then installs pinned Calibre 8.16.2 in an isolated directory, installs the generated ZIP, verifies plugin registration, creates a dry-run AZW3 through the installed plugin, converts it back to EPUB, and verifies the bilingual marker. No provider credentials or paid API requests are used.

The plugin is not an automatic installer. A future stable release may be submitted to the Calibre/MobileRead community plugin index so Calibre can announce updates.

Calibre keeps toolbar placement and book-context-menu placement as separate user choices. If the action is visible on the toolbar but not after right-clicking a book, open Preferences → Interface → Toolbars & menus, select The context menu for books in the calibre library, move Dual Language from Available actions to Current actions, and restart Calibre if requested.

Provider configuration and security

OpenRouter is the default/easiest setup. An OpenRouter key belongs to OpenRouter and is used with https://openrouter.ai/api/v1. An OpenAI key belongs to OpenAI and is used with https://api.openai.com/v1. A custom OpenAI-compatible endpoint requires credentials only when that service requires them. Keys are not interchangeable unless the service explicitly says so.

The settings screen provides four isolated provider presets:

Preset Default endpoint Initial model Credentials
OpenRouter https://openrouter.ai/api/v1 google/gemini-3-flash-preview OpenRouter key required
OpenAI https://api.openai.com/v1 gpt-5-mini OpenAI key required
Ollama (local) http://localhost:11434/v1 qwen3:8b Not required
Custom User supplied User supplied Optional, depending on service

Install and start Ollama separately, then pull the initial local model with ollama pull qwen3:8b, or enter any other locally installed chat model. Ollama uses its documented OpenAI-compatible /v1/chat/completions interface. Local inference has a displayed API cost of zero, though electricity and hardware costs are naturally not included.

Saved credentials, primary models, fallback models, and price estimates are scoped to their provider preset. Switching providers does not carry an OpenRouter model or key into OpenAI, Ollama, or a custom endpoint. OpenRouter model-catalog access is optional, cached for 30 minutes, limited to a short timeout, and never attempted for the other presets. If it fails, the model field remains editable and translation is unaffected.

The CLI preserves OPENROUTER_API_KEY. The plugin also supports, in precedence order, the selected provider's environment variable (OPENROUTER_API_KEY or OPENAI_API_KEY), EPUB_TRANSLATOR_API_KEY, and the saved plugin key. The API-key field is masked, but a saved key is plain text in Calibre's local plugin configuration; use an environment variable if that is unacceptable. Keys and authorization headers are excluded from diagnostics.

The settings screen shows the active credential source without displaying its value. Changing provider presets does not reuse a saved key belonging to another preset. Custom headers cannot replace authorization or transport headers, and provider redirects are not followed.

The plugin intentionally does not load the repository's .env file. Calibre must be started with the relevant provider environment variable already set, or the key can be entered in the masked settings field. If a key is ever pasted into chat, source control, or a screenshot, revoke it at the provider and create a replacement.

OpenAI-compatible endpoints

OpenRouter and OpenAI use their documented base URLs. A custom service needs its own display name, base URL, model, credentials, and optional non-authorization headers. The transport appends /chat/completions exactly once and does not require a /models endpoint. HTTPS certificate verification remains enabled. For unauthenticated Ollama/custom endpoints, no Authorization header is sent. When a custom endpoint key is configured, it is sent as a bearer token.

Building and debugging

python calibre_plugin/build.py
calibre-customize -a dist/epub_dual_language_calibre_plugin.zip
calibre-debug -g

The ZIP contains the plugin source and the shared core. It does not bundle platform- specific wheels or require Conda, pip, requests, or an external Python runtime for normal Calibre users. Its standard-library HTTPS fallback uses TLS verification and rejects redirects. BeautifulSoup and lxml are supplied by the tested Calibre runtime.

The current development release supports one selected book, Calibre-backed format conversion, dry-run/sample mode, and separate-edition output. It does not support batch translation or an automatic updater. The packaged core, plugin registration, settings/run widgets, and isolated-library insertion callback have been exercised locally with Calibre 8.16.2; an end-to-end toolbar click and paid network translation still require a local manual GUI test.

Testing the plugin without an API

In the per-book dialog, enable Test mode (do not contact the API). The plugin creates a valid book containing visibly marked dry-run translations while using the same conversion, EPUB processing, progress, output-validation, and library-insertion paths as a normal run. No API key is required and no network request is made. Use Optional sample limit to keep the test book small.

Developers can exercise the installed plugin without opening its GUI:

calibre-debug -r "EPUB Dual Language" -- \
  input.epub output.test.epub Spanish --limit-units 10

This command is intentionally dry-run only; it cannot make a provider request.

CLI installation

Install the package with python -m pip install . (or .[dev] for tests). The existing epub-dual-language command and its documented options remain supported. Use a .env file or the shell environment for OPENROUTER_API_KEY; the CLI does not silently use a key from a different provider.

Development and tests

Run the complete local suite and build both artifacts:

python -m pytest
python -m epub_dual_language.cli --help
python -m build
python calibre_plugin/build.py

For Calibre development, use an isolated configuration and library:

python calibre_plugin/build.py
calibre-customize -a dist/epub_dual_language_calibre_plugin.zip
calibre-debug -g

Do not use a real library for plugin experiments. The release workflow checks package and plugin versions, builds the Calibre ZIP, and attaches the ZIP and checksum to a GitHub Release. The verification workflow also retains a downloadable ZIP/checksum for each successful run. The project may later be submitted to the Calibre/MobileRead community plugin index; there is no custom in-plugin updater.

Privacy-aware bug reports

Use the issue form's sanitized diagnostics field. Never include API keys, authorization headers, prompts, source or translated passages, EPUB files, usernames in paths, or complete Calibre library paths. The plugin offers Copy sanitized diagnostics and Report bug actions from structured error dialogs.

Run the CLI module directly:

python -m epub_dual_language.cli "path/to/book.epub" "English" --dry-run --limit-units 10

Metadata

Release files for epub-dual-language 0.3.2

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

Source distribution (sdist)

Source distribution for epub-dual-language 0.3.2
File Size Uploaded Provenance Actions
epub_dual_language-0.3.2.tar.gz 50.6 kB With provenance Details for epub_dual_language-0.3.2.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for epub-dual-language 0.3.2
File Interpreter ABI Platform Actions
epub_dual_language-0.3.2-py3-none-any.whl Python 3 none any Details for epub_dual_language-0.3.2-py3-none-any.whl

Total release size: 89.1 kB

Release files / epub_dual_language-0.3.2.tar.gz

Download URL epub_dual_language-0.3.2.tar.gz
Size 50.6 kB
Tags Source
SHA-256 checksum
How to use checksums
654f45c38849f58de1037b81a61d964e69cdb090e7f03ec6073e2c5afbc95007
BLAKE2b-256 checksum
How to use checksums
950f739c07752503bb1671db9b28acdebad3b39006670edc5254c9d5cf3ff2bb
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

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 Aug 12, 2026.

Transparency log

Release files / epub_dual_language-0.3.2-py3-none-any.whl

Download URL epub_dual_language-0.3.2-py3-none-any.whl
Size 38.5 kB
Tags Python 3
SHA-256 checksum
How to use checksums
1ec000d9fb68d71f77e4ac5befc515a47f12cb1f1e2828b7c1df024e1ecd7479
BLAKE2b-256 checksum
How to use checksums
670157a5888d860aa08b9d383f6f24f13cf81109f770b284cc3034124461c358
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

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 Aug 12, 2026.

Transparency log

Security for epub-dual-language 0.3.2

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 epub_dual_language-0.3.2.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 Aug 12, 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.

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