Download batch_review.py from foliokestrel/folio-fold: direct link, hf CLI and curl.
- Browser
- Download file 12.7 kB
-
https://huggingface.co/foliokestrel/folio-fold/resolve/main/batch_review.py
- Command line
-
hf download hf://foliokestrel/folio-fold/batch_review.py
-
curl -L -o batch_review.py https://huggingface.co/foliokestrel/folio-fold/resolve/main/batch_review.py
12.7 kB
| """Prepare a local book-spread review and export the cuts a reviewer has approved.""" | |
| import argparse | |
| from contextlib import contextmanager | |
| import hashlib | |
| import json | |
| import math | |
| import os | |
| import shutil | |
| from pathlib import Path | |
| import tempfile | |
| from PIL import Image, ImageDraw, ImageOps | |
| SCHEMA = "folio-fold-review-v1" | |
| SUFFIXES = {".jpg", ".jpeg", ".png", ".webp", ".tif", ".tiff"} | |
| def new_directory(destination): | |
| if destination.exists() or destination.is_symlink(): | |
| raise ValueError(f"Choose a new destination: {destination}") | |
| with tempfile.TemporaryDirectory(dir=destination.parent) as temp: | |
| staged = Path(temp) / "prepared" | |
| staged.mkdir() | |
| yield staged | |
| # Exclusively claim the target. A failed or racing export cannot merge two batches. | |
| if os.name == "nt": | |
| staged.rename(destination) | |
| return | |
| destination.mkdir() | |
| try: | |
| staged.replace(destination) | |
| except OSError: | |
| if not any(destination.iterdir()): | |
| destination.rmdir() | |
| raise | |
| def digest(file): | |
| file.seek(0) | |
| checksum = hashlib.sha256() | |
| while block := file.read(1024 * 1024): | |
| checksum.update(block) | |
| file.seek(0) | |
| return checksum.hexdigest() | |
| def upright(source): | |
| if getattr(source, "n_frames", 1) != 1: | |
| raise ValueError("Choose a single-frame image") | |
| if source.mode not in {"1", "L", "LA", "P", "RGB", "RGBA", "CMYK"}: | |
| raise ValueError(f"Unsupported source pixel mode {source.mode}") | |
| if source.format == "PNG": | |
| # Pillow can present a 16-bit RGB PNG as RGB with only eight bits retained. | |
| position = source.fp.tell() | |
| source.fp.seek(24) | |
| depth = source.fp.read(1) | |
| source.fp.seek(position) | |
| if depth == bytes([16]): | |
| raise ValueError("Use a PNG with at most 8 bits per channel") | |
| if source.format == "TIFF": | |
| bits = source.tag_v2.get(258, (1,)) | |
| if max((bits,) if isinstance(bits, int) else bits) > 8: | |
| raise ValueError("Use a TIFF with at most 8 bits per channel") | |
| return ImageOps.exif_transpose(source) | |
| def page_annotations(xml_dir, image_path, size): | |
| if __package__: | |
| from .page_lines import read_page | |
| else: | |
| from page_lines import read_page | |
| xml_path = xml_dir / (image_path.stem + ".xml") | |
| try: | |
| page = read_page(xml_path.read_bytes(), include_contours=True) | |
| except FileNotFoundError: | |
| return {"note": f"No matching PAGE XML: {xml_path.name}"} | |
| except (OSError, ValueError) as exc: | |
| return {"note": f"Could not read {xml_path.name}: {exc}"} | |
| filename = page["filename"].replace("\\", "/").split("/")[-1] | |
| if filename != image_path.name: | |
| return {"note": "The PAGE image filename differs from this scan."} | |
| if (page["width"], page["height"]) != size: | |
| return {"note": "The PAGE dimensions differ from the displayed scan."} | |
| return { | |
| "lines": [points for _, points in page["lines"]], | |
| "contours": page["contours"], | |
| "total_lines": page["counts"].get("TextLine", 0), | |
| "omitted": page["counts"].get("TextLine", 0) - len(page["lines"]), | |
| } | |
| def preview_row(locator, rgb, out, index, name, checksum): | |
| prediction = locator.predict(rgb) | |
| rgb.thumbnail((1100, 850), Image.Resampling.LANCZOS) | |
| preview = f"previews/{index+1:06}.jpg" | |
| rgb.save(out / preview, quality=86) | |
| return dict(name=name, sha256=checksum, preview=preview, **prediction) | |
| def write_review(out, manifest): | |
| shutil.copytree(Path(__file__).with_name("review_assets"), out / "assets") | |
| template = ( | |
| Path(__file__).with_name("review_template.html").read_text(encoding="utf-8") | |
| ) | |
| payload = json.dumps(manifest, ensure_ascii=True, allow_nan=False).replace( | |
| "<", "\\u003c" | |
| ) | |
| (out / "index.html").write_text( | |
| template.replace("__SCAN_MANIFEST__", payload), encoding="utf-8" | |
| ) | |
| def prepare(source_dir, destination, page_xml=None): | |
| if __package__: | |
| from .locate import FoldLocator, displayed_image | |
| else: | |
| from locate import FoldLocator, displayed_image | |
| if page_xml is not None and not page_xml.is_dir(): | |
| raise ValueError(f"PAGE XML directory could not be opened: {page_xml}") | |
| inputs = sorted( | |
| ( | |
| p | |
| for p in source_dir.iterdir() | |
| if p.is_file() and p.suffix.lower() in SUFFIXES | |
| ), | |
| key=lambda p: (p.name.casefold(), p.name), | |
| ) | |
| if not inputs: | |
| raise ValueError("The input folder has no supported scan files") | |
| locator = FoldLocator() | |
| rows = [] | |
| rejected = [] | |
| with new_directory(destination) as out: | |
| (out / "previews").mkdir() | |
| for idx, path in enumerate(inputs): | |
| try: | |
| with path.open("rb") as file: | |
| checksum = digest(file) | |
| with Image.open(file) as source: | |
| image = upright(source) | |
| rgb = displayed_image(image) | |
| del image | |
| except (ValueError, OSError, Image.DecompressionBombError) as exc: | |
| rejected.append(dict(name=path.name, reason=str(exc))) | |
| continue | |
| row = preview_row(locator, rgb, out, idx, path.name, checksum) | |
| rows.append(row) | |
| if page_xml is not None: | |
| rows[-1]["annotation"] = page_annotations( | |
| page_xml, path, (row["width"], row["height"]) | |
| ) | |
| if not rows: | |
| first = rejected[0] | |
| raise ValueError( | |
| f"No supported scans could be prepared. {first['name']}: {first['reason']}" | |
| ) | |
| if rejected: | |
| (out / "unreadable.json").write_text( | |
| json.dumps(rejected, ensure_ascii=True, indent=2) + "\n", | |
| encoding="utf-8", | |
| ) | |
| manifest = dict(schema=SCHEMA, scans=rows, unreadable=len(rejected)) | |
| write_review(out, manifest) | |
| if rejected: | |
| print( | |
| f"Skipped {len(rejected)} unreadable or unsupported files. See {destination / 'unreadable.json'}." | |
| ) | |
| print( | |
| f"Prepared {len(rows)} scans. Open {destination / 'index.html'} in a browser." | |
| ) | |
| def cut_column(width, height, top, bottom, row): | |
| position = width * (top + (bottom - top) * (row + 0.5) / height) | |
| return max(0, min(width, math.floor(position + 0.5))) | |
| def split_rgba(image, top, bottom): | |
| width, height = image.size | |
| cuts = [cut_column(width, height, top, bottom, row) for row in range(height)] | |
| low, high = min(cuts), max(cuts) | |
| if high == 0 or low == width: | |
| raise ValueError("The line leaves a page empty") | |
| rgba = image.convert("RGBA") | |
| left, right = rgba.crop((0, 0, high, height)), rgba.crop((low, 0, width, height)) | |
| if low != high: | |
| left_pen, right_pen = ImageDraw.Draw(left), ImageDraw.Draw(right) | |
| for y, cut in enumerate(cuts): | |
| if cut < high: | |
| left_pen.line((cut, y, high - 1, y), fill=(0, 0, 0, 0)) | |
| if cut > low: | |
| right_pen.line((0, y, cut - low - 1, y), fill=(0, 0, 0, 0)) | |
| return left, right, low | |
| def export(source_dir, decisions, destination): | |
| batch = json.loads(decisions.read_text(encoding="utf-8")) | |
| if ( | |
| not isinstance(batch, dict) | |
| or batch.get("schema") != SCHEMA | |
| or not isinstance(batch.get("scans"), list) | |
| ): | |
| raise ValueError("Expected a Folio Fold review file") | |
| included = [] | |
| seen = set() | |
| for row in batch["scans"]: | |
| if not isinstance(row, dict) or row.get("state") not in ( | |
| "approved", | |
| "whole", | |
| "skipped", | |
| "pending", | |
| ): | |
| raise ValueError("Invalid scan decision") | |
| name = row.get("name") | |
| if ( | |
| not isinstance(name, str) | |
| or name in {"", ".", ".."} | |
| or Path(name).name != name | |
| or Path(name).is_absolute() | |
| or name in seen | |
| ): | |
| raise ValueError("Invalid or repeated source filename") | |
| seen.add(name) | |
| if row["state"] in ("pending", "skipped"): | |
| continue | |
| if row["state"] == "approved": | |
| for key in ("top_x", "bottom_x"): | |
| x = row.get(key) | |
| if ( | |
| type(x) not in (float, int) | |
| or not math.isfinite(x) | |
| or not -100 <= x <= 100 | |
| ): | |
| raise ValueError(f"Invalid cut in {name}") | |
| included.append(row) | |
| if not included: | |
| raise ValueError("Approve a cut or keep a scan whole before exporting") | |
| results = [] | |
| with new_directory(destination) as out: | |
| for idx, row in enumerate(included): | |
| name = row["name"] | |
| path = source_dir / name | |
| with path.open("rb") as file: | |
| if digest(file) != row.get("sha256"): | |
| raise ValueError(f"{name} has changed since review") | |
| with Image.open(file) as source: | |
| image = upright(source) | |
| if list(image.size) != [row.get("width"), row.get("height")]: | |
| raise ValueError(f"Dimensions changed for {name}") | |
| folder = f"{idx+1:06}" | |
| (out / folder).mkdir() | |
| record = dict(name=name, sha256=row["sha256"], width=image.width, height=image.height) | |
| if row["state"] == "whole": | |
| pages = [("whole", image.convert("RGBA"))] | |
| else: | |
| left, right, right_x = split_rgba(image, row["top_x"], row["bottom_x"]) | |
| pages = [("left", left), ("right", right)] | |
| record.update(top_x=row["top_x"], bottom_x=row["bottom_x"], right_origin_x=right_x) | |
| options = {k: image.info[k] for k in ("dpi",) if k in image.info} | |
| if image.mode in ("RGB", "RGBA") and image.info.get("icc_profile"): | |
| options["icc_profile"] = image.info["icc_profile"] | |
| for side, page in pages: | |
| record[side] = f"{folder}/{side}.png" | |
| page.info.clear() | |
| page.save(out / record[side], **options) | |
| results.append(record) | |
| (out / "pages.json").write_text( | |
| json.dumps(results, ensure_ascii=True, indent=2) + "\n", encoding="utf-8" | |
| ) | |
| print( | |
| f"Exported {len(included)} reviewed scans to {destination}. Omitted {len(seen)-len(included)}." | |
| ) | |
| def main(): | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| commands = parser.add_subparsers(dest="command", required=True) | |
| for name in ("prepare", "export"): | |
| command = commands.add_parser(name) | |
| command.add_argument("scans", type=Path, help="Directory of single-frame scans") | |
| if name == "prepare": | |
| command.add_argument( | |
| "--page-xml", | |
| type=Path, | |
| help="Optional directory containing a matching <scan stem>.xml per image", | |
| ) | |
| if name == "export": | |
| command.add_argument( | |
| "decisions", type=Path, help="Review JSON saved by the browser" | |
| ) | |
| command.add_argument("output", type=Path, help="New directory to create") | |
| crops = commands.add_parser("crop-lines", help="Extract PAGE line crops from already exported pages") | |
| crops.add_argument("manifest", type=Path, help="pages.json from folio-fold-batch export") | |
| crops.add_argument("page_xml", type=Path, help="Directory holding the source PAGE XML files") | |
| crops.add_argument("output", type=Path, help="New folder for line PNGs and lines.jsonl") | |
| crops.add_argument("--crossings-only", action="store_true", help="Write PNGs only for rectangles divided by the cut") | |
| args = parser.parse_args() | |
| try: | |
| if args.command == "prepare": | |
| prepare(args.scans, args.output, args.page_xml) | |
| elif args.command == "crop-lines": | |
| if __package__: | |
| from .line_crops import extract_lines | |
| else: | |
| from line_crops import extract_lines | |
| with new_directory(args.output) as stage: | |
| counts = extract_lines(args.manifest, args.page_xml, stage, args.crossings_only) | |
| print(json.dumps(counts)) | |
| else: | |
| export(args.scans, args.decisions, args.output) | |
| except (OSError, ValueError, OverflowError) as exc: | |
| parser.exit(2, f"{parser.prog}: {exc}\n") | |
| if __name__ == "__main__": | |
| main() | |