Export complete OCR line crops from existing batches with Folio Fold 0.5.0
Browse filesFiles changed (5)
- .gitattributes+1
- batch_review.py+19-10
- line_crops.pyAdded+266
- pyproject.toml+1-1
- wheels/folio_fold-0.5.0-py3-none-any.whlAdded+3
49 unmodified lines50515249 unmodified linesexamples/iiif-export/word-layers/book/000001/left.png filter=lfs diff=lfs merge=lfs -textexamples/iiif-export/word-layers/book/000001/right.png filter=lfs diff=lfs merge=lfs -textwheels/folio_fold-0.4.2-py3-none-any.whl filter=lfs diff=lfs merge=lfs -text49 unmodified lines5051525349 unmodified linesexamples/iiif-export/word-layers/book/000001/left.png filter=lfs diff=lfs merge=lfs -textexamples/iiif-export/word-layers/book/000001/right.png filter=lfs diff=lfs merge=lfs -textwheels/folio_fold-0.4.2-py3-none-any.whl filter=lfs diff=lfs merge=lfs -textwheels/folio_fold-0.5.0-py3-none-any.whl filter=lfs diff=lfs merge=lfs -text
173 unmodified lines174175176177178179180181182183184185186187188189190191105 unmodified lines297298299300301302303304305306173 unmodified lines)def split_rgba(image, top, bottom):width, height = image.sizecuts = [max(0,min(width,math.floor(width * (top + (bottom - top) * (y + 0.5) / height) + 0.5),),)for y in range(height)]low, high = min(cuts), max(cuts)if high == 0 or low == width:raise ValueError("The line leaves a page empty")105 unmodified lines"decisions", type=Path, help="Review JSON saved by the browser")command.add_argument("output", type=Path, help="New directory to create")args = parser.parse_args()try:if args.command == "prepare":prepare(args.scans, args.output, args.page_xml)else:export(args.scans, args.decisions, args.output)except (OSError, ValueError, OverflowError) as exc:173 unmodified lines174175176177178179180181182183184185186187105 unmodified lines293294295296297298299300301302303304305306307308309310311312313314315173 unmodified lines)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.sizecuts = [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")105 unmodified lines"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_lineselse:from line_crops import extract_lineswith 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:
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266"""Extract complete OCR rectangles from the published Folio Fold batch geometry."""
from collections import Counterfrom contextlib import ExitStackfrom itertools import groupbyimport jsonimport mathfrom pathlib import Pathfrom xml.etree import ElementTree as ET
from PIL import Image
if __package__: from .batch_review import cut_columnelse: from batch_review import cut_column
def window(element, width, height): node = element.find("{*}Coords") if node is None: return None, "missing_contour" try: pts = [tuple(map(float, s.split(","))) for s in node.get("points", "").split()] except ValueError: return None, "invalid_contour" if ( any(len(p) != 2 or not all(map(math.isfinite, p)) for p in pts) or len(set(pts)) < 3 ): return None, "invalid_contour" if any(x < 0 or y < 0 or x > width or y > height for x, y in pts): return None, "outside_image" if not sum(x * v - y * u for (x, y), (u, v) in zip(pts, pts[1:] + pts[:1])): return None, "degenerate_contour" xs, ys = zip(*pts) return ( math.floor(min(xs)), math.floor(min(ys)), min(width, math.floor(max(xs)) + 1), min(height, math.floor(max(ys)) + 1), ), None
def check_page(folder, filename, size): if not isinstance(filename, str) or not filename or Path(filename).is_absolute(): raise ValueError(f"Expected a relative PNG path, got {filename!r}.") path = (folder / filename).resolve() if not path.is_relative_to(folder.resolve()): raise ValueError( f"Exported page {filename!r} is outside the manifest directory." ) with Image.open(path) as image: if image.format != "PNG" or image.size != size: raise ValueError(f"{filename}: expected a {size[0]} × {size[1]} PNG.")
def page_geometry(record, folder): width, height = record["width"], record["height"] if any(type(n) is not int or n < 1 for n in (width, height)): raise ValueError("Invalid source dimensions.") if "whole" in record: if "left" in record or "right" in record: raise ValueError("A scan has both whole and split page paths.") check_page(folder, record["whole"], (width, height)) return None, 0 a, b = record["top_x"], record["bottom_x"] if any( type(x) not in (int, float) or not math.isfinite(x) or abs(x) > 100 for x in (a, b) ): raise ValueError("Invalid exported cut endpoints.")
def cut(row): return cut_column(width, height, a, b, row)
low, high = sorted((cut(0), cut(height - 1))) if ( low == width or high == 0 or type(record["right_origin_x"]) is not int or low != record["right_origin_x"] ): raise ValueError( "The page origin or crop width disagrees with the exported cut." ) check_page(folder, record["left"], (high, height)) check_page(folder, record["right"], (width - low, height)) return cut, low
def target(box, cut, origin): if not cut: return "whole", box, None x0, y0, x1, y1 = box bounds = (cut(y0), cut(y1 - 1)) if x1 <= min(bounds): return "left", box, None if x0 >= max(bounds): return "right", (x0 - origin, y0, x1 - origin, y1), None return "review", None, "window_crosses_cut"
def scan_record(record, xml_dir, cut, origin): name = record["name"] xml_path = xml_dir / Path(name).with_suffix(".xml") pages = {key: record[key] for key in ("whole", "left", "right") if key in record} result = dict( source=name, source_sha256=record["sha256"], width=record["width"], height=record["height"], pages=pages, xml=xml_path.name, lines=[], ) if cut is not None: result.update( top_x=record["top_x"], bottom_x=record["bottom_x"], right_origin_x=origin ) try: root = ET.parse(xml_path).getroot() except FileNotFoundError: return dict(result, status="missing_xml") except ET.ParseError as exc: return dict(result, status="invalid_xml", detail=str(exc)) matches = root.findall("{*}Page") if len(matches) != 1: return dict(result, status="invalid_xml", detail="Expected one Page element.") page = matches[0] xml_name = page.get("imageFilename", "").replace("\\", "/").rsplit("/", 1)[-1] if xml_name != name: return dict(result, status="filename_mismatch", xml_image=xml_name) try: dims = [int(page.get(k, "")) for k in ("imageWidth", "imageHeight")] except ValueError: return dict( result, status="invalid_xml", detail="Expected integer image dimensions." ) if dims != [record["width"], record["height"]]: return dict(result, status="dimension_mismatch", xml_size=dims) for i, line in enumerate(page.iterfind(".//{*}TextLine"), 1): strings = [ dict(attributes=dict(alt.attrib), text=node.text or "") for alt in line.findall("{*}TextEquiv") for node in alt.findall("{*}Unicode") ] box, reason = window(line, *dims) side, mapped = "review", None if box: side, mapped, reason = target(box, cut, origin) result["lines"].append( dict( line_index=i, line_id=line.get("id"), unicode=strings, side=side, source_box=box, page_box=mapped, review_reason=reason, ) ) return dict(result, status="indexed")
def recover_window(left, right, cut, origin, box): """Select original RGBA samples from the owning page on each raster row.""" x0, y0, x1, y1 = box crop = Image.new("RGBA", (x1 - x0, y1 - y0))
def boundary(y): return max(x0, min(x1, cut(y)))
for split, rows in groupby(range(y0, y1), key=boundary): first = next(rows) end = first + 1 + sum(1 for _ in rows) if split > x0: crop.paste(left.crop((x0, first, split, end)), (0, first - y0)) if split < x1: part = right.crop((split - origin, first, x1 - origin, end)) crop.paste(part, (split - x0, first - y0)) return crop
def extract_lines(manifest, xml_dir, stage, crossings_only=False): if not xml_dir.is_dir(): raise ValueError("Choose the directory with source PAGE XML files.") records = json.loads(manifest.read_text(encoding="utf-8")) if not isinstance(records, list) or not records: raise ValueError("Expected a nonempty pages.json array.") seen = set() scan_counts = Counter() line_counts = Counter() written = 0 with (stage / "lines.jsonl").open("w", encoding="utf-8") as index: for number, record in enumerate(records, 1): required = {"name", "sha256", "width", "height"} if not isinstance(record, dict) or not required.issubset(record): raise ValueError(f"Missing scan metadata at manifest row {number}.") name = record["name"] if ( not isinstance(name, str) or not name or Path(name).name != name or name in (".", "..") or name in seen ): raise ValueError( f"Invalid or duplicate scan name at manifest row {number}." ) seen.add(name) try: cut, origin = page_geometry(record, manifest.parent) scan = scan_record(record, xml_dir, cut, origin) except (TypeError, KeyError) as exc: raise ValueError(f"{name}: invalid page metadata ({exc}).") from exc scan_counts[scan["status"]] += 1 scan_dir = stage / f"{number:06d}" with ExitStack() as stack: images = {} for line in scan["lines"]: side = line["side"] line_counts[side] += 1 crossing = line["review_reason"] == "window_crosses_cut" line["crop"] = None if not crossing and (crossings_only or line["page_box"] is None): continue sides = ("left", "right") if crossing else (side,) for needed in sides: if needed not in images: image = stack.enter_context( Image.open(manifest.parent / scan["pages"][needed]) ) if ( image.mode != "RGBA" or getattr(image, "n_frames", 1) != 1 ): raise ValueError( f"{name}: expected an original single-frame RGBA export." ) images[needed] = image if crossing: crop = recover_window( images["left"], images["right"], cut, origin, line["source_box"], ) else: crop = images[side].crop(line["page_box"]) scan_dir.mkdir(exist_ok=True) path = scan_dir / f"line-{line['line_index']:06d}.png" metadata = images[sides[0]].info crop.save( path, **{ k: metadata[k] for k in ("dpi", "icc_profile") if k in metadata }, ) line["crop"] = path.relative_to(stage).as_posix() written += 1 print(json.dumps(scan, ensure_ascii=False), file=index) return {"scans": scan_counts, "lines": line_counts, "written_crops": written}3 unmodified lines456789103 unmodified lines[project]name = "folio-fold"version = "0.4.2"description = "Locate and review book folds offline with bundled ONNX weights"requires-python = ">=3.10"license = "Apache-2.0"3 unmodified lines456789103 unmodified lines[project]name = "folio-fold"version = "0.5.0"description = "Locate and review book folds offline with bundled ONNX weights"requires-python = ">=3.10"license = "Apache-2.0"
123version https://git-lfs.github.com/spec/v1oid sha256:3640d4b0f310c7699d2e90f3e85dd16767dabd31351ef289d10069d30eaee5efsize 782362.gitattributes+1
batch_review.py+19-10
line_crops.pyAdded+266
pyproject.toml+1-1
wheels/folio_fold-0.5.0-py3-none-any.whlAdded+3