惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

F
Fortinet All Blogs
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
有赞技术团队
有赞技术团队
www.infosecurity-magazine.com
www.infosecurity-magazine.com
大猫的无限游戏
大猫的无限游戏
爱范儿
爱范儿
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
T
Threatpost
V
Visual Studio Blog
Apple Machine Learning Research
Apple Machine Learning Research
博客园 - Franky
人人都是产品经理
人人都是产品经理
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
The Cloudflare Blog
N
News and Events Feed by Topic
L
Lohrmann on Cybersecurity
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
酷 壳 – CoolShell
酷 壳 – CoolShell
V
V2EX
AWS News Blog
AWS News Blog
S
SegmentFault 最新的问题
T
Tailwind CSS Blog
Hugging Face - Blog
Hugging Face - Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
Spread Privacy
Spread Privacy
J
Java Code Geeks
博客园 - 聂微东
T
Tor Project blog
宝玉的分享
宝玉的分享
博客园 - 叶小钗
Webroot Blog
Webroot Blog
博客园 - 【当耐特】
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
H
Heimdal Security Blog
Y
Y Combinator Blog
T
The Blog of Author Tim Ferriss
MongoDB | Blog
MongoDB | Blog
I
InfoQ
Security Latest
Security Latest
Martin Fowler
Martin Fowler
Hacker News: Ask HN
Hacker News: Ask HN
P
Privacy International News Feed
C
CERT Recently Published Vulnerability Notes
Latest news
Latest news
雷峰网
雷峰网
D
Darknet – Hacking Tools, Hacker News & Cyber Security
C
Cisco Blogs
H
Help Net Security
L
LINUX DO - 最新话题
L
LINUX DO - 热门话题

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Parsing and Rebuilding EPUB Files in Python: Lessons Learned from Building an AI Translation Service
龚旭东 · 2026-06-20 · via DEV Community

龚旭东

How we extract, translate, and reconstruct entire ebooks with Python while preserving every detail

At 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.

EPUB is essentially a ZIP file containing a structured set of XHTML, CSS, and XML files. The content.opf file defines the reading order (spine), metadata, and manifest. The toc.ncx holds 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.

The Problem with Off-the-Shelf Libraries

We initially reached for ebooklib, 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:

  • Metadata loss: ebooklib didn’t fully preserve custom metadata or namespace-prefixed properties in the OPF.
  • Namespace handling: When modifying XHTML, it could strip or mangle xmlns attributes, breaking rendering on some devices.
  • TOC and spine sync: After rebuilding, the table of contents and spine often got out of sync unless we manually repaired them.
  • Large files: Processing a 200‑chapter book consumed surprising memory because ebooklib loaded 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 for high-level book structure and augment it with lxml for precise XML control.

Our Parsing and Rebuilding Pipeline

Here’s the core approach we landed on:

  1. Read the EPUB with ebooklib to get a list of items (documents, images, CSS).
  2. Identify translatable content – usually ITEM_DOCUMENT (XHTML) and sometimes ITEM_NAVIGATION (NCX for titles).
  3. Parse each XHTML document with lxml, extract text, while keeping a map of each text node to its parent element.
  4. Send blocks of text to the LLM for translation, preserving order and context.
  5. Rebuild the XHTML by replacing original text nodes with their translations using the saved mapping.
  6. Write the new EPUB with ebooklib, manually ensuring the OPF and spine are correct.

Let’s dive into the code.

Step 1: Reading and Filtering Items

import ebooklib
from ebooklib import epub

book = epub.read_epub('original.epub')

translatable_items = []
for item in book.get_items():
    if item.get_type() == ebooklib.ITEM_DOCUMENT:
        translatable_items.append(item)
    # Some books use NCX for chapter titles
    elif item.get_type() == ebooklib.ITEM_NAVIGATION:
        translatable_items.append(item)

We ignore images, fonts, and CSS—they don’t contain translatable text.

Step 2: Extracting Text with Context

We need to extract text while remembering exactly where it came from. We use lxml.etree to parse the XHTML and walk the tree, collecting text nodes and their XPath locations:

from lxml import etree

