06 Companion make_catalog.py (2/2)

def main():
    if len(sys.argv) != 3:
        sys.exit(__doc__)
    folder = pathlib.Path(sys.argv[1])
    base = sys.argv[2].rstrip("/")
    books = []
    for epub in sorted(folder.glob("*.epub")):
        try:
            title, author, description = metadata(epub)
        except (KeyError, AttributeError, ET.ParseError, zipfile.BadZipFile) as e:
            print(f"skipping {epub.name}: {e}", file=sys.stderr)
            continue
        books.append({
            # ids end up inside a JSON sidecar template: keep them simple.
            "id": re.sub(r"[^a-z0-9-]+", "-", epub.stem.lower()).strip("-"),
            "title": title,
            "author": author,
            "summary": description,
            "file": f"{base}/{urllib.parse.quote(epub.name)}",
        })
    json.dump({"books": books}, sys.stdout, ensure_ascii=False, indent=1)
    print()

if __name__ == "__main__":
    main()
‹ PreviousReader file (.txt)