Writing an EPUB parser. Part 1
Tags: python, epub
Published: 2023-02-01 02:35:20

---
title: Writing an EPUB parser. Part 1
published: true
date: 2022-06-01 05:41:00 UTC
tags: Python,epub,python
canonical_url: https://tyrel.dev/blog/2022/06/writing-an-epub-parser-part-1.html
---

## Parsing Epubs

Recently I've become frustrated with the experience of reading books on my Kindle Paperwhite. The swipe features, really bother me. I really like MoonReader on Android, but reading on my phone isn't always pleasing. This lead me to look into other hardware. I've been eyeing the BOOX company a while ago, but definitely considering some of their new offerings some time. Until the time I can afford the money to splurge on a new ebook reader, I've decided to start a new project, making my own ebook reader tools!

I'm starting with EPUBs, as this is one of the easiest to work with. At its core, an EPUB is a zip file with the <tt>.epub</tt> extension instead of <tt>.epub</tt> with many individual XHTML file chapters inside it. You can read more of how they're structured yourself over at [FILEFORMAT](https://docs.fileformat.com/ebook/epub/).

The tool I've chosen for reading EPUBs is the Python library [ebooklib](https://pypi.org/project/EbookLib/). This seemed to be a nice lightweight library for reading EPUBs. I also used [DearPyGUI](https://pypi.org/project/dearpygui/) for showing this to the screen, because I figured why not, I like GUI libraries.

My first task was to find an EPUB file, so I downloaded one from my calibre server. I convert all my ebook files to <tt>.epub</tt> and <tt>.mobi</tt> on my calibre server so I can access them anywhere I can read my OPDS feed. I chose Throne of Glass (abbreviating to <tt>TOG.epub</tt> for rest of post). Loading I launched Python, and ran

```

>>> from ebooklib import epub >>> print(book := epub.read\_epub("TOG.epub")

```

This returned me a <tt>&lt;ebooklib.epub.EpubBook <span>object...&gt;</span></tt> , seeing I had an EpubBook I ran a <tt>dir(book)</tt> and found the properties available to me

```

['add\_author', 'add\_item', 'add\_metadata', 'add\_prefix',
 'bindings',
 'direction',
 'get\_item\_with\_href', 'get\_item\_with\_id', 'get\_items',
   'get\_items\_of\_media\_type', 'get\_items\_of\_type', 'get\_metadata',
   'get\_template', 'guide',
 'items',
 'language',
 'metadata',
 'namespaces',
 'pages', 'prefixes',
 'reset',
 'set\_cover', 'set\_direction', 'set\_identifier', 'set\_language', 'set\_template', 'set\_title', 'set\_unique\_metadata', 'spine',
 'templates', 'title', 'toc',
 'uid',
 'version']

```

Of note, the <tt>get_item_with_X</tt> entries caught my eye, as well as <tt>spine</tt>. For my file, <tt>book.spine</tt> looks like it gave me a bunch of tuples of ID and a <tt>"yes"</tt> string of which I had no Idea what was. I then noticed I had a <tt>toc</tt> property, assuming that was a Table of Contents, I printed that out and saw a bunch of <tt>epub.Link</tt> objects. This looks like something I could use.

I will note, at this time I was thinking that this wasn't the direction I wanted to take this project. I really wanted to learn how to parse these things myself, unzip, parse XML, or HTML, etc., but I realized I needed to see someone else's work to even know what is going on. With this "defeat for the evening" admitted, I figured hey, why not at least make SOMETHING, right?" I decided to carry on.

Seeing I was on at least some track, I opened up PyCharm and made a new Project. First I setup a class called Epub, made a couple of functions for setting things up and ended up with

```

class Epub:
    def \_\_init\_\_(self, book\_path: str) -> None:
        self.contents: ebooklib.epub.EpubBook = epub.read\_epub(book\_path)
        self.title: str = self.contents.title
        self.toc: List[ebooklib.epub.Link] = self.contents.toc

```

I then setup a <tt>parse_chapters</tt> file, where I loop through the TOC. Here I went to the definition of <tt>Link</tt> and saw I was able to get a <tt>href</tt> and a <tt>title</tt>, I decided my object for chapters would be a dictionary (I'll move to a DataClass later) with <tt>title</tt> and <tt>content</tt>. I remembered from earlier I had a <tt>get_item_by_href</tt> so I stored the itext from the TOC's href: <tt><span>self.contents.get_item_with_href(link.href).get_content()</span></tt>. This would later prove to be a bad decision when I opened "The Fold.epub" and realized that a TOC could have a tuple of <tt>Section</tt> and <tt>Link</tt>, not just <tt>Links</tt>. I ended up storing the item itself, and doing a double loop in the <tt>parse_chapters</tt> function to loop if it's a tuple.

```

def parse\_chapters(self) -> None:
    idx = 0
    for \_item in self.toc:
        if isinstance(\_item, tuple): # In case is section tuple(section, [link, ...])
            for link in \_item[1]:
                self.\_parse\_link(idx, link)
                idx += 1
        else:
            self.\_parse\_link(idx, \_item)
            idx += 1

```

<tt>_parse_link</tt> simply makes that dictionary of <tt>title</tt> and <tt>item</tt> I mentioned earlier, with a new <tt>index</tt> as I introduced buttons in the DearPyGUI at this time as well.

```

def \_parse\_link(self, idx, link) -> None:
    title = link.title
    self.chapters.append(dict(
        index=idx,
        title=title,
        item=self.contents.get\_item\_with\_href(link.href)
    ))

```

That's really all there is to make an MVP of an EPUB parser. You can use <tt>BeautifulSoup</tt> to parse the HTML from the <tt>get_body_contents()</tt> calls on items, to make more readable text if you want, but depending on your front end, the HTML may be what you want.

In my implementation my Epub class keeps track of the currently selected chapter, so this loads from all chapters and sets the <tt>current_text</tt> variable.

```

def load\_view(self) -> None:
    item = self.chapters[self.current\_index]['item']
    soup = BeautifulSoup(item.get\_body\_content(), "html.parser")
    text = [para.get\_text() for para in soup.find\_all("p")]
    self.current\_text = "\n".join(text)

```

I don't believe any of this code will be useful to anyone outside of my research for now, but it's my first step into writing an EPUB parser myself.

The DearPyGUI steps are out of scope of this blog post, but here is my [final ebook Reader](https://gist.github.com/tyrelsouza/9c6681850fc00bf5d9f35568faf611d4) which is super inefficient!

 ![final ebook reader, chapters on left, text on right](https://tyrel.dev/blog/images/2022/06/ebook-ebook_reader.png)

I figure the Dedication page is not _as_ copywrited as the rest of the book, so it's fair play showing that much. Sarah J Maas, if you have any issues, I can find another book for my screenshots.