Prepare local book reviews from IIIF 2 and 3 manifests with canvas provenance, bounded working resolution and resumable downloads
Browse filesFiles changed (2)
- examples/iiif-book/README.mdAdded+35
- iiif_book.pyAdded+323
1234567891011121314151617181920212223242526272829303132333435# Review a book from an IIIF manifest
Give Folio Fold the manifest URL from a digital library to prepare a local review of its scans. You can start with a few canvases, adjust each suggested cut in a browser, and export the approved pages. The source map keeps each exported scan traceable to the library’s canvas.
## Try three spreads
This example opens canvases 2–4 of the National Diet Library’s 1878 copy of *Hokusai Manga*, volume 14. Canvas 1 is the front cover. The manifest marks the volume PDM. [Catalogue](https://ndlsearch.ndl.go.jp/books/R100000039-I851659) · [Original manifest](https://dl.ndl.go.jp/api/iiif/851659/manifest.json)
```shpython -m pip install 'https://huggingface.co/foliokestrel/folio-fold/resolve/main/wheels/folio_fold-0.1.0-py3-none-any.whl'curl -fL https://huggingface.co/foliokestrel/folio-fold/resolve/main/iiif_book.py -o iiif_book.pypython iiif_book.py https://dl.ndl.go.jp/api/iiif/851659/manifest.json hokusai-review --canvases 2-4 --cache ndl-cache.sqlite```
Open `hokusai-review/review/index.html`. On canvas 2, the title leaf faces a blank leaf. The thin black band between them is the binding. Check the proposed cut, adjust its top and bottom positions if needed, and choose **Approve cut**. Choose **Save decisions** and save `fold-decisions.json` to your working directory.
```shfolio-fold-batch export hokusai-review/scans fold-decisions.json hokusai-pages```
Each approved scan produces full working-resolution `left.png` and `right.png`. In this Japanese volume, read the right page of a spread first. Review and export work offline after preparation.
## Select canvases and resolution
`--canvases 3,7-12` selects one-based positions in manifest order. The default processes all canvases from the first sequence of a Presentation 2 manifest or from the manifest’s ordered canvases in Presentation 3. Book page numbers and canvas positions can differ.
`--width 2048` sets the maximum displayed pixel width of the working copies. The default is 1,536. For full-image IIIF services the importer requests a supported rendition and respects advertised size limits. Standalone images and declared crops or rotations use the supplied image URL. When a returned image is wider than requested, the importer applies its display orientation and saves a locally reduced PNG. A direct image URL can therefore require downloading a larger file. Set a larger width before preparation if you need more export resolution.
The optional `--cache` file stores downloaded annotation pages, image-service metadata and image bytes. An interrupted run retains completed downloads. Rerun the same command to finish. The importer fetches the manifest again and reuses cached responses for the same manifest bytes and resource URL. Use a fresh cache file when you want to fetch those resources again. Each successful run writes a new review folder.
## Find the source of an exported page
`manifest.json` preserves the retrieved manifest. `canvases.json` records the manifest checksum and attribution, the original canvas label and identifier, the painted image, requested rendition, final response URL and SHA-256, working-copy dimensions and SHA-256, and rights statements attached to the selected canvases, annotations and images. For an exported page, match its `name` and `sha256` in `pages.json` to the corresponding record in `canvases.json`. A resized working copy has its own digest.
The importer handles public HTTP(S) manifests with a single full-canvas still image per selected canvas. JPEG, PNG up to eight bits per channel, and WebP are supported. It reads embedded annotations and linked Presentation 3 annotation pages. A canvas that requires compositing, a choice between images, or painting into part of a canvas stops preparation with its canvas number. The manifest retains the provider’s rights information for review before sharing derivatives. [Presentation 2](https://iiif.io/api/presentation/2.1/) · [Presentation 3](https://iiif.io/api/presentation/3.0/) · [Image API 2](https://iiif.io/api/image/2.1/) · [Image API 3](https://iiif.io/api/image/3.0/)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323"""Prepare selected canvases of an IIIF book manifest for local Folio Fold review."""
import argparsefrom contextlib import closing, contextmanager, redirect_stdoutfrom hashlib import sha256from io import BytesIO, StringIOimport jsonfrom pathlib import Pathimport reimport sqlite3from urllib.parse import urlsplitfrom urllib.request import Request, urlopen
from PIL import Image, ImageOps
try: from folio_fold.batch_review import new_directory, prepareexcept ModuleNotFoundError as exc: if exc.name != "folio_fold": raise from batch_review import new_directory, prepare
def fetch(url): if not isinstance(url, str) or urlsplit(url).scheme not in ("http", "https"): raise ValueError("Expected an HTTP or HTTPS resource URL") req = Request( url, headers={ "User-Agent": "FolioFold/1.0 (https://huggingface.co/foliokestrel/folio-fold)" }, ) with urlopen(req, timeout=60) as response: return response.read(), response.geturl()
@contextmanagerdef cached_reader(cache, manifest_hash): if cache is None: yield fetch return with closing(sqlite3.connect(cache, timeout=30)) as db: db.execute( """CREATE TABLE IF NOT EXISTS folio_iiif ( manifest TEXT, url TEXT, final TEXT, digest TEXT, content BLOB, PRIMARY KEY(manifest,url))""" )
def read(url): row = db.execute( "SELECT content,final,digest FROM folio_iiif WHERE manifest=? AND url=?", (manifest_hash, url), ).fetchone() if row and sha256(row[0]).hexdigest() == row[2]: return row[0], row[1] content, final = fetch(url) with db: db.execute( "INSERT OR REPLACE INTO folio_iiif VALUES (?,?,?,?,?)", (manifest_hash, url, final, sha256(content).hexdigest(), content), ) return content, final
yield read
def identifier(obj): if isinstance(obj, dict): return obj.get("id") or obj.get("@id") return obj
def numbers(spec, total): if not spec: return range(1, total + 1) chosen = set() for part in spec.split(","): m = re.fullmatch(r"(\d+)(?:-(\d+))?", part.strip()) if not m: raise ValueError("Use one-based canvas numbers such as 1-4,9,12") a, b = int(m[1]), int(m[2] or m[1]) if not 1 <= a <= b <= total: raise ValueError(f"Canvas range {part} is outside 1–{total} or reversed") chosen.update(range(a, b + 1)) return sorted(chosen)
def canvases(manifest): if manifest.get("type") == "Manifest": return manifest["items"], 3 if manifest.get("@type") == "sc:Manifest": sequences = manifest["sequences"] if not sequences: raise ValueError("Manifest has no sequences") return sequences[0]["canvases"], 2 raise ValueError("Expected an IIIF Presentation 2 or 3 Manifest")
def painting(canvas, version, read): if version == 2: pairs = [(a, a.get("resource"), a.get("on")) for a in canvas.get("images", [])] else: pairs = [] for page in canvas.get("items", []): if "items" not in page: page = json.loads(read(identifier(page))[0]) for a in page["items"]: if a.get("motivation") == "painting": pairs.append((a, a.get("body"), a.get("target"))) if len(pairs) != 1: raise ValueError(f"Expected one painting annotation, found {len(pairs)}") ann, body, target = pairs[0] if identifier(target) != identifier(canvas) or ( isinstance(target, dict) and "selector" in target ): raise ValueError("Segment or transformed painting target") if not isinstance(body, dict) or body.get("type", body.get("@type")) not in ( "Image", "dctypes:Image", ): raise ValueError("The painting body is not a single still image") return ann, body
def choose_rendition(body, width, read): url = identifier(body) services = body.get("service", []) for service in services if isinstance(services, list) else [services]: sid = identifier(service) if not isinstance(sid, str) or not isinstance(url, str): continue # Resize only a full, unrotated default rendition. Cropped, styled and # rotated image bodies must keep their declared presentation geometry. base = sid.rstrip("/") + "/full/" if not url.startswith(base) or url[len(base) :] not in ( "full/0/default.jpg", "max/0/default.jpg", ): continue info = json.loads(read(sid.rstrip("/") + "/info.json")[0]) w, h = info["width"], info["height"] if not (w > 0 and h > 0): raise ValueError("Invalid image service dimensions") profile = info.get("profile") profiles = profile if isinstance(profile, list) else [profile] max_w = min(width, w) for limits in [info, *(p for p in profiles if isinstance(p, dict))]: max_w = min(max_w, limits.get("maxWidth", w)) limit_h = limits.get("maxHeight", limits.get("maxWidth", h)) max_w = min(max_w, int(limit_h * w / h)) if "maxArea" in limits: max_w = min(max_w, int((limits["maxArea"] * w / h) ** 0.5)) if max_w < 1: raise ValueError("No positive rendition size fits the service limits") extras = info.get("extraFeatures", []) sized = "sizeByW" in extras or any( (isinstance(p, str) and re.search(r"level[12](?:\.json)?$", p)) or (isinstance(p, dict) and "sizeByW" in p.get("supports", [])) for p in profiles ) if max_w == w: return url if sized: return f"{base}{max_w},/0/default.jpg" sizes = sorted(info.get("sizes", []), key=lambda s: s["width"]) if sizes: size = next((s for s in reversed(sizes) if s["width"] <= max_w), sizes[0]) return f"{base}{size['width']},{size['height']}/0/default.jpg" # A level-0 server may expose only its maximum rendition. Download # that body and resize locally as with a standalone image. return url
def prepare_book(url, destination, selection, width, cache=None): if width < 1: raise ValueError("Rendition width must be positive") raw, final = fetch(url) manifest = json.loads(raw) pages, version = canvases(manifest) if not pages: raise ValueError("Manifest contains no canvases") manifest_hash = sha256(raw).hexdigest() with new_directory(destination) as out, cached_reader(cache, manifest_hash) as read: scans = out / "scans" scans.mkdir() (out / "manifest.json").write_bytes(raw) rows = [] for n in numbers(selection, len(pages)): canvas = pages[n - 1] try: ann, body = painting(canvas, version, read) requested = choose_rendition(body, width, read) content, actual = read(requested) source_hash = sha256(content).hexdigest() with Image.open(BytesIO(content)) as image: if getattr(image, "n_frames", 1) != 1: raise ValueError("Multi-frame painting body") # Existing folder review handles orientation, bit depth and # export. Limit direct-body derivatives to common 8-bit types. if image.format not in ("JPEG", "PNG", "WEBP"): raise ValueError( f"Unsupported downloaded format {image.format}" ) if image.format == "PNG" and content[24] == 16: raise ValueError("16-bit PNG painting body") displayed = ImageOps.exif_transpose(image) if displayed.width > width: displayed = displayed.convert("RGBA") displayed = displayed.resize( ( width, max( 1, round(width * displayed.height / displayed.width) ), ), Image.Resampling.LANCZOS, ) name = f"canvas-{n:08d}.png" # An RGB profile can accompany the converted RGBA image. profile = ( image.info.get("icc_profile") if image.mode in ("RGB", "RGBA") else None ) displayed.info.clear() displayed.save(scans / name, icc_profile=profile) else: ext = {"JPEG": "jpg", "PNG": "png", "WEBP": "webp"}[ image.format ] name = f"canvas-{n:08d}.{ext}" (scans / name).write_bytes(content) w, h = displayed.size rows.append( dict( canvas=n, canvas_id=identifier(canvas), label=canvas.get("label"), painting=identifier(body), requested=requested, retrieved=actual, response_sha256=source_hash, name=name, sha256=sha256((scans / name).read_bytes()).hexdigest(), width=w, height=h, rights={ k: v for k, v in ( ("canvas", canvas.get("rights", canvas.get("license"))), ("annotation", ann.get("rights", ann.get("license"))), ("image", body.get("rights", body.get("license"))), ) if v }, ) ) except ( OSError, ValueError, KeyError, TypeError, Image.DecompressionBombError, ) as exc: raise ValueError(f"Canvas {n} ({identifier(canvas)}): {exc}") from exc (out / "canvases.json").write_text( json.dumps( dict( manifest=final, manifest_sha256=manifest_hash, total_canvases=len(pages), rights=manifest.get("rights", manifest.get("license")), attribution=manifest.get( "requiredStatement", manifest.get("attribution") ), canvases=rows, ), ensure_ascii=False, indent=2, ) + "\n", encoding="utf-8", ) with redirect_stdout(StringIO()): prepare(scans, out / "review") rejected = out / "review/unreadable.json" if rejected.exists(): raise ValueError( "Unreadable review scan: " + str(json.loads(rejected.read_text())[0]) ) print(f"Prepared {len(rows)} canvases. Open {destination / 'review/index.html'}.")
def main(): p = argparse.ArgumentParser(description=__doc__) p.add_argument("manifest", help="HTTP(S) URL of a public book manifest") p.add_argument( "output", type=Path, help="New directory for scans, review and provenance" ) p.add_argument( "--canvases", help="One-based canvas numbers and ranges in source order, e.g. 1-4,9", ) p.add_argument( "--width", type=int, default=1536, help="Maximum displayed working-copy width (default: 1536 pixels)", ) p.add_argument( "--cache", type=Path, help="Optional SQLite file to reuse downloaded responses when retrying the same manifest", ) args = p.parse_args() try: prepare_book(args.manifest, args.output, args.canvases, args.width, args.cache) except (OSError, ValueError, KeyError, TypeError, sqlite3.Error) as exc: p.exit(2, f"{p.prog}: {exc}\n")
if __name__ == "__main__": main()examples/iiif-book/README.mdAdded+35
iiif_book.pyAdded+323