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

推荐订阅源

T
Threat Research - Cisco Blogs
C
CERT Recently Published Vulnerability Notes
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
S
Securelist
K
Kaspersky official blog
V
Vulnerabilities – Threatpost
C
Cisco Blogs
Application and Cybersecurity Blog
Application and Cybersecurity Blog
Hacker News: Ask HN
Hacker News: Ask HN
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
S
Security Affairs
Forbes - Security
Forbes - Security
Spread Privacy
Spread Privacy
C
CXSECURITY Database RSS Feed - CXSecurity.com
P
Palo Alto Networks Blog
H
Hacker News: Front Page
L
Lohrmann on Cybersecurity
Cloudbric
Cloudbric
S
Schneier on Security
Simon Willison's Weblog
Simon Willison's Weblog
I
InfoQ
人人都是产品经理
人人都是产品经理
PCI Perspectives
PCI Perspectives
月光博客
月光博客
爱范儿
爱范儿
Jina AI
Jina AI
WordPress大学
WordPress大学
N
News and Events Feed by Topic
Cyberwarzone
Cyberwarzone
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
小众软件
小众软件
Google Online Security Blog
Google Online Security Blog
W
WeLiveSecurity
V
V2EX
阮一峰的网络日志
阮一峰的网络日志
美团技术团队
博客园 - 司徒正美
Scott Helme
Scott Helme
AI
AI
L
LangChain Blog
A
Arctic Wolf
博客园 - 【当耐特】
量子位
S
SegmentFault 最新的问题
The GitHub Blog
The GitHub Blog
MyScale Blog
MyScale Blog
腾讯CDC
博客园 - 叶小钗
Last Week in AI
Last Week in AI
S
Secure Thoughts

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
龚旭东 · 2026-06-27 · via DEV Community

龚旭东

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:

  1. Accept any EPUB the user throws at us.
  2. Extract all text content while preserving the exact structure.
  3. Send each paragraph to an LLM for translation.
  4. Re‑insert the translated text into the original XHTML files.
  5. 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) -> epub.EpubBook:
    book = epub.read_epub(epub_path, {"ignore_ncx": True})
    # Force title to be a string (some books have list titles)
    if isinstance(book.title, list):
        book.title = " ".join(book.title)
    return book

But we quickly learned that read_epub can fail silently if the book’s metadata is corrupted. We added a custom validation step that checks for a valid OPF and at least one spine item.

def validate_epub(book: epub.EpubBook):
    if not book.opf:
        raise ValueError("Missing OPF metadata")
    if len(list(book.spine)) == 0:
        raise ValueError("No spine items found – EPUB is unreadable")

Step 2: Extracting Readable Text from XHTML Documents

An EPUB’s content is stored in epub.EpubHtml objects. We iterate over all items in reading order (spine) and parse the body content with BeautifulSoup (lxml parser) because ebooklib’s own get_body_content() returns raw bytes, and we need to extract text paragraph‑by‑paragraph while keeping the HTML structure.

from bs4 import BeautifulSoup
import html

def extract_paragraphs(item: epub.EpubHtml) -> list[dict]:
    soup = BeautifulSoup(item.get_body_content(), "html.parser")
    paragraphs = []
    for tag in soup.find_all(["p", "h1", "h2", "h3", "h4", "h5", "h6", "li"]):
        clean_text = tag.get_text(strip=True)
        if clean_text:
            paragraphs.append({
                "tag": tag,
                "original": clean_text,
                "translated": None
            })
    return paragraphs

We keep a reference to the original BeautifulSoup tag object so we can later replace its text. This is memory‑heavy for large books but works for books under 10 MB (our VPS limit).

Step 3: Translating with an LLM (and Controlling Length)

For each paragraph we call our translation API (Claude or DeepSeek). The tricky part is that some paragraphs are very short (headers) or contain entity references. We escape HTML entities before sending, and decode them afterward.

import requests

