DEV Community

tieli liao
tieli liao

Posted on

Audit EPUB Cover Metadata With a Small Python Script

When an EPUB shows its cover in Apple Books or Calibre but arrives on a Kindle as a grey tile, the image is usually fine. What is broken is the metadata that tells a converter which image is the cover. You can check it yourself with a short, standard-library Python script that reads container.xml, finds the OPF, and compares the EPUB 3 cover-image property, the EPUB 2 <meta name="cover"> reference, the file path and the real image type.

Key takeaways

  • An EPUB is a ZIP. META-INF/container.xml points to the OPF package file, and the OPF is where the cover is declared.
  • EPUB 3 marks the cover with properties="cover-image" on a manifest item. EPUB 2 tooling uses <meta name="cover" content="ITEM-ID"/>.
  • The EPUB 2 content value is a manifest ID, not a filename. Pointing it at cover.jpg is a common bug.
  • Declaring both, pointing at the same item, with a correct media-type, removes ambiguity for different readers and conversion paths.
  • Metadata cannot fix a cached thumbnail. Delete the old copy from your Kindle library before sending a repaired file.

Why does an EPUB show a cover in one app but not on Kindle?

Because reading apps are forgiving and conversion pipelines are strict. Many readers will guess: they pick the first image, or a file called cover.jpg. A conversion service that is building a thumbnail wants one unambiguous declaration. If the EPUB 3 property is missing and the EPUB 2 reference points to an ID that does not exist, there may be no declared cover at all, even though the artwork is sitting in the archive.

Where is the cover declared inside an EPUB?

In the OPF package document, which you find through META-INF/container.xml. Do not assume the OPF is called content.opf or lives in OEBPS/; read the full-path attribute of the rootfile element.

A healthy EPUB 3 package that also keeps EPUB 2 compatibility looks like this:

<metadata xmlns:dc="http://purl.org/dc/elements/1.1/">
  <dc:title>My Book</dc:title>
  <meta name="cover" content="cover"/>           <!-- EPUB 2: an ID -->
</metadata>
<manifest>
  <item id="cover"
        href="images/cover.jpg"
        media-type="image/jpeg"
        properties="cover-image"/>              <!-- EPUB 3 -->
</manifest>
Enter fullscreen mode Exit fullscreen mode

Three things have to agree: the ID, the path (resolved relative to the OPF, not the ZIP root), and the media type. FixMyEPUB's guide to EPUB cover metadata walks through each declaration and a safe repair order if you want the long version.

What should a cover metadata check actually test?

Six things, in this order:

  1. mimetype is the first ZIP entry and is stored without compression (an OCF requirement in the EPUB spec).
  2. container.xml exists and names an OPF.
  3. Exactly one manifest item has properties="cover-image".
  4. A <meta name="cover"> exists and its content is a real manifest ID.
  5. Both declarations point to the same item.
  6. The file exists at the resolved path, and its first bytes match the declared media-type.

The last check catches a surprisingly sneaky case: a PNG renamed to .jpg and declared as image/jpeg. It opens fine on a desktop, but a strict processor may refuse it.

The script

Standard library only: zipfile, xml.etree.ElementTree and posixpath (EPUB paths always use forward slashes, so os.path is the wrong tool on Windows).

import sys, zipfile, posixpath
import xml.etree.ElementTree as ET
from urllib.parse import unquote

NS = {
    "c": "urn:oasis:names:tc:opendocument:xmlns:container",
    "opf": "http://www.idpf.org/2007/opf",
}
MAGIC = {b"\xff\xd8\xff": "image/jpeg", b"\x89PNG": "image/png"}

def audit(path):
    z = zipfile.ZipFile(path)
    names = z.namelist()
    problems = []

    # 1. mimetype must be the first entry, stored uncompressed
    first = z.infolist()[0]
    if first.filename != "mimetype" or first.compress_type != zipfile.ZIP_STORED:
        problems.append("mimetype is not the first, uncompressed entry")

    # 2. container.xml tells us where the OPF lives
    container = ET.fromstring(z.read("META-INF/container.xml"))
    opf_path = container.find(".//c:rootfile", NS).get("full-path")
    opf_dir = posixpath.dirname(opf_path)
    opf = ET.fromstring(z.read(opf_path))
    print("OPF:", opf_path, "| version", opf.get("version"))

    items = {i.get("id"): i for i in opf.findall(".//opf:manifest/opf:item", NS)}

    # 3. EPUB 3 declaration
    epub3 = [i for i in items.values() if "cover-image" in (i.get("properties") or "").split()]
    # 4. EPUB 2 declaration (content is an ID, not a filename)
    meta = opf.find(".//opf:metadata/opf:meta[@name='cover']", NS)
    epub2_id = meta.get("content") if meta is not None else None

    if not epub3:
        problems.append("no manifest item has properties='cover-image' (EPUB 3)")
    if len(epub3) > 1:
        problems.append("more than one item is marked cover-image")
    if epub2_id is None:
        problems.append("no <meta name='cover'> (EPUB 2 compatibility)")
    elif epub2_id not in items:
        problems.append(f"<meta name='cover'> points to missing id '{epub2_id}'")
    if epub3 and epub2_id and epub3[0].get("id") != epub2_id:
        problems.append("EPUB 2 and EPUB 3 declarations point to different items")

    # 5. Does the declared file exist, and is the media type honest?
    for item in epub3 + ([items[epub2_id]] if epub2_id in items else []):
        href = posixpath.normpath(posixpath.join(opf_dir, unquote(item.get("href"))))
        if href not in names:
            problems.append(f"cover href resolves to {href}, which is not in the archive")
            continue
        head = z.read(href)[:4]
        actual = next((t for m, t in MAGIC.items() if head.startswith(m)), "unknown")
        if actual != "unknown" and actual != item.get("media-type"):
            problems.append(f"{href} is declared {item.get('media-type')} but looks like {actual}")

    return problems

