File size: 7,310 Bytes
9126e0d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
"""Reviewer-requested cache replay; no model fitting or additional language queries.

The R2 rule remains primary. All sweeps are post-review diagnostics. GT is used
only by score(), never by projection(). Each threshold sweep has a matched
native comparator. Rejected expressions contribute exactly zero paired delta.
"""
from pathlib import Path
import argparse, collections, hashlib, json, os, time
import numpy as np
from PIL import Image
from scipy import ndimage
import phase1_repair as p1
from r2_repair import scope_safe

ROOT=Path(os.getenv('REFSEG_ROOT',Path(__file__).resolve().parents[1]))
BASE=dict(anchor_margin=.05,target_margin=.05,geometry=.03,size_factor=1.,threshold_offset=0.)
CONFIGS={'primary':BASE.copy()}
for key,values in [('anchor_margin',[.02,.10]),('target_margin',[.02,.10]),('geometry',[.01,.05]),('size_factor',[.5,2.]),('threshold_offset',[-.05,.05])]:
    for v in values:CONFIGS[key+'_'+str(v)]={**BASE,key:v}

def components(prob,t,factor):
    lab,n=ndimage.label(prob>=t,structure=np.ones((3,3),int));h,w=prob.shape
    sizes=np.bincount(lab.ravel());out=[];minimum=max(1,int(max(16,int(.0002*h*w))*factor))
    for i,sl in enumerate(ndimage.find_objects(lab),1):
        if sl is None or sizes[i]<minimum:continue
        mask=lab==i;ys,xs=np.nonzero(mask)
        out.append(dict(mask=mask,area=int(sizes[i]),x=float(xs.mean()/w),y=float(ys.mean()/h),confidence=float(prob[mask].mean())))
    return sorted(out,key=lambda c:c['confidence'],reverse=True)

def projection(q,cs,shape,cfg):
    base=p1.union(cs[q.original],shape);empty=np.zeros(shape,bool)
    trace=dict(reason='fallback',plural=q.plural,relation=q.relation,anchor_margin=None,target_margin=None,boundary_distance=None)
    def finish(m,why):trace['reason']=why;return m,trace
    if q.negate:return finish(empty,'action')
    ts=cs.get(q.target,cs[q.original]);trace['target_components']=len(ts)
    if not ts:return finish(base,'target_missing')
    if q.relation.endswith('most'):return finish(p1.global_component(ts,q.relation)['mask'],'extreme')
    if not q.anchor:
        if q.plural:return finish(p1.union(ts,shape),'plural')
        tm=ts[0]['confidence']-(ts[1]['confidence'] if len(ts)>1 else 0);trace['target_margin']=tm
        return finish(base,'target_ambiguous') if tm<cfg['target_margin'] else finish(ts[0]['mask'],'singular')
    ac=cs[q.anchor];trace['anchor_components']=len(ac)
    if not ac:return finish(base,'anchor_missing')
    am=ac[0]['confidence']-(ac[1]['confidence'] if len(ac)>1 else 0);trace['anchor_margin']=am
    if am<cfg['anchor_margin']:return finish(base,'anchor_ambiguous')
    key='x' if q.relation in ('left','right') else 'y';sign=1 if q.relation in ('right','below') else -1
    distances=[sign*(c[key]-ac[0][key]) for c in ts]
    trace['boundary_distance']=min(abs(d-cfg['geometry']) for d in distances)
    allowed=[c for c,d in zip(ts,distances) if d>=cfg['geometry']];trace['eligible_components']=len(allowed)
    if not allowed:return finish(base,'relation_unsatisfied')
    tm=allowed[0]['confidence']-(allowed[1]['confidence'] if len(allowed)>1 else 0);trace['target_margin']=tm
    if not q.plural and tm<cfg['target_margin']:return finish(base,'assignment_ambiguous')
    return finish(p1.union(allowed if q.plural else [allowed[0]],shape),'projected')

def score(pred,gt,is_nt):
    op=np.asarray(Image.fromarray(pred).resize((480,480),Image.Resampling.NEAREST),bool)
    inter=int((op&gt).sum());union=int((op|gt).sum());nt=not pred.any()
    return dict(iou=float(nt) if is_nt else inter/union if union and not nt else 0.,intersection=inter if not is_nt else 0,union=0 if is_nt and nt else union,pred_nt=bool(nt))

