File size: 9,816 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
108
109
110
111
112
113
114
115
116
117
118
119
120
"""New evaluation data, independent of unavailable original RefSeg generator.
Controlled RGB generation and official gRefCOCO subsampling with original masks.
The inference runner receives RGB + query, never scene objects or target labels.
"""
from pathlib import Path
import json,random,hashlib,collections,concurrent.futures,sys
import numpy as np
from PIL import Image,ImageDraw,ImageFilter,ImageEnhance
from prepare_assets import download
ROOT=Path(__file__).resolve().parents[1];DATA=ROOT/'data'
COLORS={'red':(214,47,47),'blue':(38,104,210),'green':(43,156,83),'orange':(233,139,34),'purple':(152,73,183),'yellow':(235,204,44),'pink':(222,105,151),'cyan':(38,177,196)}
SHAPES=['circle','square','triangle']
def raster(shape,x,y,r,size=320):
 m=Image.new('L',(size,size));d=ImageDraw.Draw(m);x*=size;y*=size;r*=size
 if shape=='circle':d.ellipse((x-r,y-r,x+r,y+r),fill=255)
 elif shape=='square':d.rectangle((x-r,y-r,x+r,y+r),fill=255)
 else:d.polygon([(x,y-r),(x-r,y+r),(x+r,y+r)],fill=255)
 return m
def save_mask(path,masks):
 out=np.zeros((320,320),bool)
 for m in masks:out|=np.asarray(m)>0
 Image.fromarray(out.astype('uint8')*255).save(path)
