"""Tree-page wrap audit using only the published image/metadata files in this directory.
Usage: python3 -B margins_126.py > results.json . Requires NumPy and Pillow."""
from pathlib import Path
import json,hashlib,collections
import numpy as np
from PIL import Image
D=Path(__file__).resolve().parent
R='ᚠᚢᚦᚩᚱᚳᚷᚹᚻᚾᛁᛄᛇᛈᛉᛋᛏᛒᛖᛗᛚᛝᛟᛞᚪᚫᚣᛡᛠ'
H=lambda b:hashlib.sha256(b).hexdigest()
src=(D/'liber-primus__transcription--master.txt').read_bytes();assert H(src)=='b0b2e13c3cd35512ee5955a2d9a56c22d7410e283d35dd9c90abbaa7b99279eb'
s=src.decode();pages=s[s.index('ᚱ-'):].split('%')
def refs(n):return [''.join(c for c in row if not c.isspace()) for row in pages[n-2].split('/') if any(c in R for c in row)]
def bands(v):
 x=np.flatnonzero(v)
 return [(int(a[0])+580,int(a[-1])+581) for a in np.split(x,np.where(np.diff(x)>1)[0]+1) if len(a)]
# Absolute approximate upper edge of the black glyphs; cropped bands have padding above and below.
# Exclude all transitions touching an opening heading/drop-cap row, all cross-page and block-final exits.
sol={5:([673,889,1106,1325],[2,3]),14:([673,861,1085,1274,1498,1686,1874,2098,2322,2547,2735],list(range(4,11))),15:([673,897,1085,1274,1499],list(range(1,5))),74:([917,1105,1349,1537,1725],[4])}
target={n:([round((917 if n==44 else 673)+i*188.3) for i in range(11 if n==44 else 6 if n==49 else 12)],list(range(4,11) if n==44 else range(1,6) if n==49 else range(1,12))) for n in range(44,50)}
manifest={a['file']:a['sha256'] for a in json.loads((D/'jpeg_source_manifest.json').read_text())['files']}
ww=collections.defaultdict(list)
for z in json.loads((D/'glyph74_training.json').read_text())['templates']:
 x,y,a,b=z['bbox'];ww[R[z['label']]].append(a-x)
width={k:float(np.median(v)) for k,v in ww.items()};width['-']=10
def analyze(th):
    solved=[];actual=[];gaps=[];placements=[];edge=[];cuts=[]
    for cohort,items in [('solved',sol),('tree',target)]:
        for n,(ys,eligible) in items.items():
            path=D/f'{n:02}.jpg';assert H(path.read_bytes())==manifest[path.name]
            im=np.asarray(Image.open(path).convert('L'));assert im.shape==(3600,2400)
            ref=refs(n);rs={}
            for i in sorted(set(eligible)|{j+1 for j in eligible}):
                y=ys[i-1];z=bands((im[y-7:y+122,580:1840]<th).sum(0)>=2);t=ref[i-1]
                assert 584<z[0][0]<905 and z[-1][1]<1815
                rs[i]=(t,z)
                # Estimate normal white gaps on solved pages only, from width-checked
                # neighboring runs at the beginning of black body rows. Stop at any mismatch.
                if cohort=='solved':
                    prefix=[]
                    for c,(a,b) in zip(t,z):
                        if c not in width or abs(b-a-width[c])>4:break
                        if prefix:gaps.append(a-prefix[-1][1])
                        prefix.append((a,b))
                    # Positive geometric checks: remove the last member of each such
                    # measured two-token pair; the original configuration fit this line.
                    placements.extend((a0[1],a1[1]-a1[0],a1[1]) for a0,a1 in zip(prefix,prefix[1:]))
            for i in eligible:
                t,z=rs[i];nt,nz=rs[i+1];j=next(k for k,ch in enumerate(nt) if ch in R)
                if not all(ch=='-' for ch in nt[:j]):raise ValueError((n,i,nt[:j]))
                for c,(a,b) in zip(nt[:j+1],nz):
                    if abs(b-a-width[c])>4:raise ValueError((n,i,c,a,b,width[c]))
                needed=nz[j][1]-nz[0][0];end=z[-1][1]
                row=dict(scan=n,row=i,end=end,first=nt[:j+1],next_span=needed)
                # Planted early wrap: move the original line's last rune to the next line,
                # with its preceding single dot if present. Check the three relevant boxes
                # against the width reference; do not infer a virtual break for ambiguous suffixes.
                if t[-1] in R and len(t)>=3:
                    take=2 if t[-2]=='-' else 1
                    if t[-take-1] in R and all(abs((b-a)-width[c])<=4 for c,(a,b) in zip(t[-take-1:],z[-take-1:])):
                        cuts.append(dict(cohort=cohort,scan=n,row=i,end=z[-take-1][1],next_span=z[-1][1]-z[-take][0],original_end=end))
                if cohort=='solved':solved.append(row);edge.append(end)
                else:actual.append(row)
        if cohort=='solved':
            # Demonstrated right edge and empirical range; never estimated from target.
            boundary=max(edge);lo=min(gaps);hi=max(gaps)
            assert 1780<boundary<=1805 and 0<=lo<=hi<36
    # Nominal x=1800 mirrors the usual x=600 left origin on the 2400px canvas.
    # The primary tag uses the furthest solved line, worst observed gap, and two pixels of reserve.
    for row in solved+actual+cuts:
        v=row['end']+row['next_span'];row.update(
            low=v+lo,high=v+hi,robust_room=boundary-(v+hi),
            status=('fits' if v+hi+2<=boundary else 'too_wide' if v+lo-2>1805 else 'borderline'))
    # Calibration: the possible end interval should contain the observed next symbol's end.
    assert all(e+w+lo<=dest<=e+w+hi for e,w,dest in placements)
    return dict(threshold=th,boundary=boundary,min_gap=lo,max_gap=hi,calibration_gaps=len(gaps),
      solved=solved,tree=actual,cuts=cuts)
def main():
    runs=[analyze(i) for i in [80,100,140]]
    primary=runs[1]
    for k in ('solved','tree'):
        for i,row in enumerate(primary[k]):
            row['all_thresholds']=[a[k][i]['status'] for a in runs]
    primary['sensitivity']=[dict(threshold=a['threshold'],edge=a['boundary'],gap=[a['min_gap'],a['max_gap']],tree=dict(collections.Counter(r['status'] for r in a['tree'])),solved=dict(collections.Counter(r['status'] for r in a['solved'])),cut_counts={c:dict(collections.Counter(r['status'] for r in a['cuts'] if r['cohort']==c)) for c in ['solved','tree']}) for a in runs]
    return primary
if __name__=='__main__':print(json.dumps(main(),ensure_ascii=False,separators=(',',':')))
