from pathlib import Path import json,hashlib,time,os import cv2,numpy as np,shapely from PIL import Image from shapely.geometry import shape from shapely.ops import transform from layer_common import feature,sample from search_views import SearchViews from crossing_discovery import primitives,evidence,supported,periodic,sample_view,POLICY,VERSION from crossing_completion import observations,groups,model,recover O=Path('/out');raw=Path('/fullplan/full-map.json').read_bytes();base=json.loads(raw);start=time.monotonic();cv2.setNumThreads(2);cv2.setRNGSeed(2026) with np.load('/evidence_plan/fields.npz')as z:labels,height,low,high=z['labels'],z['z'],z['bounds'][0],z['bounds'][1] tiles=[t for t in json.loads(Path('/survey/tile-index.json').read_text())['tiles']if t['status']=='surveyed'];views=SearchViews(tiles,labels,low,high,None) seeds=[shape(f['geometry'])for f in json.loads(Path('/primary/crossing-seeds.json').read_text())] oldcross=shapely.union_all([shapely.force_2d(shape(f['geometry']))for f in base['features']if f['properties'].get('subtype')=='crosswalk']) (O/'crossing-seeds.json').write_text(json.dumps([feature(p,'road_marking',subtype='crosswalk')for p in seeds])) features=list(base['features']);rows=[];diagnostics=[] proposals=[(g,False)for g in groups(observations([feature(p,'road_marking',subtype='crosswalk')for p in seeds]))] proposals += [(g,True)for g in groups(observations(base['features']))if len(g)>=3] for group,anchored in proposals: # Two image primitives can propose a search axis; admission still requires # at least three separately observed, periodic bars in both original views. if len(group)<2: diagnostics.append(dict(seed_count=len(group),reason='insufficient-seeds',bounds_xy=list(shapely.union_all([r['p']for r in group]).bounds))) continue hull=shapely.union_all([r['p']for r in group]).convex_hull if not anchored and hull.distance(oldcross)<1.:continue m=model(group);center=m['origin'];tile=min(tiles,key=lambda t:np.linalg.norm(np.mean(t['bounds_xy'],axis=0)-center))['id'] def sampler(xy): rgb,valid=sample_view(xy,tile,views);road=sample(labels,xy,low,high)==1 return rgb,(~valid).astype(float),road.astype(float),np.ones(len(xy)) fitted,rec=recover(m,sampler);candidates=[r for r in fitted if r['observed']];d=dict(seed_count=len(group),bounds_xy=list(hull.bounds),profile=rec,accepted=False,evidence=[]);diagnostics.append(d) if len(candidates)<3 or not periodic([r['center']for r in candidates]):d['reason']='family-period-or-count';continue out=[];out_evidence=[];anchors=[r['f']for r in group]if anchored else[] for r in candidates: if anchored and not r['new']:continue p=r['polygon'];ev=evidence(p,views);d['evidence'].append(ev) if anchored: from crossing_discovery import aligned_with_anchors if not aligned_with_anchors(p,anchors):continue if not supported(ev):continue if not all(POLICY['min_length_m']<=e['length_m']<=POLICY['max_length_m']and POLICY['min_width_m']<=e['width_m']<=POLICY['max_width_m']for e in ev):continue if any(p.intersection(shapely.force_2d(shape(f['geometry']))).area>.02 for f in features if f['properties']['class']=='road_marking'):continue lifted=transform(lambda x,y,z=None:(x,y,sample(height,np.c_[x,y],low,high)),p) out.append(feature(lifted,'road_marking',subtype='crosswalk',method=VERSION,family_size=len(candidates),source_tiles=[e['tile']for e in ev],observed=True)) out_evidence.append(ev) if len(out)<(1 if anchored else 3):d['reason']='two-view-original-paint';continue # Do not publish a sparse subset of a family: every proposed observed bar must pass. if not anchored and len(out)!=len(candidates):d['reason']='incomplete-family-evidence';continue features.extend(out);d['accepted']=True display=shapely.union_all([hull]+[shapely.force_2d(shape(f['geometry']))for f in out]) rows.append(dict(kind='anchored-crossing-completion'if anchored else'whole-crossing',context_ids=[f['id']for f in anchors],before=[],after=out,source_ids=[],output_ids=[f['id']for f in out],bounds_xy=list(display.buffer(1).bounds),evidence=out_evidence)) result={**base,'features':features,'crossing_discovery':VERSION};(O/'full-map.json').write_text(json.dumps(result,allow_nan=False));(O/'arrow-rows.json').write_text(json.dumps(rows,indent=2));(O/'crossing-diagnostics.json').write_text(json.dumps(diagnostics,indent=2));(O/'crossing-report.json').write_text(json.dumps(dict(scene=os.environ['SCENE'],policy=POLICY,seeds=len(seeds),families=len(rows),added_stripes=sum(len(r['after'])for r in rows),seconds=time.monotonic()-start,source_sha256=hashlib.sha256(raw).hexdigest()),indent=2)) print('RESULT',len(seeds),len(rows),sum(len(r['after'])for r in rows),flush=True)