03 Generate them instead of typing (2/2)

  #!/usr/bin/env python3
  """Build a CrossPoint catalog JSON from a folder of EPUBs.
  usage: make_catalog.py books/ https://raw.githubusercontent.com/<you>/my-shelf/main/books > all.json
  """
  import json, sys, zipfile, re, pathlib, urllib.parse
  import xml.etree.ElementTree as ET
  
  NS = {"c": "urn:oasis:names:tc:opendocument:xmlns:container",
        "dc": "http://purl.org/dc/elements/1.1/"}
  
  def meta(epub):
      with zipfile.ZipFile(epub) as z:
          root = ET.fromstring(z.read("META-INF/container.xml"))
          opf_path = root.find(".//c:rootfile", NS).get("full-path")
          opf = ET.fromstring(z.read(opf_path))
          def get(tag):   # itertext: descriptions may contain nested XHTML elements
              el = opf.find(f".//dc:{tag}", NS)
              return "".join(el.itertext()).strip() if el is not None else ""
          desc = re.sub(r"<[^>]+>", "", get("description"))[:600]
          return get("title") or epub.stem, get("creator"), desc
  
  folder, base = pathlib.Path(sys.argv[1]), sys.argv[2].rstrip("/")
  books = []
  for epub in sorted(folder.glob("*.epub")):
      title, author, desc = meta(epub)
      books.append({
          "id": epub.stem,
          "title": title,
          "author": author,
          "summary": desc,
          "file": f"{base}/{urllib.parse.quote(epub.name)}",   # spaces etc. must be encoded
      })
  json.dump({"books": books}, sys.stdout, ensure_ascii=False, indent=1)
‹ PreviousReader file (.txt)