"""Numeric crop preprocessing variants for multi-pass recognition.""" from io import BytesIO def _to_gray_array(image_bytes: bytes): import numpy as np from PIL import Image with Image.open(BytesIO(image_bytes)) as source: image = source.convert("L") width = max(64, round(image.width * 64 / max(image.height, 1))) image = image.resize((width, 64)) return (255 - np.asarray(image, dtype=np.float32)) / 255 def default_tensor(image_bytes: bytes): import numpy as np array = _to_gray_array(image_bytes) return array[None, None, :, :], "model_default" def inverted_tensor(image_bytes: bytes): import numpy as np array = 1.0 - _to_gray_array(image_bytes) return array[None, None, :, :], "polarity_inverted" def contrast_tensor(image_bytes: bytes): import numpy as np array = _to_gray_array(image_bytes) mean = float(array.mean()) stretched = np.clip((array - mean) * 1.35 + mean, 0.0, 1.0) return stretched[None, None, :, :], "contrast_stretch" VARIANTS = (default_tensor, inverted_tensor, contrast_tensor)