"""Generate deterministic label-free box hypotheses from local image contrast."""
import cv2
import numpy as np

def _box_iou(a,b):
 x0=max(a[0],b[0]);y0=max(a[1],b[1]);x1=min(a[2],b[2]);y1=min(a[3],b[3]);inter=max(0,x1-x0)*max(0,y1-y0);aa=(a[2]-a[0])*(a[3]-a[1]);bb=(b[2]-b[0])*(b[3]-b[1]);return inter/(aa+bb-inter) if aa+bb>inter else 0.

def contrast_boxes(gray,limit=80):
 """Rank threshold-component boxes, without reference labels or class claims.

 Args: 2D uint8 image; positive candidate limit. Returns boxes and contrast
 scores. Boxes are clipped, up to 80 by default, and are only hypotheses.
 """
 if not isinstance(gray,np.ndarray) or gray.ndim!=2 or gray.dtype!=np.uint8 or gray.shape[0]<64 or gray.shape[1]<64:raise ValueError('Expected at least 64x64 uint8 grayscale')
 if type(limit) is not int or limit<=0:raise ValueError('Invalid candidate limit')
 h,w=gray.shape;blur=cv2.GaussianBlur(gray,(0,0),12);contrast=cv2.absdiff(gray,blur);candidates=[];kernel=np.ones((3,3),np.uint8)
 for block in (31,63):
  for invert in (False,True):
   src=255-gray if invert else gray;binary=cv2.adaptiveThreshold(src,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY_INV,block,5);binary=cv2.morphologyEx(binary,cv2.MORPH_CLOSE,kernel)
   contours,_=cv2.findContours(binary,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
   for contour in contours:
    x,y,bw,bh=cv2.boundingRect(contour)
    if min(bw,bh)<8 or max(bw,bh)>320 or not 80<=bw*bh<=30000:continue
    l=max(0,x-2);t=max(0,y-2);r=min(w,x+bw+2);b=min(h,y+bh+2);rect=[l,t,r,b];score=float(np.mean(contrast[t:b,l:r]));candidates.append({'box':rect,'score':score})
 candidates.sort(key=lambda v:(-v['score'],*v['box']));kept=[]
 for candidate in candidates:
  if all(_box_iou(candidate['box'],old['box'])<.7 for old in kept):kept.append(candidate)
  if len(kept)>=limit:break
 return kept
