File size: 7,561 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
import json,collections,hashlib,argparse
from pathlib import Path
from common import *

def answer_from_evidence(r):
    e=r['source_evidence'];q=r['query'];op=q['op'];ts=[{tuple(t) for t in x['ivt'] if t[1]!='null_verb' and t[2]!='null_target'} for x in e]
    g=e[0]['scene_graph'];o=g['objects'] if g else [];ids={x['component']:i for i,x in enumerate(o)}
    def exact1(x):
        assert len(x)==1,(r['id'],'ambiguous',x)
        return next(iter(x))
    def geo(a,b,p,frame=0):
        oo=e[frame]['scene_graph']['objects']
        if a==b:return False
        axis=0 if p in ['left','right'] else 1;d=oo[a]['center'][axis]-oo[b]['center'][axis]
        assert abs(d)>=(21.5 if axis==0 else 12),(r['id'],'near axis',a,b,p)
        ans=d*(1 if p in ['right','below'] else -1)>0
        if ans:
            rr=e[frame]['scene_graph']['relationships'];assert a in rr.get(p,[[]]*len(oo))[b] and b in rr.get(INV[p],[[]]*len(oo))[a],(r['id'],'spatial edge mismatch',a,b,p)
        return ans
    def quad(a,b=None):
        x,y=o[a]['center'];X,Y=(215,120) if b is None else o[b]['center'];assert abs(x-X)>=21.5 and abs(y-Y)>=12
        if b is not None:geo(a,b,'left' if x<X else 'right');geo(a,b,'above' if y<Y else 'below')
        return ('Upper' if y<Y else 'Lower')+(' left' if x<X else ' right')
    def targets(inst,verb=None,frame=0):return {t[2] for t in ts[frame] if t[0]==inst and (verb is None or t[1]==verb)}
    if op=='phase':return PHASES[e[0]['phase']]
    if op=='object_identity':
        a=o[q['id']]['component'];assert a==q['component'];return title(a)
    if op=='tool_presence':return 'Yes' if e[0]['tools'][TOOLS.index(q['tool'])] else 'No'
    if op=='count_tools':
        ii=[i for i,x in enumerate(o) if x['component']==q['tool'] and x['type']=='instrument'];assert ii==q['ids'];assert bool(ii)==bool(e[0]['tools'][TOOLS.index(q['tool'])]);return str(len(ii))
    if op=='absolute_quadrant':return quad(q['id'])
    if op=='relative_quadrant':return quad(q['subject'],q['reference'])
    if op=='ivt_verb':return GERUND[exact1({t[1] for t in ts[0] if t[0]==q['instrument'] and t[2]==q['target']})]
    if op=='ivt_instrument':return title(exact1({t[0] for t in ts[0] if t[1]==q['verb'] and t[2]==q['target']}))
    if op=='ivt_target':return title(exact1(targets(q['instrument'],q['verb'])))
    if op=='ordered_action_targets':return '('+', '.join(title(exact1(targets(i,v))) for i,v in q['queries'])+')'
    if op=='spatial_tool_target':
        ii=[i for i,x in enumerate(o) if x['type']=='instrument' and x['component'] in INSTRUMENTS and e[0]['tools'][TOOLS.index(x['component'])]]
        inst=o[exact1({i for i in ii if geo(i,q['reference'],q['predicate'])})]['component'];return title(exact1(targets(inst)))
    if op=='action_target_quadrant':return quad(ids[exact1(targets(q['instrument'],q['verb']))],q['reference'])
    if op=='spatial_intersection':
        sets=[{i for i in q['candidate_ids'] if geo(i,ref,p)} for ref,p in zip(q['references'],q['predicates'])];assert all(len(a)>1 for a in sets)
        return title(o[exact1(sets[0]&sets[1])]['component'])
    if op=='action_spatial_intersection':
        aa=targets(q['instrument'],q['verb']);bb={o[i]['component'] for i in q['candidate_ids'] if geo(i,q['reference'],q['predicate'])};assert len(aa)>1 and len(bb)>1;return title(exact1(aa&bb))
    if op=='spatial_count':
        ii=[i for i,x in enumerate(o) if x['type']=='instrument' and x['component'] in INSTRUMENTS];assert set(ii)==set(q['tool_ids'])
        sets=[{i for i in ii if geo(i,ref,p)} for ref,p in zip(q['references'],q['predicates'])];return str(len(sets[0]&sets[1]))
    if op=='spatial_target_instrument':
        ans={t[0] for t in ts[0] if t[2] in ids and geo(ids[t[2]],q['reference'],q['predicate'])};return title(exact1(ans))
    if op=='cvs':
        from generate import CVS_OPTIONS
        k=q['criterion'];score=q['scores'][k] if k<3 else int(sum(q['scores'])>=5);assert e[0]['phase']==1;return CVS_OPTIONS[k][score]
    if op=='temporal_presence':return ' → '.join('Present' if x['tools'][TOOLS.index(q['tool'])] else 'Absent' for x in e)
    if op=='temporal_verb':return ' → '.join(GERUND[exact1({t[1] for t in tt if t[0]==q['instrument'] and t[2]==q['target']})] for tt in ts)
    if op=='temporal_target':return ' → '.join(title(exact1(targets(q['instrument'],q['verb'],f))) for f in range(2))
    if op=='temporal_phase':return ' → '.join(PHASES[x['phase']] for x in e)
    if op=='temporal_spatial':
        aa=[]
        for f in range(2):
            oo=e[f]['scene_graph']['objects'];ii={x['component']:i for i,x in enumerate(oo)};pp=exact1({p for p in q['axis'] if geo(ii[q['instrument']],ii[q['reference']],p,f)});aa.append(pp.capitalize())
        return ' → '.join(aa)
    raise ValueError(op)

