Datasets:
Download source/code/phase1_repair.py from Ethosoft/RefSeg-CA: direct link, hf CLI and curl.
- Browser
- Download file 7.95 kB
-
https://huggingface.co/datasets/Ethosoft/RefSeg-CA/resolve/main/source/code/phase1_repair.py
- Command line
-
hf download hf://datasets/Ethosoft/RefSeg-CA/source/code/phase1_repair.py
-
curl -L -o phase1_repair.py https://huggingface.co/datasets/Ethosoft/RefSeg-CA/resolve/main/source/code/phase1_repair.py
7.95 kB
| """Counterfactual Anchor-Consistent Projection (CACP). | |
| All primary decisions use only query text and predicted maps. The optional | |
| oracle anchor is isolated and must never be supplied to the primary method. | |
| Fixed defaults are declared before the evaluation predictions are observed. | |
| """ | |
| import re | |
| from dataclasses import dataclass, asdict | |
| import numpy as np | |
| from scipy import ndimage | |
| class Query: | |
| original: str | |
| target: str | |
| anchor: str = '' | |
| relation: str = '' | |
| opposite: str = '' | |
| plural: bool = False | |
| negate: bool = False | |
| supported: bool = False | |
| OPPOSITE = {'left':'right','right':'left','above':'below','below':'above'} | |
| VERBS = r'(?:segment|show|select|find|highlight)' | |
| IRREGULAR = {'people':'person','men':'man','women':'woman','children':'child'} | |
| def noun_phrase(s): | |
| s=re.sub(r'^(?:(?:all|every|both|two|the|a|an)\s+)+','',s.strip()) | |
| words=s.split() | |
| if not words:return s | |
| w=words[-1] | |
| if w in IRREGULAR:words[-1]=IRREGULAR[w] | |
| elif w.endswith('s') and not w.endswith(('ss','us','is')):words[-1]=w[:-1] | |
| return ' '.join(words) | |
| def parse_query(text): | |
| q=' '.join(text.lower().strip(' .').split()) | |
| neg=bool(re.match(r"^(?:do not|don't)\s+"+VERBS+r'\b',q)) | |
| cleaned=re.sub(r"^(?:do not|don't)\s+",'',q) if neg else q | |
| cleaned=re.sub(r'^'+VERBS+r'\s+','',cleaned) | |
| plural=bool(re.search(r'\b(all|every|both|two|people|men|women|children)\b',cleaned)) | |
| # Only a single explicit relation is supported; nested clauses fall back. | |
| pat=r'^(.+?)\s+(?:(?:to|on)\s+the\s+)?(left|right)\s+of\s+(.+)$' | |
| m=re.match(pat,cleaned) | |
| if not m:m=re.match(r'^(.+?)\s+(above|below)\s+(.+)$',cleaned) | |
| if m: | |
| t,rel,a=m.groups() | |
| if re.search(r'\b(left|right|above|below|that|which)\b',a): | |
| return Query(q,q,plural=plural,negate=neg) | |
| opp=re.sub(r'\b'+rel+r'\b',OPPOSITE[rel],q,count=1) | |
| return Query(q,noun_phrase(t),noun_phrase(a),rel,opp,plural,neg,True) | |
| m=re.match(r'^(?:the\s+)?(leftmost|rightmost|topmost|bottommost)\s+(.+)$',cleaned) | |
| if m:return Query(q,noun_phrase(m[2]),relation=m[1],plural=plural,negate=neg,supported=True) | |
| # Simple imperatives / quantified noun phrases are compositional; preserve | |
| # unrestricted natural expressions rather than pretending a regex is a parser. | |
| simple=bool(re.match(r'^'+VERBS+r'\s+',q) or re.match(r'^(all|every|both|two)\s+',cleaned)) | |
| if simple and len(cleaned.split())<=5: | |
| return Query(q,noun_phrase(cleaned),plural=plural,negate=neg,supported=True) | |
| return Query(q,q,plural=plural,negate=neg,supported=neg) | |
| def query_plan(text): | |
| q=parse_query(text) | |
| return q,list(dict.fromkeys([q.original,q.target]+([q.anchor,q.opposite] if q.anchor else []))) | |
| def components(prob,threshold): | |
| lab,n=ndimage.label(prob>=threshold,structure=np.ones((3,3),int)) | |
| sizes=np.bincount(lab.ravel());out=[];h,w=prob.shape | |
| for i,sl in enumerate(ndimage.find_objects(lab),1): | |
| if sl is None or sizes[i]<max(16,int(.0002*h*w)):continue | |
| mask=lab==i;ys,xs=np.nonzero(mask) | |
| out.append({'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 union(cs,shape): | |
| out=np.zeros(shape,bool) | |
| for c in cs:out|=c['mask'] | |
| return out | |
| def native(prob,threshold):return union(components(prob,threshold),prob.shape) | |
| def global_component(cs,relation): | |
| key='x' if relation in ('left','right','leftmost','rightmost') else 'y' | |
| positive=relation in ('right','rightmost','below','bottommost') | |
| return sorted(cs,key=lambda c:c[key],reverse=positive)[0] | |
| def repaired_maps(text,maps,threshold,oracle_anchor=None): | |
| q=parse_query(text);p=maps[q.original];base=native(p,threshold);empty=np.zeros_like(base) | |
| cs=components(p,threshold) | |
| largest=union([max(cs,key=lambda c:c['area'])],p.shape) if cs else empty | |
| action=empty if q.negate else base | |
| global_out=base if q.plural else largest | |
| if q.relation and cs:global_out=global_component(cs,q.relation)['mask'] | |
| if q.negate:global_out=empty | |
| pt=maps.get(q.target,p);targets=components(pt,threshold) | |
| target_out=union(targets,p.shape) if q.supported else base | |
| if q.negate:target_out=empty | |
| result={'frozen':base,'action_only':action,'largest':empty if q.negate else largest, | |
| 'global_direction':global_out,'target_only':target_out} | |
| flags={'supported':q.supported,'relation':q.relation,'anchor':q.anchor, | |
| 'anchor_margin':None,'score_margin':None,'reason':'fallback'} | |
| def project(use_cf=True,gate=True,oracle=False): | |
| if q.negate:return empty,'action',None,None | |
| if not q.supported:return base,'unsupported',None,None | |
| if not targets:return base,'no_target_proposal',None,None | |
| if q.relation.endswith('most'): | |
| return global_component(targets,q.relation)['mask'],'extreme',None,None | |
| if not q.anchor: | |
| if q.plural:return union(targets,p.shape),'plural',None,None | |
| scores=sorted(targets,key=lambda c:c['confidence'],reverse=True) | |
| margin=scores[0]['confidence']-(scores[1]['confidence'] if len(scores)>1 else 0) | |
| if gate and margin<.05:return base,'target_ambiguous',None,margin | |
| return scores[0]['mask'],'singular',None,margin | |
| anchors=components(maps[q.anchor],threshold) | |
| if oracle: | |
| if oracle_anchor is None:return base,'oracle_unavailable',None,None | |
| anchors=components(oracle_anchor.astype(float),.5) | |
| if not anchors:return base,'anchor_missing',None,None | |
| ac=anchors[0];am=ac['confidence']-(anchors[1]['confidence'] if len(anchors)>1 else 0) | |
| if gate and am<.05:return base,'anchor_ambiguous',am,None | |
| key='x' if q.relation in ('left','right') else 'y' | |
| sign=1 if q.relation in ('right','below') else -1 | |
| allowed=[] | |
| for c in targets: | |
| distance=sign*(c[key]-ac[key]) | |
| if distance<(.03 if gate else 0):continue | |
| residual=float((p[c['mask']]-maps[q.opposite][c['mask']]).mean()) | |
| score=c['confidence']+(.5*residual if use_cf else 0) | |
| allowed.append((score,c,residual)) | |
| if not allowed:return base,'relation_unsatisfied',am,None | |
| allowed.sort(key=lambda z:z[0],reverse=True) | |
| sm=allowed[0][0]-(allowed[1][0] if len(allowed)>1 else 0) | |
| # A confidently contradictory full-query response blocks a repair. | |
| if use_cf and gate and allowed[0][2]<-.05:return base,'counterfactual_veto',am,sm | |
| if not q.plural and gate and sm<.05:return base,'assignment_ambiguous',am,sm | |
| return union([c for _,c,_ in allowed] if q.plural else [allowed[0][1]],p.shape),'projected',am,sm | |
| result['anchor_nogate']=project(False,False)[0] | |
| result['anchor_gate']=project(False,True)[0] | |
| result['counterfactual_nogate']=project(True,False)[0] | |
| main,reason,am,sm=project(True,True);result['cacp']=main | |
| if oracle_anchor is not None:result['oracle_anchor']=project(True,True,True)[0] | |
| flags.update(reason=reason,anchor_margin=am,score_margin=sm,changed=bool(np.any(main!=base))) | |
| return result,flags | |
| def visual_features(prob,mask,threshold): | |
| p=np.asarray(prob,float);k=max(1,int(p.size*.01));top=np.partition(p.ravel(),p.size-k)[-k:] | |
| p2=np.clip(p,1e-6,1-1e-6) | |
| return [float(p.max()),float(top.mean()),float(p.mean()),float(p.std()),float(mask.mean()), | |
| float((-p2*np.log(p2)-(1-p2)*np.log(1-p2)).mean()),float(np.log1p(len(components(p,threshold))))] | |
| def score_mask(pred,gt): | |
| intersection=int(np.logical_and(pred,gt).sum());union_n=int(np.logical_or(pred,gt).sum()) | |
| return {'iou':intersection/union_n if union_n else 1.,'intersection':intersection,'union':union_n, | |
| 'pred_pixels':int(pred.sum()),'gt_pixels':int(gt.sum()),'empty':not bool(pred.any())} | |