{"slug": "parsing-and-rebuilding-epub-files-in-python-lessons-learned-from-building-an-ai", "title": "Parsing and Rebuilding EPUB Files in Python: Lessons Learned from Building an AI Translation Service", "summary": "LectuLibre built a service that translates entire EPUB books using large language models. The team developed a Python pipeline that parses EPUB files, extracts text while preserving formatting, sends it to an LLM for translation, and reconstructs the EPUB. They used ebooklib for high-level structure and lxml for precise XML control to handle real-world EPUB complexities.", "body_md": "*How we extract, translate, and reconstruct entire ebooks with Python while preserving every detail*\n\nAt LectuLibre, we built a service that translates entire books using large language models. Our users upload EPUB files, and our backend pipeline parses them, extracts the text, sends it to an LLM for translation, and then rebuilds the EPUB with the translated content—all while preserving the original formatting, images, and metadata. This sounded straightforward until we looked inside a real EPUB.\n\nEPUB is essentially a ZIP file containing a structured set of XHTML, CSS, and XML files. The `content.opf`\n\nfile defines the reading order (spine), metadata, and manifest. The `toc.ncx`\n\nholds the table of contents. The actual text lives in XHTML documents, often split per chapter. To translate a book, we needed to: 1) reliably parse the EPUB, 2) locate all translatable text, 3) send it chunk by chunk to the LLM, and 4) rebuild the EPUB with the translated text while keeping every byte of the formatting intact.\n\nWe initially reached for `ebooklib`\n\n, the most popular Python library for EPUB manipulation. It worked great for simple EPUBs—until we threw a few hundred real-world files at it. We quickly hit issues:\n\n`ebooklib`\n\ndidn’t fully preserve custom metadata or namespace-prefixed properties in the OPF.`xmlns`\n\nattributes, breaking rendering on some devices.`ebooklib`\n\nloaded everything at once.We could have used a heavyweight tool like Calibre’s command-line interface, but that introduced external dependencies and wasn’t as programmatically flexible. Instead, we decided to stick with `ebooklib`\n\nfor high-level book structure and augment it with `lxml`\n\nfor precise XML control.\n\nHere’s the core approach we landed on:\n\n`ebooklib`\n\nto get a list of items (documents, images, CSS).`ITEM_DOCUMENT`\n\n(XHTML) and sometimes `ITEM_NAVIGATION`\n\n(NCX for titles).`lxml`\n\n, extract text, while keeping a map of each text node to its parent element.`ebooklib`\n\n, manually ensuring the OPF and spine are correct.Let’s dive into the code.\n\n``` python\nimport ebooklib\nfrom ebooklib import epub\n\nbook = epub.read_epub('original.epub')\n\ntranslatable_items = []\nfor item in book.get_items():\n    if item.get_type() == ebooklib.ITEM_DOCUMENT:\n        translatable_items.append(item)\n    # Some books use NCX for chapter titles\n    elif item.get_type() == ebooklib.ITEM_NAVIGATION:\n        translatable_items.append(item)\n```\n\nWe ignore images, fonts, and CSS—they don’t contain translatable text.\n\nWe need to extract text while remembering exactly where it came from. We use `lxml.etree`\n\nto parse the XHTML and walk the tree, collecting text nodes and their XPath locations:\n\n``` python\nfrom lxml import etree\n\ndef extract_text_with_xpath(content):\n    parser = etree.HTMLParser()\n    root = etree.fromstring(content, parser)\n    tree = etree.ElementTree(root)\n\n    text_mapping = []  # list of (xpath, original_text, parent_element)\n    for elem in root.iter():\n        if elem.text and elem.text.strip():\n            xpath = tree.getpath(elem)\n            text_mapping.append((xpath, elem.text, elem))\n        if elem.tail and elem.tail.strip():\n            # tail text belongs to the parent, but logically follows the element\n            parent = elem.getparent()\n            xpath = tree.getpath(parent) if parent is not None else None\n            if xpath:\n                text_mapping.append((xpath, elem.tail, elem))\n    return text_mapping\n```\n\nPay attention to `tail`\n\ntext—it’s the text that follows a closing tag, common in interleaved markup. Missing it leads to lost sentences.\n\nWe batch the collected text nodes into chunks that respect LLM token limits. For instance, we group consecutive text from the same XHTML document, aiming for ~3000 tokens per batch. We then send each chunk to our translation model (e.g., Claude 3.5 Sonnet) and receive a block of translated text. We split the translated block back into individual strings by comparing lengths (advanced: we use a diff algorithm to align original and translated sentences). This is simplified here for brevity.\n\nNow we map translations back:\n\n```\nfor (xpath, original, elem), translated_text in zip(text_mapping, translations):\n    # Use xpath to locate the element again (parsed fresh from original)\n    # but we cached the element objects, so we can just update them\n    if elem.text and elem.text == original:\n        elem.text = translated_text\n    elif elem.tail and elem.tail == original:\n        elem.tail = translated_text\n\n# Serialize back to string\nnew_content = etree.tostring(root, encoding='unicode', method='html')\n```\n\nWe return the modified XHTML as a string, ready to replace the item’s content in the EPUB.\n\nHere’s where `ebooklib`\n\nshines. We create a new `EpubBook`\n\n, set the same metadata (title, author, language), and add items:\n\n```\nnew_book = epub.EpubBook()\nnew_book.set_identifier(original_book.get_metadata('DC', 'identifier')[0][0])\nnew_book.set_title(original_book.get_metadata('DC', 'title')[0][0])\nnew_book.set_language(original_book.get_metadata('DC', 'language')[0][0])\n\n# Add all original items, replacing document content where needed\nfor item in original_book.get_items():\n    if item.get_name() in modified_content_map:\n        # Replace with translated XHTML\n        new_content = modified_content_map[item.get_name()]\n        new_item = epub.EpubItem(\n            uid=item.get_id(),\n            file_name=item.get_name(),\n            media_type=item.get_type(),\n            content=new_content.encode('utf-8')\n        )\n    else:\n        # Copy image, CSS, etc. as-is\n        new_item = item\n    new_book.add_item(new_item)\n\n# Replicate the spine and table of contents\nnew_book.spine = original_book.spine\nnew_book.toc = original_book.toc\n\n# Write out\nepub.write_epub('translated.epub', new_book, {})\n```\n\nBut wait—this naive approach can corrupt the OPF. We found that `ebooklib`\n\nsometimes rewrites the spine order incorrectly if the original had complex nesting. To fix this, we manually post-process the written EPUB’s `content.opf`\n\nusing `lxml`\n\n:\n\n``` python\nimport zipfile\nfrom lxml import etree\n\n# Open the new EPUB as a ZIP\nwith zipfile.ZipFile('translated.epub', 'a') as zf:\n    with zf.open('content.opf', 'r') as f:\n        opf = etree.parse(f)\n    # Ensure itemref order matches original spine\n    spine = opf.find('.//{http://www.idpf.org/2007/opf}spine')\n    # Reorder based on original spine list\n    # ... custom correction logic ...\n    zf.writestr('content.opf', etree.tostring(opf, xml_declaration=True, encoding='UTF-8'))\n```\n\nYes, it’s ugly, but it saved us from countless validation errors.\n\nWe benchmarked on a typical novel: 50 chapters, 350KB uncompressed. Parsing and extracting text: ~0.2 seconds. Rebuilding after translation: ~0.3 seconds. The LLM translation step dominates (around 45 seconds for the whole book), so we worked on parallelism for that part instead.\n\nHowever, with larger educational texts containing hundreds of images and complex tables, memory usage spiked to over 500MB. We mitigated this by processing documents one by one and releasing them immediately.\n\n`xmlns=\"http://www.w3.org/1999/xhtml\"`\n\nand any custom namespaces on the `<html>`\n\ntag. Lxml’s `etree.tostring()`\n\nwith `method='html'`\n\ncan drop them unless you explicitly add them back.`epubcheck`\n\n(via Python subprocess) to catch issues. False positives from custom metadata? We whitelist them after manual review.`ebooklib`\n\nis great for reading, but for writing, we ended up doing a lot of OPF and NCX manipulation ourselves to ensure compliance.`<encryption>`\n\nelement in `META-INF/encryption.xml`\n\nand gracefully reject them.We’d love to know how others are managing complex EPUB manipulation in production. Have you found a more robust library than `ebooklib`\n\n? How do you deal with interactive EPUB3 elements (Javascript, form fields) when translating? We’re still iterating on our pipeline and would appreciate any battle stories.\n\nIf you’re tackling similar problems or want to try translating your own eBooks, you can see the result of this work at LectuLibre. But most importantly, we hope this deep dive saves you a few late nights the next time you need to mess with EPUB internals.", "url": "https://wpnews.pro/news/parsing-and-rebuilding-epub-files-in-python-lessons-learned-from-building-an-ai", "canonical_source": "https://dev.to/jacob_gong/parsing-and-rebuilding-epub-files-in-python-lessons-learned-from-building-an-ai-translation-service-jpb", "published_at": "2026-06-20 03:01:16+00:00", "updated_at": "2026-06-20 04:06:58.698780+00:00", "lang": "en", "topics": ["large-language-models", "developer-tools", "natural-language-processing"], "entities": ["LectuLibre", "ebooklib", "lxml", "Claude 3.5 Sonnet"], "alternates": {"html": "https://wpnews.pro/news/parsing-and-rebuilding-epub-files-in-python-lessons-learned-from-building-an-ai", "markdown": "https://wpnews.pro/news/parsing-and-rebuilding-epub-files-in-python-lessons-learned-from-building-an-ai.md", "text": "https://wpnews.pro/news/parsing-and-rebuilding-epub-files-in-python-lessons-learned-from-building-an-ai.txt", "jsonld": "https://wpnews.pro/news/parsing-and-rebuilding-epub-files-in-python-lessons-learned-from-building-an-ai.jsonld"}}