Parsing and Rebuilding EPUB Files in Python: Lessons Learned from Building an AI Book Translator
说明与用途
使用ebooklib和lxml构建了一个在保留格式的前提下翻译EPUB书籍的系统,并通过LLM进行批量处理。
问题
Translating EPUB books while preserving formatting, fonts, images, and structure.
结果
The pipeline successfully translates EPUBs while maintaining formatting and structure, enabling a functional AI book translation service.
工作流
- Load EPUB with ebooklib.read_epub
- Iterate over spine items and parse XHTML with lxml
- Handle namespaces for XPath queries
- Extract block-level text while preserving order
- Batch paragraphs for LLM translation
- Replace text in original elements without removing attributes
- Rebuild EPUB with updated content and metadata
证据
We started building LectuLibre, an AI-powered book translation service, with a simple premise: users upload an EPUB or PDF, we translate it using large language models (Claude, DeepSeek), and they download a translated copy.
We settled on ebooklib for the container-level work and lxml for parsing and modifying the XHTML content.
To replace text while preserving the block-level structure, we used lxml to set the text content of each block element.
- 记录日期: 2026-10-17T03:41:25.261Z