def translate_text(text: str, source_lang: str, target_lang: str) -> str:
    escaped = html.escape(text, quote=False)
    response = requests.post(
        "https://api.lectulibre.com/v1/translate",  # simplified
        json={"text": escaped, "source": source_lang, "target": target_lang},
        headers={"Authorization": f"Bearer {API_KEY}"}
    )
    translated = response.json()["translated"]
    return html.unescape(translated)

We found that LLMs can sometimes add extra spaces or punctuation. We apply a light post‑processing: trim, normalize spaces, and ensure the translated text doesn’t break the containing tag’s structure.

Step 4: Rebuilding the XHTML with Translated Text

Back in the extract_paragraphs output, we replace the tag.string with the translated text. Since tag.string might be a NavigableString containing child elements, we must be careful. If the tag contains only a string, we replace it. If it contains mixed content, we replace the first text node only, which is a simplification that works for most books.

def replace_text(tag, new_text: str):
    if tag.string is not None and not tag.find_all(text=False):
        # Simple case: tag has only a single text node
        tag.string.replace_with(new_text)
    else:
        # Find the first text node and replace it
        for child in tag.children:
            if isinstance(child, str) and child.strip():
                child.replace_with(new_text)
                break

After all replacements, we set the item’s body content back to the modified HTML.

def update_item(item: epub.EpubHtml, paragraphs: list[dict]):
    for p in paragraphs:
        if p["translated"]:
            replace_text(p["tag"], p["translated"])
    # Rebuild the HTML
    html_str = p["tag"].prettify()  # or extract the full soup
    item.set_body_content(html_str.encode("utf-8"))

A problem here: set_body_content expects bytes, and we must ensure the encoding is UTF‑8. Also, if the original file had a XML declaration or namespaces, we might lose them. We handle that by preserving the item.media_type and other metadata.

Step 5: Writing the Translated EPUB

Once all items are updated, we write the book to a new file. We also add a modified‑date and update the language metadata.

def save_book(book: epub.EpubBook, output_path: str):
    book.set_identifier("urn:uuid:" + str(uuid.uuid4()))
    book.add_metadata("DC", "language", "fr")  # target language
    epub.write_epub(output_path, book, {})

We learned the hard way that epub.write_epub may fail if items reference resources (images, fonts) that aren’t properly registered in the manifest. We iterate all items from the original book and add them to the manifest early to avoid missing dependency errors.

Real‑World Pitfalls and How We Solved Them

  1. Broken Table of Contents: After translation, the NCX/NAV files pointed to old file names or anchors that no longer existed because we had renamed items. We now never rename items; we only modify their content in-place. If we must add new items (e.g., for footnotes), we update the TOC manually using ebooklib.epub.Link objects.

  2. Inline CSS Overwrites: Some books use inline styles like font-size: 12pt. When a translated paragraph becomes longer, it can overflow fixed‑height containers. We don’t modify CSS, but we added a warning for books with rigid styling and offer a “clean” version without fixed heights.

  3. Performance: For a 500‑page novel, the entire pipeline (parse, translate, rebuild) takes about 90 seconds on our VPS (4 vCPU, 8 GB RAM). The LLM calls dominate; we batch paragraphs of up to 5 together to reduce API overhead, trading off a slight translation quality dip.

  4. Memory: Loading the entire EPUB and keeping BeautifulSoup trees in memory can spike to 300 MB for large books. We process one book at a time and use a queue to avoid concurrency issues.

Lessons Learned

  • ebooklib is great but fragile – always validate the EPUB structure yourself; don’t assume all fields are present.
  • Preserve the original item order and names – renaming breaks internal links.
  • Escape/unescape HTML entities when moving text between HTML and plain text.
  • Translation quality depends on context – we’re experimenting with sending the entire chapter instead of individual paragraphs, but that increases latency.

What’s Next?

We’re exploring pandoc for pre‑conversion to a simpler intermediate format that’s easier to manipulate. However, the rebuild step becomes more complex. For now, ebooklib + BeautifulSoup serves our needs.

If you’re building an EPUB processing tool in Python, I hope these real‑world insights save you some of the debugging hours we spent. Got a better approach? I’d love to hear it in the comments!

Happy coding!