See Ash Code logo See Ash Code
Completed Creator

Ebook2Text

A Python package for extracting normalized text from ebooks and documents.

Python OCR Document parsing Packaging

From books to usable text

Ebooks and manuscripts don’t all store their contents the same way. An EPUB contains structured HTML, a DOCX contains paragraphs and embedded objects, and a PDF can mix selectable text with images. For an application that needs the words, that variety creates work before any analysis can begin.

I built ebook2text as a Python package that accepts EPUB, DOCX, PDF, and plain-text files and produces a common text representation. It identifies chapter breaks, marks them with three asterisks, and normalizes smart punctuation. The caller can write the result to a file or get a string back for further processing. The package is published on PyPI, and the source is on GitHub.

The interesting part has been deciding how much behavior the formats can share. Extracting a PDF page and extracting a Word paragraph are both text-processing tasks, but they don’t expose the same objects or fail in the same ways.

One entry point, different converters

convert_file examines the file extension and initializes the corresponding converter. Each converter reads its own format and works with text extraction, image extraction, and shared text utilities as appropriate. Text files take a simpler path through TextParser.

EPUB / DOCX / PDF / TXT
          ↓
     convert_file
          ↓
 format-specific reader → image extraction → OCR provider
          ↓                                      ↓
       text processing and chapter detection
          ↓
    text file or string

This gives an application one entry point without pretending all documents have the same internal structure. It also makes the output contract visible: a successful call returns or writes text, while unsupported extensions raise an error.

The architecture changed as I learned where the similarities ended. An earlier version used shared parent classes for converters and extractors. The parent stored common settings and required child methods, but a single abstract object had to represent both a DOCX paragraph stream and PDF page layouts. I removed those inheritance relationships and made each converter initialize its own input. The trade-off was some repeated setup in exchange for seeing format-specific behavior where it is used. Shared operations such as punctuation normalization remained utilities.

PDF extraction: two paths to the same page

A PDF can contain a mixture of extractable text and images that need optical character recognition (OCR). Both paths contribute to the final output, and each has its own failure modes.

One bug joined pieces of extracted text without a separator. If one piece ended with continue and the next began with on, the result could become continueon. Adding a space in the continuation case fixed that particular loss of word boundaries. It did not solve PDF layout in general: punctuation at the end of a line is still only a clue about where a paragraph ends.

Image extraction posed a different problem. Width and height alone don’t explain how to interpret a PDF image’s bytes. The extractor reads color-space and bit-depth information to select an image mode, handles grayscale, RGB, and CMYK inputs, and expands packed pixel values where needed. A later fix normalized PDF color spaces before saving images. These details matter because incorrectly interpreted pixels give the OCR model a distorted input before it even tries to read the page.

The project history also records a failure-handling mistake. An invalid PDF caused the reader to log PDFSyntaxError and then stop yielding pages, making a failed read look like an empty conversion to the caller. The fix re-raised the exception. Because the reader is a generator, the regression test had to consume the pages to reach the error; constructing the converter alone would not exercise the parse.

OCR without coupling the converters to a provider

Image OCR is separated behind an OCRProvider interface. The package includes implementations for OpenAI, Gemini, Anthropic, and OpenRouter; a caller can also pass an object that implements perform_ocr. Provider modules are loaded lazily, and Gemini and Anthropic are optional dependencies. Text-only conversions don’t require OCR credentials.

This design lets an application choose an OCR backend without rewriting PDF or DOCX extraction. It doesn’t make all providers interchangeable in quality, latency, or cost. The caller still needs to select a model and review results where accuracy matters.

The configuration itself evolved. A previous implementation read an OCR model name when its module loaded, which made a missing or mismatched environment variable an import-time problem. The current provider factory resolves configuration when a provider is requested. That moves the dependency closer to the operation that needs it.

Testing and maintenance

The test suite includes real PDF, EPUB, and DOCX fixtures, including files with images, alongside smaller tests for chapter detection and format-specific helpers. File fixtures exercise the boundary between an actual document and the parser; mocked OCR responses make it possible to check how the converter combines returned text without buying an API response for every test. A mocked response does not establish that a model can read the image correctly.

The package has also required maintenance beyond its conversion logic: dependency changes, Python compatibility, release automation, and the behavior of the EPUB library used underneath it. The README still identifies additional edge cases, failure states, and formats as future work. The project is a working extraction tool, not a guarantee that every document’s layout or every OCR result will be recovered perfectly.