def main():
    p=argparse.ArgumentParser();p.add_argument('--root',default='/home/ach18533cl/workspace/SceneBench');a=p.parse_args();root=Path(a.root);items=list(read_jsonl(root/'release/benchmark.jsonl'));cfg=json.loads((root/'config.json').read_text());errors=[];counts=collections.Counter();frames=collections.Counter();dynamic=set();positions=collections.defaultdict(collections.Counter);task_answers=collections.defaultdict(collections.Counter);video_counts=collections.defaultdict(collections.Counter)
    assert len({r['id'] for r in items})==len(items)
    for r in items:
        try:
            assert int(r['video_id'][3:]) in cfg['test_videos'];assert r['split']=='test'
            ans=answer_from_evidence(r);assert ans==r['answer_text'],(ans,r['answer_text']);assert len(set(r['options']))==len(r['options']);assert r['options'][r['answer_index']]==ans;assert 'ABCD'[r['answer_index']]==r['answer']
            assert sum(x==ans for x in r['options'])==1
            for img,meta in zip(r['images'],r['image_metadata']):assert hashlib.sha256((root/'release'/img).read_bytes()).hexdigest()==meta['sha256']
            for f,original in zip(r['frame_ids'],r['source_frame_ids']):assert original==f*25;frames[r['video_id'],f]+=1
            if r['task'].startswith('D'):
                assert len(r['images'])==2 and 3<=r['frame_ids'][1]-r['frame_ids'][0]<=10
                for f in r['frame_ids']:assert (r['video_id'],f) not in dynamic;dynamic.add((r['video_id'],f))
            else:assert len(r['images'])==1
            if r['task'] in ['P01','P02']:assert r['marker'] is not None
            counts[r['task']]+=1;positions[r['task']][r['answer']]+=1;task_answers[r['task']][r['answer_class']]+=1;video_counts[r['task']][r['video_id']]+=1
        except Exception as ex:errors.append({'id':r['id'],'error':str(ex)})
    for key in dynamic:
        if frames[key]!=1:errors.append({'frame':key,'error':'dynamic endpoint reused'})
    for key,n in frames.items():
        if n>2:errors.append({'frame':key,'error':'source frame over reuse limit'})
    for t,c in positions.items():
        if max(c.values())-min(c.values())>1:errors.append({'task':t,'error':'answer position imbalance'})
    report=dict(status='pass' if not errors else 'fail',items=len(items),unique_source_frames=len(frames),tasks=dict(counts),answer_positions={k:dict(v) for k,v in positions.items()},answer_classes={k:dict(v) for k,v in task_answers.items()},video_counts={k:dict(v) for k,v in video_counts.items()},errors=errors)
    write_json(root/'release/validation_report.json',report);print(json.dumps({'status':report['status'],'items':len(items),'errors':errors[:30]},ensure_ascii=False),flush=True)
    if errors:raise SystemExit(1)
if __name__=='__main__':main()