if __name__ == "__main__":
    issues = audit(sys.argv[1])
    print("\n".join(f"- {p}" for p in sorted(set(issues))) or "Cover declarations look consistent.")
Enter fullscreen mode Exit fullscreen mode

Run it with python3 cover_audit.py book.epub.

What does the output look like?

Here is the script's real output on three small synthetic test EPUBs, run with Python 3.13.

A file where the EPUB 2 tag uses the filename instead of the ID, and the EPUB 3 property is missing:

OPF: EPUB/package.opf | version 3.0
- <meta name='cover'> points to missing id 'cover.jpg'
- no manifest item has properties='cover-image' (EPUB 3)
Enter fullscreen mode Exit fullscreen mode

A "half-fixed" file where both declarations are right, but the image is really a PNG declared as JPEG:

OPF: EPUB/package.opf | version 3.0
- EPUB/images/cover.jpg is declared image/jpeg but looks like image/png
Enter fullscreen mode Exit fullscreen mode

And a consistent file:

OPF: EPUB/package.opf | version 3.0
Cover declarations look consistent.
Enter fullscreen mode Exit fullscreen mode

How do I fix what the script finds?

Fix the declarations so that one manifest item is the cover, then rebuild the ZIP correctly.

  • Missing EPUB 3 property: add properties="cover-image" to the image item. If the item already has other properties, separate them with spaces.
  • EPUB 2 tag points to a filename: change content to the item's id.
  • Declarations disagree: pick the real cover image and point both at it. Do not promote the first image in the book; it may be a publisher logo.
  • Wrong media type: either convert the file or correct media-type to match it (image/jpeg, image/png).
  • Rebuilding: write mimetype first with ZIP_STORED, then everything else. Zipping the folder with a desktop tool often gets this wrong.
with zipfile.ZipFile("fixed.epub", "w") as out:
    out.writestr(zipfile.ZipInfo("mimetype"), "application/epub+zip",
                 compress_type=zipfile.ZIP_STORED)
    # then add every other file with ZIP_DEFLATED
Enter fullscreen mode Exit fullscreen mode

If you would rather not edit XML, the free fixer at https://fixmyepub.com/ runs the same kind of checks in the browser, writes a repaired copy, and does not upload the book anywhere. It only handles DRM-free files under 100 MB.

What this script does not cover

It checks cover declarations, not the whole book. It does not validate XHTML, the spine or the navigation document, and it does not handle EPUBs with more than one rootfile. For full validation, run EPUBCheck, the reference validator (github.com/w3c/epubcheck). It also cannot fix Kindle-side caching: if an older copy of the same document is still in your library, you may keep seeing the old grey thumbnail. Remove it, let the library sync, then send the repaired file once.

Frequently asked questions

Is the EPUB 2 meta name="cover" still needed in an EPUB 3 file?
It is not required by EPUB 3, but keeping it, pointed at the same item as cover-image, helps older readers and conversion paths that still look for it.

Does the cover need to be a JPEG?
JPEG and PNG are the safe choices. Whatever you use, the declared media-type must match the actual file.

Why is my cover still grey after fixing the file?
Most likely a cached thumbnail or a duplicate document. Delete the old copy from your Kindle library before sending the repaired one.

Can this script remove DRM or fix purchased Kindle books?
No. It only reads DRM-free EPUB files you are allowed to modify.

Will this fix a "Send to Kindle failed" error?
Only if the failure is caused by the cover or packaging. Rejections can also come from broken manifest or spine references or invalid XML, which need a fuller validator.

Wrap-up

A grey Kindle cover is usually a three-way disagreement between an ID, a path and a media type. A short Python script is enough to see which one is wrong, and fixing it is a two-line edit in the OPF plus a correctly ordered ZIP.

Top comments (0)