"""RQ2 augmentation policies (design.json 'policy_typical', 'policy_safe'); PIL and numpy only. Input of every op: a PIL RGB image with dark ink on light paper, already height-normalised to H px (design image path step 3). Policy(name, height)(im, rng) -> (im_out, op_name, params). The caller resizes back to H when the height changed. Random numbers: one generator per training sample, numpy default_rng([seed, 4242, sample ordinal]) (design). The draw order is fixed and the same in both policies: slot u = integers(0, 7), then z1 = random(), z2 = random(); each policy maps (z1, z2) to its own parameter range, so the same sample gets the same slot and the same relative magnitude in all four arms of a seed. Typical = TrOCR build_data_aug(mode='train') (microsoft/unilm trocr/data_aug.py @ 581af18, torchvision 0.8.2 defaults); the constants and their line numbers are in records/R5/RQ2/trocr_policy.json. Safe = proposal section 5 as read by the design: rotation within +-2 deg (and never forcing a downscale below 0.75x), blur sigma <= H/64, shear +-0.5 DEGREES (owner decision 2026-11-26), 2x2 thickening at 64 px only, downscale >= 0.75x, translation by padding; it never thins strokes. """ import math import numpy as np from PIL import Image, ImageFilter N_SLOTS = 7 SLOT_SALT = 4242 REPLACE_SALT = 4343 WHITE = (255, 255, 255) # TrOCR constants (trocr_policy.json); a unit test compares these with that file. TROCR = { "rotation_deg": [-10.0, 10.0], "rotation_expand": True, "rotation_fill": 255, "rotation_resample": "NEAREST", "blur_kernel": 3, "blur_sigma": [0.1, 2.0], "dilation_kernel": 3, "erosion_kernel": 3, "downscale_divisor": 3, "downscale_down": "NEAREST", "downscale_up": "BICUBIC", "underline_threshold": 50, "underline_rows": 3, "underline_colour": [0, 0, 0], "n_choices": 7, "weights": "equal", } SAFE = { "rotation_max_deg": 2.0, "rotation_resample": "BILINEAR", "rotation_min_scale": 0.75, "blur_kernel": 3, "blur_sigma_min": 0.1, "blur_sigma_max": "H/64", "shear_deg": 0.5, "shear_resample": "BILINEAR", "thicken_kernel": "round(2*H/64) (2 at 64 px, 1 = identity at 32 px)", "downscale_min": 0.75, "downscale_interp": "BICUBIC", "pad_max": "H//2 px on each side", } TYPICAL_SLOTS = ("rotate", "blur", "max3_thin", "min3_thicken", "down_up_third", "underline", "keep") SAFE_SLOTS = ("rotate", "blur", "shear", "thicken2", "down_up", "pad", "keep") RESAMPLE = {"NEAREST": Image.NEAREST, "BILINEAR": Image.BILINEAR, "BICUBIC": Image.BICUBIC, "LANCZOS": Image.LANCZOS} def slot_rng(seed, ordinal): return np.random.default_rng([int(seed), SLOT_SALT, int(ordinal)]) def draw_slot(rng): """The fixed draw order shared by both policies: (slot, z1, z2).""" u = int(rng.integers(0, N_SLOTS)) z1 = float(rng.random()) z2 = float(rng.random()) return u, z1, z2 def resize_to_height(im, H, resample=Image.LANCZOS): """As linedet.data.pil_tensor: width max(int(w * H / h), 1), Lanczos by default.""" w, h = im.size if h == H: return im return im.resize((max(int(w * H / h), 1), H), resample) # ------------------------------------------------------------------------------------------------ ops def op_rotate(im, deg, resample, fill=255): """Rotate counter-clockwise by deg, canvas expanded, constant fill (PIL Image.rotate, as torchvision 0.8.2 calls it).""" return im.rotate(float(deg), resample=resample, expand=True, fillcolor=(fill, fill, fill) if im.mode == "RGB" else fill) def gauss_kernel3(sigma): """torchvision 0.8.2 functional_tensor._get_gaussian_kernel1d(3, sigma) in float32.""" x = np.linspace(-1.0, 1.0, 3).astype(np.float32) pdf = np.exp(np.float32(-0.5) * (x / np.float32(sigma)) ** 2).astype(np.float32) return (pdf / pdf.sum()).astype(np.float32) def op_blur(im, sigma): """torchvision 0.8.2 GaussianBlur(3) on a PIL image: to_tensor (/255), 3x3 Gaussian (outer product of the 1-D kernel), reflect padding of 1, float32, back with mul(255).byte() (truncation).""" a = np.asarray(im, dtype=np.float32) / np.float32(255.0) k = gauss_kernel3(sigma) K = np.outer(k, k).astype(np.float32) mode = "reflect" if min(a.shape[0], a.shape[1]) >= 2 else "edge" pad = ((1, 1), (1, 1), (0, 0)) if a.ndim == 3 else ((1, 1), (1, 1)) p = np.pad(a, pad, mode=mode) H, W = a.shape[:2] out = np.zeros_like(a) for dy in range(3): for dx in range(3): out += K[dy, dx] * p[dy:dy + H, dx:dx + W] out = (out * np.float32(255.0)).astype(np.float32) return Image.fromarray(np.clip(out, 0, 255).astype(np.uint8), im.mode) def op_max3(im): """TrOCR 'Dilation(3)' = PIL MaxFilter(3): on dark ink over light paper this THINS strokes.""" return im.filter(ImageFilter.MaxFilter(3)) def op_min3(im): """TrOCR 'Erosion(3)' = PIL MinFilter(3): on dark ink over light paper this THICKENS strokes.""" return im.filter(ImageFilter.MinFilter(3)) def op_down_up(im, size, down, up): """Resize to size=(w, h) with `down`, then back to the original size with `up`.""" W, H = im.size return im.resize((max(1, int(size[0])), max(1, int(size[1]))), down).resize((W, H), up) def op_underline(im, threshold=50, rows=3): """TrOCR Underline on a copy: ink = grey < threshold; rows y1, y1-1, y1-2 (y1 = lowest ink row) set to black from the leftmost ink column to the rightmost ink column minus one. Returns (image, applied).""" g = np.asarray(im.convert("L")) ys, xs = np.nonzero(g < threshold) if len(ys) == 0: return im.copy(), False y1, x0, x1 = int(ys.max()), int(xs.min()), int(xs.max()) a = np.array(im) for y in range(y1, y1 - rows, -1): if 0 <= y < a.shape[0]: a[y, x0:x1] = 0 return Image.fromarray(a, im.mode), True def shear_geometry(W, H, deg): """Horizontal shear by deg about the vertical centre; returns (new size, inverse affine data for PIL). The canvas grows by a whole number of pixels on each side (ceil(|tan| H / 2)), so the shear adds no global half-pixel shift (with a fractional offset, bilinear resampling would blur every stroke by half a pixel even at 0.5 deg).""" t = math.tan(math.radians(deg)) off = int(math.ceil(abs(t) * H / 2.0)) return (W + 2 * off, H), (1.0, -t, t * H / 2.0 - off, 0.0, 1.0, 0.0) def op_shear(im, deg, resample=Image.BILINEAR, fill=255): size, data = shear_geometry(im.size[0], im.size[1], deg) fc = (fill, fill, fill) if im.mode == "RGB" else fill return im.transform(size, Image.AFFINE, data, resample=resample, fillcolor=fc) def op_pad_translate(im, left, right, fill=255): W, H = im.size out = Image.new(im.mode, (W + int(left) + int(right), H), (fill, fill, fill) if im.mode == "RGB" else fill) out.paste(im, (int(left), 0)) return out def op_thicken2(im): """2x2 minimum filter: out[y, x] = min over (y, x), (y-1, x), (y, x-1), (y-1, x-1); dark ink grows 1 px right and down. Built in numpy because PIL rank filters take odd sizes only. Monotone: out <= in everywhere.""" a = np.asarray(im) pad = ((1, 0), (1, 0), (0, 0)) if a.ndim == 3 else ((1, 0), (1, 0)) p = np.pad(a, pad, mode="constant", constant_values=255) out = np.minimum(np.minimum(p[1:, 1:], p[:-1, 1:]), np.minimum(p[1:, :-1], p[:-1, :-1])) return Image.fromarray(out.astype(np.uint8), im.mode) def safe_rotation_limit_deg(H, W): """Largest |angle| (<= 2 deg) whose expanded canvas keeps the height scale >= 0.75 after resizing back to H. Design: a = min(2, asin(H / (3 W))). PIL's expanded canvas rounds each side outward (floor/ceil of the rotated corners), adding up to 2 px of height, so the bound uses (H - 6) / (3 W): W sin a + H cos a + 2 <= (H - 6)/3 + H + 2 = 4H/3.""" return min(SAFE["rotation_max_deg"], math.degrees(math.asin(min(1.0, max(0.0, (H - 6.0) / (3.0 * max(W, 1))))))) def thicken_kernel(H): return int(round(2.0 * H / 64.0)) # ------------------------------------------------------------------------------------------------ policies class Policy: """name in {'typical', 'safe'}; height = the line height H the ops act on.""" def __init__(self, name, height): if name not in ("typical", "safe"): raise ValueError(name) self.name = name self.height = int(height) self.slots = TYPICAL_SLOTS if name == "typical" else SAFE_SLOTS def __call__(self, im, rng): u, z1, z2 = draw_slot(rng) return self.apply(im, u, z1, z2) def apply(self, im, u, z1, z2): """Apply slot u with magnitudes z1, z2 in [0, 1). Returns (image, op_name, params).""" W, H = im.size if self.name == "typical": return self._typical(im, u, z1, z2, W, H) return self._safe(im, u, z1, z2, W, H) def _typical(self, im, u, z1, z2, W, H): T = TROCR if u == 0: lo, hi = T["rotation_deg"] deg = lo + (hi - lo) * z1 return op_rotate(im, deg, Image.NEAREST, T["rotation_fill"]), "rotate", {"deg": deg} if u == 1: lo, hi = T["blur_sigma"] s = lo + (hi - lo) * z1 return op_blur(im, s), "blur", {"sigma": s} if u == 2: return op_max3(im), "max3_thin", {"kernel": 3} if u == 3: return op_min3(im), "min3_thicken", {"kernel": 3} if u == 4: size = (max(1, W // T["downscale_divisor"]), max(1, H // T["downscale_divisor"])) return op_down_up(im, size, Image.NEAREST, Image.BICUBIC), "down_up_third", {"size": list(size), "scale_h": size[1] / H} if u == 5: out, applied = op_underline(im, T["underline_threshold"], T["underline_rows"]) return out, ("underline" if applied else "underline_noop"), {"applied": applied} return im, "keep", {} def _safe(self, im, u, z1, z2, W, H): Hp = self.height if u == 0: a = safe_rotation_limit_deg(H, W) deg = -a + 2 * a * z1 return op_rotate(im, deg, Image.BILINEAR, 255), "rotate", {"deg": deg, "limit_deg": a} if u == 1: smax = Hp / 64.0 s = SAFE["blur_sigma_min"] + (smax - SAFE["blur_sigma_min"]) * z1 return op_blur(im, s), "blur", {"sigma": s, "sigma_max": smax} if u == 2: deg = -SAFE["shear_deg"] + 2 * SAFE["shear_deg"] * z1 return op_shear(im, deg, Image.BILINEAR, 255), "shear", {"deg": deg} if u == 3: k = thicken_kernel(Hp) if k <= 1: return im, "thicken_identity", {"kernel": k} return op_thicken2(im), "thicken2", {"kernel": 2} if u == 4: f = SAFE["downscale_min"] + (1.0 - SAFE["downscale_min"]) * z1 size = (max(1, int(math.ceil(W * f))), max(1, int(math.ceil(H * f)))) # ceil: neither side below f return op_down_up(im, size, Image.BICUBIC, Image.BICUBIC), "down_up", {"factor": f, "size": list(size), "scale_h": size[1] / H} if u == 5: m = Hp // 2 left = int(math.floor(z1 * (m + 1))) right = int(math.floor(z2 * (m + 1))) return op_pad_translate(im, left, right), "pad", {"left": left, "right": right} return im, "keep", {} def geometry_on_mask(mask, op, params): """Move a mode-L mask (255 = mask) with the geometry of an op, nearest neighbour, fill 0 (probe P1).""" if op == "rotate": return mask.rotate(float(params["deg"]), resample=Image.NEAREST, expand=True, fillcolor=0) if op in ("shear", "shear_factor"): size, data = shear_geometry(mask.size[0], mask.size[1], params["deg"]) return mask.transform(size, Image.AFFINE, data, resample=Image.NEAREST, fillcolor=0) if op == "pad": return op_pad_translate(mask, params["left"], params["right"], fill=0) return mask