def controlled():
 records=[];scenes=[];rng_names=list(COLORS)
 for seed in [11,23,37,53,71]:
  rng=random.Random(seed)
  for idx in range(240):
   split='fit' if idx<40 else 'cal' if idx<80 else 'test';sid=f's{seed}_{idx:04d}'
   color,ac,other=rng.sample(rng_names,3);shape=rng.choice(SHAPES);ash=rng.choice([s for s in SHAPES if s!=shape]);y=rng.uniform(.38,.54)
   ax=rng.choice([.07,.335,.665,.93])
   objects=[(color,shape,x+rng.uniform(-.012,.012),y+rng.uniform(-.015,.015),rng.uniform(.055,.075)) for x in [.17,.5,.83]]
   objects += [(ac,ash,ax,.71,rng.uniform(.045,.055)),(other,shape,.21+rng.uniform(-.02,.02),.15,rng.uniform(.05,.065))]
   positions=[(.5,.15),(.8,.15),(.2,.86),(.5,.86),(.8,.86)]
   used={(color,shape),(ac,ash),(other,shape)}
   for x,yy in positions[:rng.randint(2,5)]:
    c,s=rng.choice([(c,s) for c in rng_names for s in SHAPES if (c,s) not in used]);used.add((c,s));objects.append((c,s,x+rng.uniform(-.025,.025),yy+rng.uniform(-.025,.025),rng.uniform(.045,.068)))
   image=Image.new('RGB',(320,320),(246,246,243));masks=[]
   for c,s,x,yy,r in objects:
    mask=raster(s,x,yy,r);image.paste(COLORS[c],mask=mask);masks.append(mask)
   folder=DATA/'controlled';(folder/'images').mkdir(parents=True,exist_ok=True);(folder/'masks').mkdir(exist_ok=True)
   image_path=folder/'images'/f'{sid}.png';image.save(image_path)
   anchor_path=folder/'masks'/f'{sid}_anchor.png';masks[3].save(anchor_path)
   absent=rng.choice([(c,s) for c in rng_names for s in SHAPES if (c,s) not in used]);phrase=f'{color} {shape}';anchor=f'{ac} {ash}';otherphrase=f'{other} {shape}'
   held=split=='test' and idx%2==1;verb=rng.choice(['highlight','select','find']) if held else rng.choice(['segment','show'])
   plural=f'all {phrase}s';left=f'all {phrase}s to the left of the {anchor}';right=f'all {phrase}s to the right of the {anchor}'
   if held:left=f'all {phrase}s on the left of the {anchor}';right=f'all {phrase}s on the right of the {anchor}'
   pairs=[('attribute',[(f'{verb} {plural}',[0,1,2]),(f'{verb} all {otherphrase}s',[4])]),('relation',[(f'{verb} {left}',[i for i in range(3) if objects[i][2]<ax]),(f'{verb} {right}',[i for i in range(3) if objects[i][2]>ax])]),('quantifier',[(f'{verb} the leftmost {phrase}',[0]),(f'{verb} {plural}',[0,1,2])]),('action',[(f'{verb} {plural}',[0,1,2]),(f'do not {verb} {plural}',[])]),('absence',[(f'{verb} {plural}',[0,1,2]),(f'{verb} all {absent[0]} {absent[1]}s',[])]),('paraphrase',[(f'show all {phrase}s',[0,1,2]),(f'select every {phrase}',[0,1,2])])]
   these=[]
   for family,endpoints in pairs:
    for ep,(query,ids) in enumerate(endpoints):
     rid=f'{sid}_{family}_{ep}';gt=folder/'masks'/f'{rid}.png';save_mask(gt,[masks[i] for i in ids])
     r={'id':rid,'scene_id':sid,'domain':'controlled','split':split,'official_split':None,'mode':family,'pair_id':sid+'_'+family,'endpoint':ep,'query':query,'image_path':str(image_path.relative_to(ROOT)),'gt_path':str(gt.relative_to(ROOT)),'anchor_gt_path':str(anchor_path.relative_to(ROOT)),'target_count':len(ids),'seed':seed,'template':'held' if held else 'seen','corruption':'clean'};records.append(r);these.append(r)
   scenes.append({'scene_id':sid,'split':split,'objects':[{'color':c,'shape':s,'x':x,'y':yy,'radius':r} for c,s,x,yy,r in objects],'rgb_sha256':hashlib.sha256(image.tobytes()).hexdigest()})
   if split=='test' and 80<=idx<120:
    rs=np.random.RandomState(seed*1000+idx)
    noisy=Image.fromarray(np.clip(np.asarray(image).astype(float)+rs.normal(0,18,(320,320,3)),0,255).astype('uint8'))
    for name,im in [('blur',image.filter(ImageFilter.GaussianBlur(2))),('noise',noisy),('dim',ImageEnhance.Brightness(image).enhance(.6))]:
     path=folder/'images'/f'{sid}_{name}.png';im.save(path)
     for base in these:
      r=dict(base);r.update(id=base['id']+'_'+name,image_path=str(path.relative_to(ROOT)),pair_id=base['pair_id']+'_'+name,corruption=name);records.append(r)
 (DATA/'controlled_scenes.jsonl').write_text(''.join(json.dumps(r)+'\n' for r in scenes))
 return records
