今日已更新 166 条资讯 | 累计 20138 条内容
关于我们

Parsing and Rebuilding EPUB Files in Python: Lessons Learned

龚旭东 2026年06月27日 11:00 5 次阅读 来源:Dev.to

How we handle complex EPUB structures for AI translation without breaking navigation and metadata At LectuLibre , we built an AI‑powered book translation service. Users upload an EPUB, and our pipeline translates the text using LLMs like Claude and DeepSeek. That sounds straightforward until you have to parse and rebuild a valid EPUB without mangling the table of contents, internal links, or styles. I’m sharing the real‑world challenge we faced, how we chose our tooling, and the ugly corners we discovered when dealing with real‑world EPUB files. The Problem: EPUB is a Messy Zip File An EPUB is essentially a ZIP archive containing XHTML, CSS, images, and an OPF manifest. It’s a well‑defined standard (EPUB 3.2), but in practice publishers produce files that bend the rules: missing container.xml , inline styles that break after translation, and structural quirks that make parsing fragile. Our translation process needed to: Accept any EPUB the user throws at us. Extract all text content while preserving the exact structure. Send each paragraph to an LLM for translation. Re‑insert the translated text into the original XHTML files. Repackage everything into a new, valid EPUB. Step 4 is the tricky part: the translated text can be longer or shorter, it may contain characters that need escaping, and the surrounding markup must remain intact. Our Approach: Use ebooklib with a Dose of Defensive Coding We evaluated several Python libraries: epub (pypub) – too simple, no editing support. lxml + manual zip – too much boilerplate. ebooklib – full read/write with a clean API. We went with ebooklib . It provides an object‑oriented model of the EPUB structure, allows us to iterate over documents, and can write a new EPUB from the modified objects. The downside: its documentation is sparse and it can choke on malformed files. We had to layer on a lot of validation. Step 1: Loading and Validating the EPUB import ebooklib from ebooklib import epub def load_epub ( epub_path : str ) -> ep

本文内容来源于互联网,版权归原作者所有
查看原文