Open selected JPEG 2000 leaves directly from an Internet Archive book ZIP, retain printed labels and export approved spreads in book reading order. Include a verified Smithsonian example.
Browse filesFiles changed (5)
123456789101112131415161718192021222324252627282930313233343536373839# Open an Internet Archive book in Folio Fold
An Internet Archive scan can contain a cover, one printed page or two facing pages. This command lists the scans in a JPEG 2000 ZIP, opens the selected leaves for review and exports the pages you keep. For a Japanese book with right-to-left progression, it records the right half of each approved spread first.
[Download the three-leaf example kit](archive-jp2-review.zip?download=true) · [Download the importer](archive_book.py?download=true)
## Try three leaves
Extract the example kit and run the commands below from its root directory with Python 3.10 or later. Installation downloads the model once. Review and export then run offline.
```bashpython -m pip install -r requirements.txtpython archive_book.py list sample_jp2.zip scandata.xmlpython archive_book.py prepare sample_jp2.zip scandata.xml review --leaves 1-2,4```
Open `review/index.html`. Leaf 1 is the front cover. Choose **Keep whole page**. Leaf 2 shows the two printed pages catalogued as “1 and 2.” Check the proposed fold against the binding, adjust its ends if needed and choose **Approve cut**. Leaf 4 is an illustrated spread labelled “5 and 6.” Choose **Skip** to leave that spread out of this export. Save the decisions and place the downloaded JSON beside the ZIP.
```bashpython archive_book.py export sample_jp2.zip review fold-decisions.json pages```
Open `pages/leaf-000001/whole.png` for the cover. For the preface, open `pages/leaf-000002/right.png`, then `left.png`. Both files retain all pixels on their respective sides of the reviewed cut. Transparent padding fills the rectangular tile around an angled cut. For applications that place the halves back on the scan, `pages/pages.json` records the column where the right tile starts.
## Use another book
Download its original `*_jp2.zip` and matching `*_scandata.xml`. Use `list` to see which leaves are present, their page types and any printed labels. Add `--json` for the full catalog. Give `--leaves` the **leaf numbers** in the first column. Commas and inclusive ranges are supported. Omitting the option prepares every JP2 member with its corresponding XML record. The example ZIP contains three original members, so the catalog also shows the other twelve leaves from the complete XML as missing.
The importer matches the numeric suffix of a JP2 filename to `leafNum` in the XML. It keeps numeric leaf order even when printed page numbers are absent, repeated or paired on one scan. When the XML supplies an item identifier, it must agree with the common JP2 filename prefix. `review/book.json` records each selected member path, SHA-256, decoded dimensions, catalog dimensions, page type, printed labels and access-format flag. Export verifies the reviewed member bytes and dimensions.
`pages/pages.json` gives the physical filenames and a `reading_order` list for each exported leaf. That order follows explicit `rl` or `lr` book progression. If progression is missing or unrecognized, the split files remain labelled by physical side and their reading order is `null`. The catalog's printed labels describe the complete scan.
The tool reads boxed `.jp2` images with unsigned 8-bit grayscale or three-component samples, using Pillow with JPEG 2000 support. Output PNGs use the decoded raster dimensions. The tool leaves catalog crop boxes and rotation instructions unapplied and records the `addToAccessFormats` flag for you to consider when selecting leaves. Only approved cuts and whole-page decisions are exported. Use a new directory for each run.
## Source and credits
The example uses volume 1 of *Ehon kyōka yama mata yama* (1804), digitized and contributed by Smithsonian Libraries. The library identifies the work as public domain. The kit includes three byte-identical JPEG 2000 members and the complete original scan metadata. Folio Kestrel selected the examples and wrote the importer. The Python code uses Apache 2.0. [Library scan and source downloads](https://archive.org/details/ehonkyoykayamamv1kats) · [Item metadata and rights statement](https://archive.org/metadata/ehonkyoykayamamv1kats)
[Catalog credits and original file checksums](SOURCES.md)12345# Source of the JPEG 2000 leaves
The three images come from *Ehon kyōka yama mata yama*, volume 1, Kyōwa 4 (1804), published in Tōto by Tsutaya Jūzaburō. The catalog credits Katsushika Hokusai, Benbenkan Koryū and Ōharatei Tanbō. Smithsonian Libraries contributed and sponsored the digitization and identifies the work as public domain. [Item and facsimile](https://archive.org/details/ehonkyoykayamamv1kats) · [Creator, contributor and rights metadata](https://archive.org/metadata/ehonkyoykayamamv1kats)
Folio Kestrel selected leaves 1, 2 and 4 and copied their original JP2 member bytes into a smaller ZIP. The accompanying scan XML covers all 15 leaves. The original ZIP has SHA-1 `35361ba005f9b33abf10b44ecccd3c82c12105cd`. The original XML has SHA-1 `cacfab9414df63e74f067fe4536cd6d36c23f329`. [Complete JPEG 2000 archive](https://archive.org/download/ehonkyoykayamamv1kats/ehonkyoykayamamv1kats_jp2.zip) · [Original scan metadata](https://archive.org/download/ehonkyoykayamamv1kats/ehonkyoykayamamv1kats_scandata.xml)123version https://git-lfs.github.com/spec/v1oid sha256:95976bbb48599970f795581114b317f918e836dbaa9884e2941f94f19a140d4dsize 4796731123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243"""Review book scans directly from an Internet Archive JPEG 2000 ZIP and scandata XML."""import argparseimport csvfrom contextlib import contextmanagerimport hashlibimport jsonimport mathfrom pathlib import Path, PurePosixPathimport reimport sysfrom tempfile import SpooledTemporaryFilefrom zipfile import BadZipFile, ZipFile
from defusedxml import ElementTree as ETfrom PIL import Imagefrom folio_fold.batch_review import SCHEMA, new_directory, preview_row, split_rgba, write_reviewfrom folio_fold.locate import FoldLocator
BOOK_SCHEMA = "folio-archive-jp2-v1"
def catalog(zipfile, xml): root = ET.fromstring(xml) item = root.findtext("bookData/bookId") labels = {} for entry in root.findall("bookData/pageNumData/assertion"): labels.setdefault(int(entry.findtext("leafNum")), []).append(entry.findtext("pageNum")) pages = {} for page in root.findall("pageData/page"): leaf = int(page.attrib["leafNum"]) if leaf < 0 or leaf in pages: raise ValueError(f"Invalid or duplicate XML leaf {leaf}") pages[leaf] = dict(leaf=leaf, page_type=page.findtext("pageType"), page_number=page.findtext("pageNumber"), printed_labels=labels.get(leaf,[]), access=page.findtext("addToAccessFormats"), original_width=page.findtext("origWidth"), original_height=page.findtext("origHeight")) if not pages: raise ValueError("No scan leaves found in the scandata XML") prefix = None for member in zipfile.infolist(): path = PurePosixPath(member.filename) if member.is_dir() or path.suffix.lower() != ".jp2": continue match = re.fullmatch(r"(.+)_(\d+)\.[jJ][pP]2", path.name) if not match: raise ValueError(f"Cannot identify the leaf number for {path.name}") if prefix is None: prefix = match[1] if prefix != match[1] or (item and item != prefix): raise ValueError("The ZIP member prefixes and XML book identifier must agree") leaf = int(match[2]) record = pages.setdefault(leaf,dict(leaf=leaf)) if "member" in record: raise ValueError(f"Multiple JP2 members identify leaf {leaf}") record["member"] = member.filename if prefix is None: raise ValueError("No JPEG 2000 members in the ZIP") direction = root.findtext("bookData/globalHandedness/page-progression") return dict(item=item or prefix, progression=direction, scandata_sha256=hashlib.sha256(xml).hexdigest(), leaves=[pages[k] for k in sorted(pages)])
def print_catalog(book): print(f"{book['item']} · {len(book['leaves'])} leaf records · progression {book['progression'] or 'unknown'}") writer = csv.writer(sys.stdout, delimiter="\t", lineterminator="\n") writer.writerow(["Leaf", "Page type", "Printed label", "Access formats", "Source image"]) for row in book["leaves"]: labels = " / ".join(v for v in row.get("printed_labels", []) if v) writer.writerow([row["leaf"], row.get("page_type"), labels or row.get("page_number"), row.get("access"), row.get("member", "missing")])
def choose(spec, rows): available = {r["leaf"]: r for r in rows} if spec is None: wanted = sorted(n for n, r in available.items() if "member" in r) else: selected = set() for part in spec.split(","): match = re.fullmatch(r"(\d+)(?:-(\d+))?", part.strip()) if not match: raise ValueError(f"Invalid leaf selection {part!r}") lo, hi = int(match[1]), int(match[2] or match[1]) group = [n for n in available if lo <= n <= hi] if hi < lo or len(group) != hi-lo+1: raise ValueError(f"Unknown or reversed leaf range {part!r}") selected.update(group) wanted = sorted(selected) for n in wanted: if "member" not in available[n] or "page_type" not in available[n]: raise ValueError(f"Leaf {n} needs both a JP2 member and a scandata page") return [available[n] for n in wanted]
def check_precision(stream, length): """Check JPEG 2000 SIZ before Pillow can narrow multichannel samples to eight bits.""" while stream.tell() + 8 <= length: start = stream.tell() size = int.from_bytes(stream.read(4),"big") kind = stream.read(4) if size == 1: size = int.from_bytes(stream.read(8),"big") if size == 0: size = length - start end = start + size if end < stream.tell() or end > length: raise ValueError("Invalid JP2 box size") if kind != b"jp2c": stream.seek(end) continue if stream.read(4) != bytes.fromhex("ff4fff51"): raise ValueError("Missing JPEG 2000 image and tile size marker") size = int.from_bytes(stream.read(2),"big") header = stream.read(size-2) if 38 <= size <= end-stream.tell()+2 else b"" count = int.from_bytes(header[34:36],"big") if count not in (1,3) or size != 38+3*count or len(header) != size-2: raise ValueError("Expected a grayscale or three-component JPEG 2000 codestream") if any(header[36+3*i] != 7 for i in range(count)): raise ValueError("This importer requires unsigned 8-bit components") stream.seek(0) return raise ValueError("Missing JP2 codestream")
@contextmanagerdef scan(archive, record): info = archive.getinfo(record["member"]) digest = hashlib.sha256() with archive.open(info) as compressed, SpooledTemporaryFile(max_size=8*1024*1024) as decoded: while chunk := compressed.read(1024*1024): digest.update(chunk) decoded.write(chunk) decoded.seek(0) check_precision(decoded, info.file_size) with Image.open(decoded) as image: if image.format != "JPEG2000" or image.mode not in ("L","RGB"): raise ValueError(f"Unsupported JP2 image on leaf {record['leaf']}") yield image, digest.hexdigest()
def prepare(source, metadata, leaves, target): locator = FoldLocator() with ZipFile(source) as archive, new_directory(target) as out: book = catalog(archive, metadata.read_bytes()) records = choose(leaves, book["leaves"]) (out/"previews").mkdir() rows = [] for record in records: name = f"Leaf {record['leaf']}" caption = " / ".join(v for v in record["printed_labels"] if v) or record["page_number"] or record["page_type"] if caption: name += f" · {caption}" with scan(archive,record) as (image, checksum): width,height=image.size row=preview_row(locator,image.convert("RGB"),out,len(rows),name,checksum) rows.append(row) record.update(name=name,sha256=checksum,width=width,height=height) book.update(schema=BOOK_SCHEMA,leaves=records) (out/"book.json").write_text(json.dumps(book,indent=2,ensure_ascii=False),encoding="utf-8") write_review(out,dict(schema=SCHEMA,scans=rows,unreadable=0))
def export(source, review, decisions, target): book=json.loads((review/"book.json").read_bytes()) batch=json.loads(decisions.read_bytes()) if (not isinstance(book,dict) or not isinstance(batch,dict) or book.get("schema")!=BOOK_SCHEMA or batch.get("schema")!=SCHEMA or not isinstance(batch.get("scans"),list)): raise ValueError("Review or decisions file has an unknown format") records,rows=book["leaves"],batch["scans"] if len(records)!=len(rows): raise ValueError("This decisions file belongs to a different review") output=[] with ZipFile(source) as archive, new_directory(target) as out: for record,row in zip(records,rows): if not isinstance(row,dict) or any(row.get(k)!=record[k] for k in ("name","sha256","width","height")): raise ValueError("This decisions file belongs to a different review") state=row.get("state") if state in ("skipped","pending"): continue if state not in ("whole","approved"): raise ValueError("Unrecognized page decision") with scan(archive,record) as (image,checksum): if checksum!=record["sha256"] or image.size!=(record["width"],record["height"]): raise ValueError(f"Source changed for leaf {record['leaf']}") folder=out/f"leaf-{int(record['leaf']):06d}" folder.mkdir() options = {"icc_profile":image.info["icc_profile"]} if image.info.get("icc_profile") else {} result=dict(record,state=state) if state=="whole": files={"whole":image} order=["whole"] else: top,bottom=row.get("top_x"),row.get("bottom_x") if not all(type(v) in (float,int) and math.isfinite(v) and -100<=v<=100 for v in (top,bottom)): raise ValueError(f"Invalid cut for leaf {record['leaf']}") left,right,x=split_rgba(image,top,bottom) files={"left":left,"right":right} result.update(top_x=top,bottom_x=bottom,right_origin_x=x) order={"lr":["left","right"],"rl":["right","left"]}.get(book["progression"]) paths={} for side,tile in files.items(): path=folder/(side+".png") tile.save(path,**options) paths[side]=path.relative_to(out).as_posix() result.update(files=paths,reading_order=[paths[k] for k in order] if order else None) output.append(result) if not output: raise ValueError("Keep a page or approve a cut before exporting") (out/"pages.json").write_text(json.dumps(dict(item=book["item"],progression=book["progression"], scandata_sha256=book["scandata_sha256"],pages=output),ensure_ascii=False,indent=2),encoding="utf-8")
if __name__=="__main__": cli=argparse.ArgumentParser(description=__doc__) subs=cli.add_subparsers(dest="action",required=True) for action in ("list","prepare","export"): cmd=subs.add_parser(action) cmd.add_argument("archive",type=Path) if action in ("list","prepare"): cmd.add_argument("scandata",type=Path) else: cmd.add_argument("review",type=Path) cmd.add_argument("decisions",type=Path) if action=="list": cmd.add_argument("--json",action="store_true",help="Print the full machine-readable catalog") if action=="prepare": cmd.add_argument("--leaves",help="Leaf numbers or inclusive ranges, e.g. 0,2-5") if action!="list": cmd.add_argument("output",type=Path,help="New output directory") args=cli.parse_args() try: if args.action=="list": with ZipFile(args.archive) as z: book = catalog(z,args.scandata.read_bytes()) if args.json: print(json.dumps(book,indent=2,ensure_ascii=False)) else: print_catalog(book) elif args.action=="prepare": prepare(args.archive,args.scandata,args.leaves,args.output) else: export(args.archive,args.review,args.decisions,args.output) except (ValueError,OSError,KeyError,BadZipFile,ET.ParseError) as exc: cli.exit(2,f"{exc}\n")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051{ "downloadable_example": { "archive_sha256": "95976bbb48599970f795581114b317f918e836dbaa9884e2941f94f19a140d4d", "archive_bytes": 4796731, "offline_viewports": [ 375, 1152 ], "all_real_leaf_labels": 15, "whole_and_split_pixels": [ 16817283, 29170197 ], "reading_order": "rl" }, "metadata_cases": { "zero_based_leaf": true, "duplicate_rejected": true, "mismatched_id_rejected": true, "high_depth_rejected": true, "preserved_grayscale_pixels": 7995, "left_to_right": true, "unknown_direction": true, "uncropped_nonaccess_leaf": true }, "source_book": { "item": "ehonkyoykayamamv1kats", "all_leaves": 15, "selected": [ 1, 2, 4 ], "exported": [ 1, 2 ], "native_pixels": [ 16817283, 29170197 ], "reading_order": [ "leaf-000002/right.png", "leaf-000002/left.png" ], "printed_labels": [ "1 and 2" ], "restored": true }}examples/archive-jp2/README.mdAdded+39
examples/archive-jp2/SOURCES.mdAdded+5
examples/archive-jp2/archive-jp2-review.zipAdded+3
examples/archive-jp2/archive_book.pyAdded+243
examples/archive-jp2/verification.jsonAdded+51