def natural():
 from pycocotools import mask as maskutils
 refs=json.loads((ROOT/'assets/grefcoco/grefs(unc).json').read_text());inst=json.loads((ROOT/'assets/grefcoco/instances.json').read_text())
 anns={a['id']:a for a in inst['annotations']};images={i['id']:i for i in inst['images']};pools=collections.defaultdict(list)
 for r in refs:
  count=0 if r['no_target'] else len(r['ann_id']);group='zero' if count==0 else 'one' if count==1 else 'multi';pools[(r['split'],group)].append(r)
 selected=[];used=set();rng=random.Random(20260906)
 # One expression per image throughout: calibration scenes are independent units.
 for split,source,n in [('fit','train',200),('cal','train',300),('val','val',200),('testA','testA',200),('testB','testB',200)]:
  for group in (['zero','multi'] if split=='val' else ['zero','one','multi']):
   count=300 if split=='val' else n
   pool=list(pools[(source,group)]);rng.shuffle(pool);take=[]
   for r in pool:
    if r['image_id'] in used:continue
    used.add(r['image_id']);take.append((split,group,r))
    if len(take)==count:break
   if len(take)!=count:raise RuntimeError(f'Not enough distinct images for {split}/{group}: {len(take)}')
   selected.extend(take)
 out=DATA/'natural';(out/'images').mkdir(parents=True,exist_ok=True);(out/'masks').mkdir(exist_ok=True)
 failures={}
 def fetch(item):
  _,_,r=item;path=out/'images'/r['file_name']
  try:download('https://s3.amazonaws.com/images.cocodataset.org/train2014/'+r['file_name'],path);Image.open(path).verify();return r['image_id'],True
  except Exception as e:return r['image_id'],str(e)
 with concurrent.futures.ThreadPoolExecutor(max_workers=12) as ex:
  for iid,result in ex.map(fetch,selected):
   if result is not True:failures[iid]=result
 
 if failures:
  (DATA/'natural_download_failures.json').write_text(json.dumps(failures,indent=2))
  raise RuntimeError(f'{len(failures)} image downloads failed; rerun to complete cached selection')
 records=[];license_map={x['id']:x for x in inst['licenses']}
 for split,group,r in selected:
  if r['image_id'] in failures:continue
  info=images[r['image_id']];h,w=info['height'],info['width'];gt=np.zeros((h,w),bool)
  if not r['no_target']:
   for aid in r['ann_id']:
    seg=anns[aid]['segmentation']
    if isinstance(seg,list):rle=maskutils.merge(maskutils.frPyObjects(seg,h,w))
    elif isinstance(seg.get('counts'),list):rle=maskutils.frPyObjects(seg,h,w)
    else:rle=seg
    gt|=maskutils.decode(rle).astype(bool)
  if not r['no_target'] and not gt.any():raise ValueError('Official positive mask is empty')
  sentence=rng.choice(r['sentences']);rid='g'+str(r['ref_id'])+'_'+str(sentence['sent_id']);path=out/'masks'/f'{rid}.png';Image.fromarray(gt.astype('uint8')*255).save(path)
  records.append({'id':rid,'scene_id':'coco_'+str(r['image_id']),'domain':'natural','split':split,'official_split':r['split'],'mode':group,'pair_id':None,'endpoint':None,'query':sentence['sent'],'image_path':str((out/'images'/r['file_name']).relative_to(ROOT)),'gt_path':str(path.relative_to(ROOT)),'target_count':0 if r['no_target'] else len(r['ann_id']),'ref_id':r['ref_id'],'sent_id':sentence['sent_id'],'ann_ids':r['ann_id'],'seed':20260906,'template':'natural','corruption':'clean','license':license_map[info['license']],'source_image_url':'https://s3.amazonaws.com/images.cocodataset.org/train2014/'+r['file_name'],'flickr_url':info.get('flickr_url')})
 (DATA/'natural_download_failures.json').write_text(json.dumps(failures,indent=2));return records
def main():
 DATA.mkdir(exist_ok=True);c=controlled();n=natural();records=c+n
 # Guard data separation and maintain each corrupted image under its original scene.
 splits=collections.defaultdict(set)
 for r in records:splits[r['scene_id']].add(r['split'])
 assert all(len(s)==1 for s in splits.values())
 path=DATA/'manifest.jsonl';path.write_text(''.join(json.dumps(r,ensure_ascii=False)+'\n' for r in records))
 counts=collections.Counter((r['domain'],r['split'],r['corruption'],r['mode']) for r in records)
 summary={'records':len(records),'controlled_records':len(c),'natural_records':len(n),'distinct_scene_ids':len(splits),'manifest_sha256':hashlib.sha256(path.read_bytes()).hexdigest(),'counts':[dict(domain=k[0],split=k[1],corruption=k[2],mode=k[3],n=v) for k,v in sorted(counts.items())],'not_original_dataset':True,'natural_sampling':'One randomly selected expression per distinct image; image-disjoint fit/cal/val/testA/testB; balanced target-count strata; failures recorded without outcome-dependent replacement'}
 (DATA/'dataset_summary.json').write_text(json.dumps(summary,indent=2));print(json.dumps(summary,indent=2))
if __name__=='__main__':main()