"""One 64px crop contract for training/inference; width is never clamped or squashed. Margins and polarity follow the Apache-2.0 Indra rec_preproc implementation. Only right-padding batches changes the canvas; widths retain the unpadded size. """ import math import numpy as np def crop_line64(gray,box,*,pad_y=.2,pad_x=.3,dark=None): import cv2 from polarity import is_dark_line if gray.ndim!=2 or gray.dtype!=np.uint8:raise ValueError('Original uint8 grayscale required') x0,y0,x1,y1=map(float,box[:4]) if not all(math.isfinite(v)for v in [x0,y0,x1,y1])or x1<=x0 or y1<=y0:raise ValueError('Invalid line geometry') height=y1-y0;ix0=math.floor(x0-pad_x*height);ix1=math.ceil(x1+pad_x*height);iy0=math.floor(y0-pad_y*height);iy1=math.ceil(y1+pad_y*height);cw,ch=ix1-ix0,iy1-iy0 H,W=gray.shape;sx0,sy0,sx1,sy1=max(0,ix0),max(0,iy0),min(W,ix1),min(H,iy1) if dark is None:dark=is_dark_line(gray,box) canvas=np.full((ch,cw),0 if dark else 255,dtype=np.uint8) if sx1>sx0 and sy1>sy0:canvas[sy0-iy0:sy1-iy0,sx0-ix0:sx1-ix0]=gray[sy0:sy1,sx0:sx1] width=max(1,round(cw*64/ch));resized=cv2.resize(canvas,(width,64),interpolation=cv2.INTER_AREA if ch>64 else cv2.INTER_LINEAR).astype(np.float32)/255. ink=resized if dark else 1.-resized receipt=dict(original_WH=[W,H],ink_box=[x0,y0,x1,y1],padded_source_extent=[ix0,iy0,ix1,iy1],padded_source_WH=[cw,ch],resized_WH=[width,64],scale_XY=[width/cw,64/ch],width_clamped=False,aspect_rounding_error_pixels=abs(width-cw*64/ch),dark_polarity=bool(dark)) return ink,receipt def pad_batch(crops,multiple=8): if not crops or any(c.ndim!=2 or c.shape[0]!=64 for c in crops):raise ValueError('Every recognizer crop must be 64px high') widths=np.array([c.shape[1]for c in crops],dtype=np.int64);padded=math.ceil(int(widths.max())/multiple)*multiple;out=np.zeros((len(crops),1,64,padded),dtype=np.float32) for i,c in enumerate(crops):out[i,0,:,:c.shape[1]]=c return out,widths