def main():
    ap=argparse.ArgumentParser();ap.add_argument('--model',choices=['clipseg','groundedsam'],required=True);ap.add_argument('--shard',type=int,default=0);ap.add_argument('--shards',type=int,default=16);ap.add_argument('--limit',type=int,default=0);a=ap.parse_args()
    rows=[json.loads(s) for s in (ROOT/'data/natural_full.jsonl').read_text().splitlines()]
    groups=collections.defaultdict(list)
    for r in rows:groups[r['image_path']].append(r)
    paths=[p for p in sorted(groups) if any(scope_safe(r['query'])[0] for r in groups[p])][a.shard::a.shards]
    if a.limit:paths=paths[:a.limit]
    dest=ROOT/'results/r3';dest.mkdir(parents=True,exist_ok=True)
    name=f'{a.model}_{a.shard}of{a.shards}'+('_pilot' if a.limit else '')
    output=dest/(name+'.jsonl');count=0;t0=time.time();native_t=.5 if a.model=='clipseg' else .25
    with output.open('w') as out:
        for idx,path in enumerate(paths):
            group=groups[path];selected=[r for r in group if scope_safe(r['query'])[0]]
            texts=list(dict.fromkeys(q for r in group for q in p1.query_plan(r['query'])[1]))
            needed=set(q for r in selected for q in p1.query_plan(r['query'])[1]);maps={}
            for start in range(0,len(texts),12):
                batch=texts[start:start+12]
                if not needed.intersection(batch):continue
                digest=hashlib.sha256((path+'\n'+'\n'.join(batch)).encode()).hexdigest()[:24]
                cp=ROOT/'cache'/a.model/(digest+'.npz')
                with np.load(cp) as z:
                    assert z['texts'].tolist()==batch,(cp,'query mismatch')
                    maps.update({q:z[f'p{i}'].astype(np.float32) for i,q in enumerate(batch) if q in needed})
            cc={};gtcache={}
            for r in selected:
                q=p1.parse_query(r['query']);keys=list(dict.fromkeys([q.original,q.target]+([q.anchor] if q.anchor else [])))
                if r['ref_id'] not in gtcache:gtcache[r['ref_id']]=np.asarray(Image.open(ROOT/'data/natural/masks_official480'/f"ref_{r['ref_id']}.png"))>0
                gt=gtcache[r['ref_id']];allres={};tr=None;primary_mask=None
                for nameconf,cfg in CONFIGS.items():
                    threshold=native_t+cfg['threshold_offset'];cs={}
                    for key in keys:
                        ck=(key,threshold,cfg['size_factor'])
                        if ck not in cc:cc[ck]=components(maps[key],threshold,cfg['size_factor'])
                        cs[key]=cc[ck]
                    shape=maps[q.original].shape;base=p1.union(cs[q.original],shape)
                    pred,trace=projection(q,cs,shape,cfg)
                    allres[nameconf]=dict(frozen=score(base,gt,r['target_count']==0),sfap=score(pred,gt,r['target_count']==0),changed=bool((base!=pred).any()))
                    if nameconf=='primary':tr=trace;primary_mask=pred.copy()
                    else:allres[nameconf]['different_from_primary']=bool((primary_mask!=pred).any())
                row={k:r[k] for k in ['id','scene_id','split','query','target_count']}
                row.update(model=a.model,trace=tr,configs=allres)
                out.write(json.dumps(row)+'\n');count+=1
            out.flush()
            if idx%10==0:print(json.dumps(dict(image=idx,images=len(paths),records=count,seconds=time.time()-t0)),flush=True)
    meta=dict(status='COMPLETE',records=count,images=len(paths),seconds=time.time()-t0,args=vars(a),configs=CONFIGS,job_id=os.getenv('SLURM_JOB_ID'))
    output.with_suffix('.meta.json').write_text(json.dumps(meta,indent=2));print(json.dumps(meta),flush=True)
if __name__=='__main__':main()