"""Lossless page isolation for cropped image-tool repairs; no artistic verdicts.""" from pathlib import Path import hashlib import shutil from PIL import Image, ImageChops, ImageFilter def sha(path): return hashlib.sha256(Path(path).read_bytes()).hexdigest() def describe(path): path = Path(path).resolve(strict=True) return {'path': str(path), 'sha256': sha(path)} def unchanged(entry): if sha(entry['path']) != entry['sha256']: raise ValueError('Local repair input changed; preserve the original source and recorded materials.') def context_crop(source, box, folder): """Keep native pixels and an immutable source snapshot, never a full-page input.""" source, folder = Path(source).resolve(strict=True), Path(folder) with Image.open(source) as opened: if opened.format != 'PNG' or opened.mode not in ('L', 'RGB', 'RGBA'): raise ValueError('Local repair needs an original L/RGB/RGBA PNG; do not convert the page.') page = opened.copy() if (len(box) != 4 or any(type(v) is not int for v in box) or not (0 <= box[0] < box[2] <= page.width and 0 <= box[1] < box[3] <= page.height) or tuple(box) == (0, 0, page.width, page.height)): raise ValueError('--crop requires a proper context region: left top right bottom, exclusive, within the page.') folder.mkdir(parents=True, exist_ok=False) snapshot = folder / 'source-page.png' crop = folder / 'context-crop.png' shutil.copy2(source, snapshot) if sha(snapshot) != sha(source): raise ValueError('Source snapshot verification failed.') page.crop(box).save(crop) return {'source': describe(source), 'snapshot': describe(snapshot), 'contextCrop': describe(crop), 'box': list(box), 'pageSize': list(page.size), 'pageMode': page.mode} def load_materials(local, raw): # The original path can be pages/P01.png and later point to a new adopted # version. The immutable snapshot, bound to the original hash, is the base. for key in ('snapshot', 'contextCrop'): unchanged(local[key]) if local['snapshot']['sha256'] != local['source']['sha256']: raise ValueError('Source snapshot is not the recorded original page.') unchanged(raw) with Image.open(local['snapshot']['path']) as image: page = image.copy() box = tuple(local['box']) with Image.open(local['contextCrop']['path']) as image: if image.size != page.crop(box).size or image.tobytes() != page.crop(box).tobytes(): raise ValueError('Context is not the recorded native crop of the original page.') with Image.open(raw['path']) as image: generated = image.copy() width, height = box[2] - box[0], box[3] - box[1] if generated.width * height != generated.height * width: raise ValueError('Generated crop aspect ratio differs. Align it explicitly; never stretch X and Y separately.') aligned = generated.convert(page.mode).resize((width, height), Image.Resampling.LANCZOS) return page, aligned, box, {'rawSize': list(generated.size), 'nativeSize': [width, height], 'uniformScale': width / generated.width, 'resample': 'LANCZOS generated crop only'} def load_mask(path, size, binary=False): with Image.open(path) as image: if image.format != 'PNG' or image.mode != 'L' or image.size != size: raise ValueError('Mask must be a page-sized L PNG at native resolution.') mask = image.copy() if binary and (mask.getbbox() is None or any(v for i, v in enumerate(mask.histogram()) if i not in (0, 255))): raise ValueError('Allowed mask must be nonempty and binary (0 or 255).') return mask def render(local, raw, allowed_path, alpha_path=None, feather=0): page, aligned, box, alignment = load_materials(local, raw) allowed = load_mask(allowed_path, page.size, binary=True) rectangle = Image.new('L', page.size) rectangle.paste(255, box) if ImageChops.multiply(allowed, ImageChops.invert(rectangle)).getbbox(): raise ValueError('Allowed mask exceeds the context crop.') if alpha_path is not None: if feather: raise ValueError('Use either explicit alpha or an inward feather radius.') alpha = load_mask(alpha_path, page.size) else: if not 0 <= feather <= 10: raise ValueError('Feather radius must be between 0 and 10 native pixels.') alpha = (ImageChops.multiply(allowed.filter(ImageFilter.MinFilter(3)).filter( ImageFilter.GaussianBlur(feather)), allowed) if feather else allowed.copy()) if ImageChops.multiply(alpha, ImageChops.invert(allowed)).getbbox(): raise ValueError('Alpha extends outside the allowed mask.') if alpha.getbbox() is None: raise ValueError('Alpha has no editable pixels.') result = page.copy() result.paste(aligned, box[:2], alpha.crop(box)) difference = ImageChops.difference(page, result) changed = difference.convert('RGB') channels = changed.split() changed = ImageChops.lighter(ImageChops.lighter(channels[0], channels[1]), channels[2]) if page.mode == 'RGBA': changed = ImageChops.lighter(changed, difference.getchannel('A')) changed = changed.point(lambda v: 255 if v else 0) outside = ImageChops.multiply(changed, ImageChops.invert(allowed)) if outside.getbbox(): raise ValueError('Outside-mask pixels changed.') return result, aligned, allowed, alpha, { 'alignment': alignment, 'outsideChangedPixels': outside.histogram()[255], 'changedPixels': changed.histogram()[255], 'changedBox': changed.getbbox(), 'allowedPixels': allowed.histogram()[255], 'artisticQualityAutomaticallyAssessed': False} def compose(local, raw, allowed_path, folder, output, alpha_path=None, feather=0): result, aligned, allowed, alpha, report = render(local, raw, allowed_path, alpha_path, feather) folder, output = Path(folder), Path(output) if output.exists() or folder.exists(): raise ValueError('Use a new composite candidate; preserve all earlier materials and variants.') folder.mkdir(parents=True) output.parent.mkdir(parents=True, exist_ok=True) aligned.save(folder / 'aligned-crop.png') allowed.save(folder / 'allowed-mask.png') alpha.save(folder / 'alpha.png') result.save(output) return {**report, 'allowedMask': describe(folder / 'allowed-mask.png'), 'alpha': describe(folder / 'alpha.png'), 'alignedCrop': describe(folder / 'aligned-crop.png')} def verify(local, raw, composite, output): for key in ('allowedMask', 'alpha', 'alignedCrop'): unchanged(composite[key]) result, aligned, _, _, _ = render(local, raw, composite['allowedMask']['path'], composite['alpha']['path']) with Image.open(composite['alignedCrop']['path']) as saved: if saved.mode != aligned.mode or saved.size != aligned.size or saved.tobytes() != aligned.tobytes(): raise ValueError('Aligned crop differs from the recorded uniform transform.') with Image.open(output) as saved: if saved.mode != result.mode or saved.size != result.size or saved.tobytes() != result.tobytes(): raise ValueError('Page does not match the recorded crop composite.')