Load the ONNX file selected by config.json and include the model configuration in the documented Hub download.
ee73700 verified Download folio_orient.py from foliokestrel/folio-orient: direct link, hf CLI and curl.
- Browser
- Download file 9.44 kB
-
https://huggingface.co/foliokestrel/folio-orient/resolve/main/folio_orient.py
- Command line
-
hf download hf://foliokestrel/folio-orient/folio_orient.py
-
curl -L -o folio_orient.py https://huggingface.co/foliokestrel/folio-orient/resolve/main/folio_orient.py
9.44 kB
| """Estimate the clockwise correction for a printed page. Run with --help for CLI usage.""" | |
| import argparse | |
| import json | |
| from pathlib import Path | |
| import numpy as np | |
| from PIL import Image, ImageFilter, ImageOps | |
| PATCH = 96 | |
| def visible_page(image): | |
| """Apply EXIF orientation and composite transparency onto paper white.""" | |
| image = ImageOps.exif_transpose(image) | |
| if "A" in image.getbands() or "transparency" in image.info: | |
| top = image.convert("RGBA") | |
| base = Image.new("RGB", top.size, "white") | |
| base.paste(top, mask=top.getchannel("A")) | |
| return base | |
| return image.convert("RGB") | |
| def text_patches(gray, *, preview=False): | |
| """Pick high-contrast patches across the page at two reading scales.""" | |
| patches = [] | |
| scales = (1024,) if preview else (900, 1600) | |
| resampling = Image.Resampling.BILINEAR if preview else Image.Resampling.LANCZOS | |
| for target in scales: | |
| factor = min(target / max(gray.size), 2) | |
| shape = tuple(max(1, round(n * factor)) for n in gray.size) | |
| pix = np.asarray(gray.resize(shape, resampling)) | |
| h, w = pix.shape | |
| if min(h, w) < (3 * PATCH if preview else PATCH): | |
| continue | |
| # One patch per region keeps a dense header or ornament from dominating. | |
| buckets = {} | |
| ny = 6 if preview else 1 + (h - PATCH) // 64 | |
| nx = 6 if preview else 1 + (w - PATCH) // 64 | |
| xs = np.linspace(0, w - PATCH, nx, dtype=int) | |
| ys = np.linspace(0, h - PATCH, ny, dtype=int) | |
| for row, y in enumerate(ys): | |
| for col, x in enumerate(xs): | |
| p = pix[y : y + PATCH, x : x + PATCH].astype(np.float32) / 255 | |
| avg, std = float(p.mean()), float(p.std()) | |
| if std < 0.045: | |
| continue | |
| # Gradient activity across both axes favors glyphs over lone rules. | |
| dx = np.abs(np.diff(p, axis=1)).mean() | |
| dy = np.abs(np.diff(p, axis=0)).mean() | |
| score = min(dx, dy) | |
| if score < 0.009: | |
| continue | |
| region = ( | |
| (row // 2, col // 2) | |
| if preview | |
| else ( | |
| min(3, int((x + PATCH / 2) * 4 / w)), | |
| min(3, int((y + PATCH / 2) * 4 / h)), | |
| ) | |
| ) | |
| if region not in buckets or score > buckets[region][0]: | |
| buckets[region] = (score, (p - avg) / max(std, 0.055)) | |
| count = 8 if preview else 12 | |
| patches.extend( | |
| p for _, p in sorted(buckets.values(), key=lambda b: -b[0])[:count] | |
| ) | |
| if not patches: | |
| return np.empty((0, 1, PATCH, PATCH), np.float32) | |
| return np.clip(np.stack(patches)[:, None], -4, 4) | |
| def quarter_turn(patches, infer): | |
| if len(patches) == 0: | |
| return {"quarter_turn_cw": None, "agreement": 0.0, "patches": 0} | |
| logits = infer(patches) | |
| exp = np.exp(logits - logits.max(axis=1, keepdims=True)) | |
| probs = (exp / exp.sum(axis=1, keepdims=True)).mean(axis=0) | |
| k = int(probs.argmax()) | |
| return { | |
| "quarter_turn_cw": k * 90, | |
| "agreement": round(float(probs[k]), 4), | |
| "patches": len(patches), | |
| } | |
| def fine_skew(gray, limit=8): | |
| """Find the clockwise angle giving the sharpest projection of dark text lines.""" | |
| gray = gray.copy() | |
| gray.thumbnail((960, 960), Image.Resampling.LANCZOS) | |
| if min(gray.size) < 48: | |
| return None | |
| a = np.asarray(gray, dtype=np.float32) | |
| # Local background subtraction suppresses gradually varying paper color. | |
| bg = np.asarray(gray.filter(ImageFilter.GaussianBlur(5)), dtype=np.float32) | |
| edge = np.maximum(bg - a - 10, 0) | |
| h, w = edge.shape | |
| border = max(2, int(min(h, w) * 0.035)) | |
| edge[:border] = edge[-border:] = 0 | |
| edge[:, :border] = edge[:, -border:] = 0 | |
| y, x = np.nonzero(edge > 6) | |
| if len(y) < 120: | |
| return None | |
| if len(y) > 30000: | |
| ids = np.random.default_rng(37).choice(len(y), 30000, replace=False) | |
| y, x = y[ids], x[ids] | |
| weights = edge[y, x].clip(0, 100) | |
| x = x.astype(np.float64) - (w - 1) / 2 | |
| pad = int(np.ceil(w * 0.5 * np.tan(np.radians(limit)))) + 2 | |
| def score(deg): | |
| pos = y + x * np.tan(np.radians(deg)) + pad | |
| base = pos.astype(np.int32) | |
| fraction = pos - base | |
| size = h + pad * 2 + 1 | |
| hist = np.bincount( | |
| base, weights * (1 - fraction), minlength=size | |
| ) + np.bincount(base + 1, weights * fraction, minlength=size) | |
| # Two-row differences still reward narrow line structure after splatting. | |
| return np.square(hist[2:] - hist[:-2]).mean() | |
| angles = np.linspace(-limit, limit, 2 * limit * 2 + 1) | |
| scores = np.asarray([score(t) for t in angles]) | |
| peak = int(scores.argmax()) | |
| if peak in (0, len(angles) - 1) or scores[peak] < np.median(scores) * 1.35: | |
| return None | |
| center = angles[peak] | |
| refine = np.linspace(center - 0.45, center + 0.45, 19) | |
| best = float(refine[np.argmax([score(t) for t in refine])]) | |
| return 0.0 if abs(best) < 0.12 else round(best, 2) | |
| def transpose_cw(image, degrees): | |
| if degrees == 0: | |
| return image | |
| return image.transpose( | |
| { | |
| 90: Image.Transpose.ROTATE_270, | |
| 180: Image.Transpose.ROTATE_180, | |
| 270: Image.Transpose.ROTATE_90, | |
| }[degrees] | |
| ) | |
| class PageOrienter: | |
| def __init__(self, model_path=None, threads=1): | |
| import onnxruntime as ort | |
| options = ort.SessionOptions() | |
| options.intra_op_num_threads = threads | |
| if model_path is None: | |
| directory = Path(__file__).resolve().parent | |
| config_path = directory / "config.json" | |
| filename = "model.onnx" | |
| if config_path.is_file(): | |
| config = json.loads(config_path.read_text(encoding="utf-8")) | |
| filename = config["weights"]["file"] | |
| model_path = directory / filename | |
| self.session = ort.InferenceSession( | |
| str(model_path), options, providers=["CPUExecutionProvider"] | |
| ) | |
| output_width = self.session.get_outputs()[0].shape[-1] | |
| if isinstance(output_width, int) and output_width != 4: | |
| raise ValueError( | |
| "PageOrienter needs four turn logits. For mirror.onnx use ReflectionDetector." | |
| ) | |
| def estimate(self, image, *, deskew=True, fast=False): | |
| gray = visible_page(image).convert("L") | |
| def predict(preview): | |
| patches = text_patches(gray, preview=preview) | |
| return quarter_turn( | |
| patches, lambda p: self.session.run(["logits"], {"patches": p})[0] | |
| ) | |
| result = predict(preview=fast) | |
| if fast: | |
| early = result["patches"] >= 4 and result["agreement"] >= 0.85 | |
| if not early: | |
| result = predict(preview=False) | |
| result["fast_path"] = early | |
| turn = result["quarter_turn_cw"] | |
| result["deskew_cw"] = ( | |
| fine_skew(transpose_cw(gray, turn)) if deskew and turn is not None else None | |
| ) | |
| return result | |
| def paper_color(page): | |
| """Median color around the visible page edge for the expanded canvas.""" | |
| pixels = np.asarray(page.resize((64, 64), Image.Resampling.BOX)) | |
| edges = np.concatenate((pixels[0], pixels[-1], pixels[1:-1, 0], pixels[1:-1, -1])) | |
| return tuple(np.median(edges, axis=0).astype(int).tolist()) | |
| def correct(image, estimate, *, min_agreement=0.70, fillcolor=None): | |
| """Apply a suggestion when its mean patch score meets the review threshold.""" | |
| page = visible_page(image) | |
| turn = estimate["quarter_turn_cw"] | |
| if turn is None or estimate["agreement"] < min_agreement: | |
| return page | |
| page = transpose_cw(page, turn) | |
| skew = estimate["deskew_cw"] | |
| return ( | |
| page.rotate( | |
| -skew, | |
| Image.Resampling.BICUBIC, | |
| expand=True, | |
| fillcolor=paper_color(page) if fillcolor is None else fillcolor, | |
| ) | |
| if skew | |
| else page | |
| ) | |
| def main(): | |
| p = argparse.ArgumentParser(description=__doc__) | |
| p.add_argument("image", type=Path) | |
| p.add_argument("--model", type=Path) | |
| p.add_argument( | |
| "--output", type=Path, help="Optional destination for the corrected image" | |
| ) | |
| p.add_argument("--no-deskew", action="store_true") | |
| p.add_argument( | |
| "--fast", | |
| action="store_true", | |
| help="Try a smaller patch sample, then fall back if uncertain", | |
| ) | |
| p.add_argument( | |
| "--min-agreement", | |
| type=float, | |
| default=0.70, | |
| help="Minimum score for automatic correction (default 0.70)", | |
| ) | |
| args = p.parse_args() | |
| if not 0 <= args.min_agreement <= 1: | |
| p.error("--min-agreement must be between 0 and 1") | |
| if args.output and args.output.exists(): | |
| p.error("output already exists") | |
| with Image.open(args.image) as image: | |
| result = PageOrienter(args.model).estimate( | |
| image, deskew=not args.no_deskew, fast=args.fast | |
| ) | |
| result["accepted"] = ( | |
| result["quarter_turn_cw"] is not None | |
| and result["agreement"] >= args.min_agreement | |
| ) | |
| print(json.dumps(result)) | |
| if args.output: | |
| correct(image, result, min_agreement=args.min_agreement).save(args.output) | |
| if __name__ == "__main__": | |
| main() | |