"""python -B lp2_digit_screen_343.py EVIDENCE_DIR OUTPUT.json.gz (Pillow, NumPy, SciPy).
Read all 58 page images in full; do not use expected text regions in the detector."""
import sys,hashlib,gzip,json
from pathlib import Path
from collections import Counter
from PIL import Image
import numpy as np
from scipy.ndimage import label,find_objects
def save(p,x):p.write_bytes(gzip.compress((json.dumps(x,sort_keys=True,separators=(',',':'))+'\n').encode(),mtime=0))
def normalized(m):
 return np.array(Image.fromarray(np.uint8(m)*255).resize((30,48),Image.Resampling.BILINEAR))>=128
def templates(d):
 g=json.loads(gzip.decompress((d/'grid_geometry_245.json.gz').read_bytes()))
 c=json.loads((d/'grid_cells_254.json').read_bytes())['cells']
 gray=np.array(Image.open(d/'66.jpg').convert('L'));T={}
 for a,b in zip(g,c):
  assert (a['page'],a['row'],a['col'])==(b['page'],b['row'],b['col'])
  if a['page']!=49 or b['a'][0] in T:continue
  x,y,X,Y=a['glyph_bboxes'][0]; shape=gray[y:Y,x:X]<128
  T[b['a'][0]]=(shape,normalized(shape))
 assert set(T)==set('01234')
 return T,g,c
def run(d):
 T,g,c=templates(d);out={}
 # Fixed before scoring. Broad mode tolerates scale and modest edge variation, not arbitrary typefaces.
 for page in range(58):
  im=np.array(Image.open(d/f'{page+17}.jpg').convert('L'));assert im.shape==(3600,2400)
  lab,_=label(im<128)
  rows=[]; comps=find_objects(lab)
  for j,(yy,xx) in enumerate(comps,1):
   w,h=xx.stop-xx.start,yy.stop-yy.start
   if not(38<=h<=116 and 8<=w<=93):continue
   m=lab[yy,xx]==j; choices=[]
   for ch,(src,norm) in T.items():
    H,W=src.shape
    if not(.60<=h/H<=1.60 and .84<=w/h/(W/H)<=1.16):continue
    if not choices: z=normalized(m)
    error=np.count_nonzero(z^norm)/max(1,np.count_nonzero(z|norm))
    if error<=.18: choices.append((error,ch))
   if not choices:continue
   err,ch=min(choices);src=T[ch][0]
   exact=(src.shape==m.shape and np.array_equal(src,m))
   rows.append([ch,xx.start,yy.start,xx.stop,yy.stop,round(err,5),bool(exact)])
  # Cluster bottom coordinates with total span <=7 native pixels;
  # various symbols may be present, so this is only a candidate-row test.
  clusters=[]
  for q in sorted(rows,key=lambda v:v[4]):
   if not clusters or q[4]-clusters[-1][0][4]>7:clusters.append([])
   clusters[-1].append(q)
  flags=[sorted(cluster,key=lambda q:q[1]) for cluster in clusters if len(cluster)>=8]
  targets={(a['glyph_bboxes'][0][0],a['glyph_bboxes'][0][1],b['a'][0]) for a,b in zip(g,c) if a['page']==page}
  found={(q[1],q[2],q[0]) for q in rows}
  flagged={(q[1],q[2],q[0]) for row in flags for q in row}
  # Independent visual transcripts for the two non-grid controls; preserve every digit 0..4 in print order.
  refs=(['3258 3222 3152 3038','3278 3299 3298 2838','3288 3294 3296 2472','4516 1206 708 1820'] if page==15 else
        (d/'grid_digest_254_image.txt').read_text().splitlines() if page==56 else None)
  readback=None
  if refs:
   readback=[''.join(q[0] for q in sorted(row,key=lambda v:v[1])) for row in clusters]
   expected=[''.join(ch for ch in row if ch in '01234') for row in refs]
   assert readback==expected,(page,readback,expected)
  # Count exact-template, broader-template and flagged-row recall against all 256 archived leads.
  out[page]={'non_grid_reference_leads_readback':readback,'matches':len(rows),'exact_matches':sum(q[-1] for q in rows),'candidate_rows':flags,
             'true_leads':len(targets),'true_leads_matched':len(found&targets),'true_leads_on_flagged_rows':len(flagged&targets),
             'true_leads_exact_single_exemplar':len(targets&{(q[1],q[2],q[0]) for q in rows if q[-1]})}
 return {'template_page':49,'images':'LP2 0..57; original JPEG = page+17; 2400x3600; grayscale <128; 4-connected.','parameters':'5 print exemplars, one per leading digit from LP2 page 49. Relative height .6..1.6, aspect .84..1.16, normalized mask Jaccard distance <=.18 at 30x48, bottom spread <=7 native pixels, minimum 8 candidate components. No predicted row x/y bounds.','pages':out}
if __name__=='__main__':save(Path(sys.argv[2]),run(Path(sys.argv[1])))