def extract_text_with_xpath(content):
    parser = etree.HTMLParser()
    root = etree.fromstring(content, parser)
    tree = etree.ElementTree(root)

    text_mapping = []  # list of (xpath, original_text, parent_element)
    for elem in root.iter():
        if elem.text and elem.text.strip():
            xpath = tree.getpath(elem)
            text_mapping.append((xpath, elem.text, elem))
        if elem.tail and elem.tail.strip():
            # tail text belongs to the parent, but logically follows the element
            parent = elem.getparent()
            xpath = tree.getpath(parent) if parent is not None else None
            if xpath:
                text_mapping.append((xpath, elem.tail, elem))
    return text_mapping

Pay attention to tail text—it’s the text that follows a closing tag, common in interleaved markup. Missing it leads to lost sentences.

Step 3: Translating in Chunks

We 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.

Step 4: Replacing Text in the Original XHTML

Now we map translations back:

for (xpath, original, elem), translated_text in zip(text_mapping, translations):
    # Use xpath to locate the element again (parsed fresh from original)
    # but we cached the element objects, so we can just update them
    if elem.text and elem.text == original:
        elem.text = translated_text
    elif elem.tail and elem.tail == original:
        elem.tail = translated_text

# Serialize back to string
new_content = etree.tostring(root, encoding='unicode', method='html')

We return the modified XHTML as a string, ready to replace the item’s content in the EPUB.

Step 5: Rebuilding the EPUB

Here’s where ebooklib shines. We create a new EpubBook, set the same metadata (title, author, language), and add items:

new_book = epub.EpubBook()
new_book.set_identifier(original_book.get_metadata('DC', 'identifier')[0][0])
new_book.set_title(original_book.get_metadata('DC', 'title')[0][0])
new_book.set_language(original_book.get_metadata('DC', 'language')[0][0])

# Add all original items, replacing document content where needed
for item in original_book.get_items():
    if item.get_name() in modified_content_map:
        # Replace with translated XHTML
        new_content = modified_content_map[item.get_name()]
        new_item = epub.EpubItem(
            uid=item.get_id(),
            file_name=item.get_name(),
            media_type=item.get_type(),
            content=new_content.encode('utf-8')
        )
    else:
        # Copy image, CSS, etc. as-is
        new_item = item
    new_book.add_item(new_item)

# Replicate the spine and table of contents
new_book.spine = original_book.spine
new_book.toc = original_book.toc

# Write out
epub.write_epub('translated.epub', new_book, {})

But wait—this naive approach can corrupt the OPF. We found that ebooklib sometimes rewrites the spine order incorrectly if the original had complex nesting. To fix this, we manually post-process the written EPUB’s content.opf using lxml:

import zipfile
from lxml import etree

# Open the new EPUB as a ZIP
with zipfile.ZipFile('translated.epub', 'a') as zf:
    with zf.open('content.opf', 'r') as f:
        opf = etree.parse(f)
    # Ensure itemref order matches original spine
    spine = opf.find('.//{http://www.idpf.org/2007/opf}spine')
    # Reorder based on original spine list
    # ... custom correction logic ...
    zf.writestr('content.opf', etree.tostring(opf, xml_declaration=True, encoding='UTF-8'))

Yes, it’s ugly, but it saved us from countless validation errors.

Performance and Real-World Numbers

We 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.

However, 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.

Key Lessons Learned

  1. Namespaces are the devil: Always preserve xmlns="http://www.w3.org/1999/xhtml" and any custom namespaces on the <html> tag. Lxml’s etree.tostring() with method='html' can drop them unless you explicitly add them back.
  2. Validate, validate, validate: After rebuilding, we run epubcheck (via Python subprocess) to catch issues. False positives from custom metadata? We whitelist them after manual review.
  3. Don’t trust the library for everything: ebooklib is great for reading, but for writing, we ended up doing a lot of OPF and NCX manipulation ourselves to ensure compliance.
  4. Handle encoding upfront: Some old EPUBs use Latin-1. We transcode everything to UTF-8 early in the pipeline to avoid crashes later.
  5. DRM is a dead end: We detect encrypted books by checking the <encryption> element in META-INF/encryption.xml and gracefully reject them.

The Open Question for the Community

We’d love to know how others are managing complex EPUB manipulation in production. Have you found a more robust library than ebooklib? 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.

If 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.