Datasets:
File size: 12,850 Bytes
7735593 | 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 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 | import argparse,json,random,collections,math,hashlib,shutil
from pathlib import Path
from PIL import Image,ImageDraw,ImageFont,ImageFilter
import numpy as np
from common import *
def image_stats(path):
im=Image.open(path).convert('RGB');small=im.resize((128,72));a=np.asarray(small.convert('L'),dtype=float);center=a[8:64,12:116]
gradient=float(np.abs(np.diff(center,axis=0)).mean()+np.abs(np.diff(center,axis=1)).mean())
valid=float((a>18).mean())>.35 and float(a.std())>14 and float((center>247).mean())<.5 and gradient>2
b=np.asarray(im.convert('L').resize((9,8)));bits=(b[:,1:]>b[:,:-1]).ravel();h=sum(int(x)<<i for i,x in enumerate(bits))
return dict(valid=bool(valid),width=im.width,height=im.height,std=float(a.std()),gradient=gradient,dhash=f'{h:016x}',sha256=hashlib.sha256(Path(path).read_bytes()).hexdigest())
class Selector:
def __init__(self,s,root,cfg):
self.s=s;self.root=root;self.cfg=cfg;self.rng=random.Random(cfg['seed']+1);self.used=collections.Counter();self.used_tasks=collections.defaultdict(set);self.dynamic_reserved=set();self.times=collections.defaultdict(list);self.episodes=collections.Counter();self.hashes=collections.defaultdict(list);self.stats={};self.rejected=collections.Counter();self.selected=[]
self.excluded_frames=set();self.excluded_candidates=set()
p=root/'work/review_exclusions.json'
if p.exists():
e=json.loads(p.read_text());self.excluded_candidates.update(e.get('candidate_ids',[]));self.excluded_frames.update((int(v),int(f)) for v,f in e.get('frames',[]))
p=root/'work/image_stats.json'
if p.exists():self.stats=json.loads(p.read_text())
def allowed(self,c):
if c['candidate_id'] in self.excluded_candidates:return False
v=c['video'];task=c['task'];fs=c['frames'];cvs=task.startswith('V');dynamic=task.startswith('D')
for f in fs:
key=(v,f)
if key in self.excluded_frames or key in self.dynamic_reserved:return False
if dynamic and self.used[key]:return False
if self.used[key]>=2:return False
if task in self.used_tasks[key]:return False
if task.startswith('R') and any(t.startswith('R') for t in self.used_tasks[key]):return False
dt=3 if cvs else 10
if any(abs(fs[0]-t)<dt for t in self.times[v,task]):return False
# Restrict repeated action facts for the same task and episode, not all frames of a CVS interval.
if not cvs and task in ['R01','R02','R03','C01','C03','C05'] and self.episodes[task,c['episode']]>=1:return False
if cvs and self.episodes[task,c['episode']]>=15:return False
# V04 negatives are phase/progress matched, not early all-zero easy cases.
if task=='V04' and c['answer_class']=='No' and c['tags']['calot_progress']<.65:return False
for f in fs:
kk=f'{v}:{f}'
if kk not in self.stats:
try:self.stats[kk]=image_stats(self.s.image_path(v,f))
except Exception:self.stats[kk]={'valid':False}
st=self.stats[kk]
if not st['valid']:self.rejected['image_quality']+=1;return False
hh=int(st['dhash'],16)
if any(bin(hh^int(old,16)).count('1')<=1 for old in self.hashes[v,task]):self.rejected['near_duplicate']+=1;return False
# A proposed anatomy arrow must avoid black regions and detected instrument bodies.
if c.get('marker') and c['marker']['kind']=='arrow':
m=c['marker'];im=Image.open(self.s.image_path(v,fs[0])).convert('RGB');g=self.s.graphs[v,fs[0]];x,y,X,Y=m['bbox'];points=[]
for px,py in [(m['point'][0],m['point'][1])]+[(x+(X-x)*a,y+(Y-y)*b) for a in [.35,.5,.65] for b in [.35,.5,.65]]:
if any(o['bbox'][0]-3<=px<=o['bbox'][2]+3 and o['bbox'][1]-3<=py<=o['bbox'][3]+3 for o in g['objects'] if o['type']=='instrument'):continue
xx=min(im.width-1,round(px/430*im.width));yy=min(im.height-1,round(py/240*im.height));pixel=im.getpixel((xx,yy))
if max(pixel)<45 or min(pixel)>245:continue
points.append([px,py])
if not points:return False
m['point']=points[0]
return True
def accept(self,c):
v=c['video'];task=c['task'];fs=c['frames'];self.selected.append(c)
for f in fs:
self.used[v,f]+=1;self.used_tasks[v,f].add(task);self.hashes[v,task].append(self.stats[f'{v}:{f}']['dhash'])
if task.startswith('D'):self.dynamic_reserved.add((v,f))
self.times[v,task].append(fs[0]);self.episodes[task,c['episode']]+=1
def select_task(self,task):
rows=list(read_jsonl(self.root/f'work/candidates/{task}.jsonl'));self.rng.shuffle(rows);target=self.cfg['target_counts'][task]
buckets=collections.defaultdict(lambda:collections.defaultdict(list))
for r in rows:buckets[r['answer_class']][r['video']].append(r)
classes=sorted(buckets);self.rng.shuffle(classes);counts=collections.Counter();videos=collections.Counter();tags=collections.Counter();changed=collections.Counter();selected=[]
explicit=self.cfg.get('cvs_answer_targets',{}).get(task)
# PR01 uses 50 questions per phase; other tasks balance only supported answer strata.
if task=='PR01':explicit={str(p):50 for p in range(1,7)}
cap_video=max(2,math.ceil(target/len(self.s.videos)*1.65))
rounds=0
while len(selected)<target:
available=[a for a in classes if any(buckets[a].values()) and (not explicit or counts[a]<explicit.get(a,0))]
if not available:break
available.sort(key=lambda a:(counts[a]/max(1,explicit.get(a,1)) if explicit else counts[a],self.rng.random()))
accepted=False
for ans in available:
vv=[v for v in buckets[ans] if buckets[ans][v]]
vv.sort(key=lambda v:(videos[v],self.rng.random()))
for v in vv:
if not task.startswith('V') and videos[v]>=cap_video:continue
while buckets[ans][v]:
c=buckets[ans][v].pop()
# Prevent a temporal question family from containing only stable endpoints.
if task.startswith('D') and changed[c['tags']['changed']]>=math.ceil(target*.6):continue
if not self.allowed(c):continue
self.accept(c);selected.append(c);counts[ans]+=1;videos[v]+=1
if task.startswith('D'):changed[c['tags']['changed']]+=1
accepted=True;break
if accepted:break
if accepted:break
if not accepted:break
rounds+=1
# CVS 0/1 redistribution only within the same question type if scarce 2-point slots fail QA.
if len(selected)<target and explicit and task in ['V01','V02','V03']:
for ans in ['0','1']:
vv=list(buckets.get(ans,{}));self.rng.shuffle(vv)
for v in vv:
while buckets[ans][v] and len(selected)<target and counts[ans]<math.ceil(target*.5):
c=buckets[ans][v].pop()
if self.allowed(c):self.accept(c);selected.append(c);counts[ans]+=1;videos[v]+=1
print('SELECT',task,len(selected),'of',target,'answers',dict(counts),'videos',dict(videos),flush=True)
return dict(target=target,selected=len(selected),answers=dict(counts),videos=dict(videos),temporal_changed=dict(changed))
def font(size):
for p in ['/usr/share/fonts/dejavu-sans-fonts/DejaVuSans.ttf','/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf']:
if Path(p).exists():return ImageFont.truetype(p,size)
return ImageFont.load_default()
def render(c,source,dest,cfg):
im=Image.open(source).convert('RGB');im.thumbnail((cfg['max_export_image_dimension'],cfg['max_export_image_dimension']),Image.Resampling.LANCZOS);m=c.get('marker');W,H=im.size
if m:
d=ImageDraw.Draw(im);scale=lambda p:(p[0]/430*W,p[1]/240*H);lw=max(2,round(W/450));size=max(20,round(H*.045));ft=font(size);color='#FFE33B'
if m['kind']=='box':
a,b=scale(m['bbox'][:2]),scale(m['bbox'][2:]);d.rectangle([*a,*b],outline=color,width=lw);xx=max(0,min(W-size*1.2,a[0]));yy=max(0,a[1]-size*1.35);d.rectangle((xx,yy,xx+size*1.1,yy+size*1.3),fill=color);d.text((xx+2,yy+1),'A',font=ft,fill='black')
else:
end=scale(m['point']);sx=end[0]-W*.12 if end[0]>W*.22 else end[0]+W*.12;sy=max(size*1.8,min(H-size*1.8,end[1]-H*.055));start=(sx,sy);d.line([start,end],fill='black',width=lw+2);d.line([start,end],fill=color,width=lw)
angle=math.atan2(end[1]-sy,end[0]-sx);L=max(9,W*.013);pts=[end,(end[0]-L*math.cos(angle-.48),end[1]-L*math.sin(angle-.48)),(end[0]-L*math.cos(angle+.48),end[1]-L*math.sin(angle+.48))];d.polygon(pts,fill=color);d.text((sx-size*.7,sy-size*1.2),'A',font=ft,fill=color,stroke_width=1,stroke_fill='black')
dest.parent.mkdir(parents=True,exist_ok=True);im.save(dest,'JPEG',quality=95,subsampling=0)
return dict(width=W,height=H,sha256=hashlib.sha256(dest.read_bytes()).hexdigest())
def export(root,s,selection,cfg):
items=[];bytask=collections.defaultdict(list)
for c in selection:bytask[c['task']].append(c)
positions=collections.defaultdict(list);rng=random.Random(cfg['seed']+2)
for task in cfg['target_counts']:
rows=bytask[task];rng.shuffle(rows)
for i,c in enumerate(rows):
qid=f'SCB-{task}-{i+1:04d}';k=len(c['choices']);position=i%k;others=[a for a in c['choices'] if a!=c['answer']];rng.shuffle(others);options=others[:];options.insert(position,c['answer'])
paths=[];ims=[]
for j,f in enumerate(c['frames']):
name=f'{qid}_{j+1}.jpg' if c.get('marker') else f'v{c["video"]:02d}_{f:06d}.jpg';rel=Path('images')/name;dest=root/'release'/rel
meta=render(c,s.image_path(c['video'],f),dest,cfg);paths.append(str(rel));ims.append(meta)
r=dict(id=qid,split='test',task=task,family=c['family'],question=c['question'],options=options,answer='ABCD'[position],answer_index=position,answer_text=c['answer'],answer_class=c['answer_class'],images=paths,image_metadata=ims,video_id=f'VID{c["video"]:02d}',frame_ids=c['frames'],source_frame_ids=[f*25 for f in c['frames']],episode_id=c['episode'],query=c['query'],marker=c.get('marker'),tags=c['tags'],candidate_id=c['candidate_id'],quality_status='source_consistency_checked_visual_review_pending' if c.get('marker') else 'source_consistency_and_image_quality_checked',source_evidence=s.source_evidence(c['video'],c['frames']))
items.append(r)
write_jsonl(root/'release/benchmark.jsonl',items);write_json(root/'release/config.json',cfg)
return items
def contacts(root,items):
for task in ['P01','P02','P04','C04','C05','C06','V01','V02','V03','V04']:
rows=[r for r in items if r['task']==task]
if task not in ['P01','P02','P04']:
# Stratified source-review panels, no model outputs are used for selection.
selected=[]
for a in sorted({r['answer_class'] for r in rows}):selected += [r for r in rows if r['answer_class']==a][:5]
rows=selected
for page in range(math.ceil(len(rows)/12)):
rr=rows[page*12:(page+1)*12];im=Image.new('RGB',(1440,4*232),(20,20,20));d=ImageDraw.Draw(im)
for i,r in enumerate(rr):
x=i%3*480;y=i//3*232;pic=Image.open(root/'release'/r['images'][0]);pic.thumbnail((480,207));im.paste(pic,(x,y+25));label=f'{r["id"]} | {r["answer_text"][:37]} | {r["video_id"]}/{r["frame_ids"][0]}'
d.text((x+3,y+3),label,font=font(15),fill='white')
p=root/f'work/review_panels/{task}_{page+1:02d}.jpg';p.parent.mkdir(parents=True,exist_ok=True);im.save(p,quality=90)
def main():
p=argparse.ArgumentParser();p.add_argument('--root',default='/home/ach18533cl/workspace/SceneBench');p.add_argument('--ori',default='/home/ach18533cl/workspace/ori_data');a=p.parse_args();root=Path(a.root);cfg=json.loads((root/'config.json').read_text());s=Sources(a.ori,cfg['test_videos']);sel=Selector(s,root,cfg)
order=['V03','V04','V02','V01','C05','C04','C06','D04','D03','D02','D05','D01','P02','P04','P01','P03','P05','C01','C02','C03','C07','R01','R02','R03','R04','R05','R06','PR01']
report={}
for t in order:report[t]=sel.select_task(t);write_json(root/'work/image_stats.json',sel.stats)
write_json(root/'work/selection_report.json',dict(tasks=report,rejections=dict(sel.rejected),total=len(sel.selected)))
write_jsonl(root/'work/selected_candidates.jsonl',sel.selected)
items=export(root,s,sel.selected,cfg);contacts(root,items);print('EXPORTED',len(items),flush=True)
if __name__=='__main__':main()
|