File size: 23,842 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
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
import argparse, random, itertools, collections, json, math
from pathlib import Path
from common import *

CVS_OPTIONS=[
 ['0 — Two separate connecting structures cannot be established.','1 — Two structures are partly distinguishable, but overlap or limited clarity prevents a clear assessment.','2 — Two connecting structures are clearly distinguishable.'],
 ['0 — The cystic plate is not visible or requires further dissection.','1 — It is visible, but exposure, overlap, or viewing angle limits the assessment.','2 — It is clearly exposed to approximately the lower third of the gallbladder.'],
 ['0 — Tissue or technical limitations prevent assessment of the triangle and its structures.','1 — The triangle is only partly clear or its view remains limited.','2 — The triangle is fully cleared and its structures are clearly visible.'],['No','Yes']]
CVS_QUESTIONS=['How clearly are exactly two structures seen connecting to the gallbladder?','How clearly is the cystic plate exposed at the lower third of the gallbladder?','How clearly has the hepatocystic triangle been cleared to reveal its structures?','Is the critical view of safety (CVS) achieved in this image?']

class Generator:
    def __init__(self,s,config):
        self.s=s;self.cfg=config;self.rng=random.Random(config['seed']);self.pool=collections.defaultdict(list);self.seen=set();self.reject=collections.Counter()
        self.all_targets=sorted({t[2] for d in s.ivt.values() for ts in d.values() for t in ts if t[2]!='null_target'})
        self.inst_verbs={i:sorted({t[1] for d in s.ivt.values() for ts in d.values() for t in ts if t[0]==i and t[1]!='null_verb'}) for i in INSTRUMENTS}
    def opts(self,answer,universe):
        neg=[x for x in universe if x!=answer]
        return [answer]+self.rng.sample(neg,3) if len(neg)>=3 else None
    def add(self,task,v,frames,q,choices,answer,query,answer_class=None,episode=None,marker=None,tags=None):
        if not choices or answer not in choices or len(set(choices))!=len(choices):return
        if isinstance(frames,int):frames=[frames]
        ident=digest([task,v,frames,query])[:20]
        if ident in self.seen:return
        self.seen.add(ident)
        self.pool[task].append(dict(candidate_id=ident,task=task,family=family(task),video=v,frames=frames,question=q,choices=choices,answer=answer,answer_class=str(answer_class if answer_class is not None else answer),query=query,episode=episode or f'{v}:{task}:{frames[0]//30}',marker=marker,tags=tags or {}))
    def run_episode(self,v,f,ts):return '|'.join(f'{v}:{"/".join(t)}:{self.s.action_starts.get((v,f,t),f)}' for t in sorted(ts))
    def frame(self,v,f):
        s=self.s;g=s.graphs.get((v,f));phase=int(s.phase[v][f]['Phase_gt']);raw=s.ivt[v].get(f,set());ts={t for t in raw if t[1]!='null_verb' and t[2]!='null_target'}
        # Current-phase task covers complete phase inventory; exclude phase boundaries by 3 s.
        if phase and f>=3 and f+3<len(s.phase[v]) and all(int(s.phase[v][k]['Phase_gt'])==phase for k in range(f-3,f+4)):
            ans=PHASES[phase];self.add('PR01',v,f,'Which surgical phase is shown in this image?',self.opts(ans,[PHASES[i] for i in range(1,7)]),ans,{'op':'phase','phase':phase},phase)
        if not g:return
        objs=s.clean_objects(v,f);u=s.unique(v,f);present=s.tools(v,f)
        if present is None:return
        # Require graph detections and expert category presence to agree for tool queries.
        toolids=[i for i,o in objs.items() if o['type']=='instrument' and o['component'] in INSTRUMENTS and o['component'] in present]
        rawtoolids=[i for i,o in enumerate(g['objects']) if o['type']=='instrument' and o['component'] in INSTRUMENTS]
        complete_tools=set(rawtoolids)==set(toolids) and {g['objects'][i]['component'] for i in toolids}==(present&set(INSTRUMENTS))
        for i in toolids:
            o=objs[i];a=o['component'];ans=title(a)
            self.add('P01',v,f,'What type of instrument is indicated by box A?',self.opts(ans,[title(t) for t in INSTRUMENTS]),ans,{'op':'object_identity','id':i,'component':a},a,marker={'kind':'box','object_id':i,'bbox':o['bbox'],'label':'A'})
        for a in ANATOMIES:
            if a not in u:continue
            i=u[a];o=objs[i];b=o['bbox'];point=o['center']
            # Marker placement remains a visual-review gate, not automatic anatomy truth.
            ans=title(a)
            self.add('P02',v,f,'Which anatomical structure is indicated by arrow A?',self.opts(ans,[title(t) for t in ANATOMIES]),ans,{'op':'object_identity','id':i,'component':a},a,marker={'kind':'arrow','object_id':i,'bbox':b,'point':point,'label':'A','review_required':True})
        # Tool absence is defined by original Tool_gt, not missing SG detections.
        for a in INSTRUMENTS:
            val=a in present
            if val and a not in {objs[i]['component'] for i in toolids}:continue
            if not val and any(o['component']==a for o in g['objects']):continue
            self.add('P03',v,f,f'Is a {display(a)} visible in this image?',['Yes','No'],'Yes' if val else 'No',{'op':'tool_presence','tool':a},'Yes' if val else 'No',tags={'tool':a})
        if complete_tools:
            for a in INSTRUMENTS:
                ids=[i for i in toolids if objs[i]['component']==a];n=len(ids)
                if n>3:continue
                # Duplicate overlapping detections are not counted as separate tools.
                bad=False
                for i,j in itertools.combinations(ids,2):
                    b=objs[i]['bbox'];c=objs[j]['bbox'];inter=max(0,min(b[2],c[2])-max(b[0],c[0]))*max(0,min(b[3],c[3])-max(b[1],c[1]));union=(b[2]-b[0])*(b[3]-b[1])+(c[2]-c[0])*(c[3]-c[1])-inter
                    if union and inter/union>.5:bad=True
                if not bad:self.add('P04',v,f,f'How many separate {display(a)} instruments are visible?',['0','1','2','3'],str(n),{'op':'count_tools','tool':a,'ids':ids},n,tags={'tool':a})
        for a in INSTRUMENTS:
            if a not in u or u[a] not in toolids:continue
            ans=s.quadrant(v,f,u[a])
            if ans:self.add('P05',v,f,f'In which image quadrant is the center of the {display(a)} bounding box?',QUADS,ans,{'op':'absolute_quadrant','id':u[a]},ans,tags={'object':a})
        # IVT three-way querying, with full matching answer-set uniqueness.
        for inst,verb,target in sorted(ts):
            if inst not in present or inst not in u or u[inst] not in toolids:continue
            ep=self.run_episode(v,f,[(inst,verb,target)])
            aa={t[1] for t in ts if t[0]==inst and t[2]==target}
            if len(aa)==1:
                ans=GERUND[verb];self.add('R01',v,f,f'What action is the {display(inst)} performing on the {display(target)}?',self.opts(ans,[GERUND[t] for t in VERBS]),ans,{'op':'ivt_verb','instrument':inst,'target':target},verb,ep,tags={'instrument':inst,'verb':verb,'target':target})
            aa={t[0] for t in ts if t[1]==verb and t[2]==target}
            if len(aa)==1:
                ans=title(inst);self.add('R02',v,f,f'Which instrument is {GERUND[verb].lower()} the {display(target)}?',self.opts(ans,[title(t) for t in INSTRUMENTS]),ans,{'op':'ivt_instrument','verb':verb,'target':target},inst,ep,tags={'verb':verb,'target':target})
            aa={t[2] for t in ts if t[0]==inst and t[1]==verb}
            if len(aa)==1:
                ans=title(target);self.add('R03',v,f,f'Which target is the {display(inst)} {GERUND[verb].lower()}?',self.opts(ans,[title(t) for t in self.all_targets]),ans,{'op':'ivt_target','instrument':inst,'verb':verb},target,ep,tags={'instrument':inst,'verb':verb})
        # Quadrants are mutually exclusive; every axis is supported by both directed arrays.
        pairs=list(itertools.permutations([a for a in u if a in ANATOMIES or a in INSTRUMENTS],2));self.rng.shuffle(pairs)
        emitted=collections.Counter()
        for a,b in pairs:
            ia,ib=u[a],u[b];A=a in INSTRUMENTS;B=b in INSTRUMENTS
            if A and ia not in toolids or B and ib not in toolids:continue
            task='R06' if A and B else 'R05' if A and not B else 'R04' if not A and not B else None
            if not task or emitted[task]>=2:continue
            ans=s.quadrant(v,f,ia,ib)
            if ans:
                self.add(task,v,f,f'Where is the center of the {display(a)} bounding box relative to the center of the {display(b)} bounding box?',QUADS,ans,{'op':'relative_quadrant','subject':ia,'reference':ib},ans,tags={'subject':a,'reference':b});emitted[task]+=1
        if phase==0:return
        facts=[t for t in sorted(ts) if t[0] in u and t[2] in u and u[t[0]] in toolids and s.action_edge(v,f,*t)]
        unique_facts=[t for t in facts if len({x[2] for x in ts if x[:2]==t[:2]})==1]
        # Two independent actions -> ordered target pair, including partial-match distractors.
        for x,y in itertools.combinations(unique_facts,2):
            if x[0]==y[0]:continue
            a,b=x[2],y[2];a2=self.rng.choice([t for t in ANATOMIES if t!=a]);b2=self.rng.choice([t for t in ANATOMIES if t!=b]);fmt=lambda p,q:f'({title(p)}, {title(q)})'
            ans=fmt(a,b);opts=[ans,fmt(a2,b),fmt(a,b2),fmt(a2,b2)]
            self.add('C01',v,f,f'Which ordered pair gives the structure {PARTICIPLE[x[1]]} by the {display(x[0])} first and the structure {PARTICIPLE[y[1]]} by the {display(y[0])} second?',opts,ans,{'op':'ordered_action_targets','queries':[list(x[:2]),list(y[:2])]},f'{a}|{b}',self.run_episode(v,f,[x,y]),tags={'ivts':[x,y]});break
        refs=[a for a in u if a in ANATOMIES];self.rng.shuffle(refs)
        # Spatially identify one tool, then follow its unique target.
        for ref in refs:
            for p in self.rng.sample(list(INV),4):
                if len(toolids)<2 or any(not s.consistent(v,f,i,u[ref],p) for i in toolids):continue
                ids=[i for i in toolids if s.spatial(v,f,i,u[ref],p)]
                if len(ids)!=1:continue
                inst=objs[ids[0]]['component'];targets={t[2] for t in facts if t[0]==inst}
                if len(targets)!=1 or targets!={t[2] for t in ts if t[0]==inst}:continue
                target=next(iter(targets));ans=title(target)
                self.add('C02',v,f,f'Which structure is being acted on by the instrument whose bounding-box center is {self.phrase(p)} the {display(ref)} center?',self.opts(ans,[title(t) for t in ANATOMIES]),ans,{'op':'spatial_tool_target','reference':u[ref],'predicate':p},target,tags={'instrument':inst,'reference':ref});break
            else:continue
            break
        for inst,verb,target in unique_facts:
            for ref in refs:
                if ref==target:continue
                ans=s.quadrant(v,f,u[target],u[ref])
                if ans:
                    self.add('C03',v,f,f'Where is the bounding-box center of the structure the {display(inst)} is {GERUND[verb].lower()} relative to the {display(ref)} center?',QUADS,ans,{'op':'action_target_quadrant','instrument':inst,'verb':verb,'reference':u[ref]},ans,self.run_episode(v,f,[(inst,verb,target)]));break
        # Two spatial predicates intersect on exactly one known anatomy; each predicate has alternatives.
        anatomies=[a for a in ANATOMIES if a in u]
        refnames=[a for a in u if a in ANATOMIES or a in INSTRUMENTS and u[a] in toolids]
        possibilities=list(itertools.combinations(refnames,2));self.rng.shuffle(possibilities);done=False
        if len(anatomies)>=4:
            for r1,r2 in possibilities[:12]:
                for p,q in self.rng.sample(list(itertools.product(INV,repeat=2)),16):
                    universe=[a for a in anatomies if s.consistent(v,f,u[a],u[r1],p) and s.consistent(v,f,u[a],u[r2],q)]
                    A={a for a in universe if s.spatial(v,f,u[a],u[r1],p)};B={a for a in universe if s.spatial(v,f,u[a],u[r2],q)};I=A&B
                    if len(I)!=1 or len(A)<2 or len(B)<2 or len(universe)<4:continue
                    target=next(iter(I));d1=self.rng.choice(sorted(A-I));d2=self.rng.choice(sorted(B-I));rest=[a for a in universe if a not in [target,d1,d2]]
                    if not rest:continue
                    opts=[title(a) for a in [target,d1,d2,self.rng.choice(rest)]]
                    self.add('C04',v,f,f'Which structure has its bounding-box center both {self.phrase(p)} the {display(r1)} center and {self.phrase(q)} the {display(r2)} center?',opts,title(target),{'op':'spatial_intersection','references':[u[r1],u[r2]],'predicates':[p,q],'candidate_ids':[u[a] for a in universe]},target);done=True;break
                if done:break
        # Raw IVT categories support multi-instance class queries, without invented instance identity.
        for inst,verb in sorted({t[:2] for t in ts}):
            targets={t[2] for t in ts if t[:2]==(inst,verb)}
            if len(targets)<2 or not targets<=set(anatomies):continue
            for ref,p in itertools.product(refs,INV):
                universe=[a for a in anatomies if s.consistent(v,f,u[a],u[ref],p)];B={a for a in universe if s.spatial(v,f,u[a],u[ref],p)};I=targets&B
                if len(I)!=1 or len(B)<2 or len(universe)<4:continue
                target=next(iter(I));neg=list(set(universe)-I);ans=title(target)
                opts=[ans]+[title(a) for a in self.rng.sample(neg,3)]
                self.add('C05',v,f,f'Which structure is both {PARTICIPLE[verb]} by a {display(inst)} and has its bounding-box center {self.phrase(p)} the {display(ref)} center?',opts,ans,{'op':'action_spatial_intersection','instrument':inst,'verb':verb,'reference':u[ref],'predicate':p,'candidate_ids':[u[a] for a in universe]},target,self.run_episode(v,f,[t for t in ts if t[:2]==(inst,verb)]));break
            else:continue
            break
        # Relation-filtered counts use full instrument inventory. Positive and zero intersections allowed.
        if complete_tools and 1<=len(toolids)<=3:
            attempts=list(itertools.product(refs,INV,refs,INV));self.rng.shuffle(attempts)
            emitted_counts=set()
            for r1,p,r2,q in attempts[:90]:
                if r1==r2 and p==q or p==INV[q] and r1==r2:continue
                if any(not s.consistent(v,f,i,u[r1],p) or not s.consistent(v,f,i,u[r2],q) for i in toolids):continue
                A={i for i in toolids if s.spatial(v,f,i,u[r1],p)};B={i for i in toolids if s.spatial(v,f,i,u[r2],q)};n=len(A&B)
                if not A or not B or n in emitted_counts:continue
                self.add('C06',v,f,f'How many instruments have bounding-box centers both {self.phrase(p)} the {display(r1)} center and {self.phrase(q)} the {display(r2)} center?',['0','1','2','3'],str(n),{'op':'spatial_count','references':[u[r1],u[r2]],'predicates':[p,q],'tool_ids':toolids},n,tags={'sets':[sorted(A),sorted(B)]});emitted_counts.add(n)
                if len(emitted_counts)>=2:break
        # Spatial target selection -> observed instrument, no planning/next-action claims.
        if len({t[0] for t in facts})>=2 and {t[2] for t in ts} <= set(u):
            targets={t[2] for t in facts}
            for ref,p in itertools.product(refs,INV):
                if any(not s.consistent(v,f,u[a],u[ref],p) for a in targets):continue
                allowed={a for a in targets if s.spatial(v,f,u[a],u[ref],p)};insts={t[0] for t in facts if t[2] in allowed}
                if len(insts)!=1 or not allowed or allowed==targets:continue
                inst=next(iter(insts));ans=title(inst)
                self.add('C07',v,f,f'Which instrument is acting on a structure whose bounding-box center is {self.phrase(p)} the {display(ref)} center?',self.opts(ans,[title(t) for t in INSTRUMENTS]),ans,{'op':'spatial_target_instrument','reference':u[ref],'predicate':p},inst);break
        # CVS: every conflict-free labeled second in domain is eligible, not one-per-interval.
    @staticmethod
    def phrase(p):return {'left':'to the left of','right':'to the right of','above':'above','below':'below'}[p]
    def cvs(self):
        for v,good in self.s.cvt.items():
            for f,r in good.items():
                for k in range(4):
                    seg=r[f'episode_{k}']
                    if f<seg['start']+2 or f>seg['end']-2:continue
                    score=r['scores'][k] if k<3 else r['cv'];answer=CVS_OPTIONS[k][score]
                    self.add(f'V0{k+1}',v,f,CVS_QUESTIONS[k],CVS_OPTIONS[k],answer,{'op':'cvs','criterion':k,'scores':r['scores'],'rows':r['rows'],'label_source':r['source'],'segment':seg},str(score) if k<3 else answer,f'{v}:V{k+1}:{seg["start"]}:{seg["end"]}',tags={'calot_progress':self.calot_progress(v,f)})
    def calot_progress(self,v,f):
        x=self.s.phase[v];a=next(i for i,r in enumerate(x) if r['Phase_gt']==1);b=next(i for i,r in enumerate(x) if r['Phase_gt']==2)
        return (f-a)/(b-a)
    def dynamic(self):
        s=self.s
        for v in s.videos:
            n=len(s.phase[v]);dtchoices=[3,5,8,10]
            for f in range(3,n-13,2):
                for dt in self.rng.sample(dtchoices,2):
                    h=f+dt
                    if (v,f) not in s.graphs or (v,h) not in s.graphs:continue
                    pres=[s.tools(v,t) for t in [f,h]]
                    if any(t is None for t in pres):continue
                    uu=[s.unique(v,t) for t in [f,h]];objs=[s.clean_objects(v,t) for t in [f,h]]
                    ts=[{x for x in s.ivt[v].get(t,set()) if x[1]!='null_verb' and x[2]!='null_target'} for t in [f,h]]
                    # Stable presence states, category-level observation of both endpoints.
                    tool=self.rng.choice(INSTRUMENTS);states=[tool in p for p in pres]
                    stable=all(s.tools(v,k) is not None and (tool in s.tools(v,k))==state for t,state in zip([f,h],states) for k in range(t-1,t+2))
                    if stable and all(not state or tool in u for state,u in zip(states,uu)):
                        opts=[f'{a} → {b}' for a,b in itertools.product(['Absent','Present'],repeat=2)];ans=' → '.join('Present' if b else 'Absent' for b in states)
                        self.add('D01',v,[f,h],f'Which pair describes {display(tool)} visibility in frame 1 and frame 2, in that order?',opts,ans,{'op':'temporal_presence','tool':tool},ans,tags={'tool':tool,'changed':states[0]!=states[1],'dt':dt})
                    common=[i for i in INSTRUMENTS if all(i in u and i in p for u,p in zip(uu,pres))]
                    for inst in common:
                        targets={t[2] for t in ts[0] if t[0]==inst}&{t[2] for t in ts[1] if t[0]==inst}
                        for target in sorted(targets):
                            verbs=[{t[1] for t in a if t[0]==inst and t[2]==target} for a in ts]
                            if any(len(x)!=1 for x in verbs):continue
                            aa=[next(iter(x)) for x in verbs]
                            if not all({x[1] for x in s.ivt[v].get(k,set()) if x[0]==inst and x[2]==target}=={a} for t,a in zip([f,h],aa) for k in range(t-1,t+2)):continue
                            av=list(dict.fromkeys(aa))
                            if len(av)==1:
                                other=[a for a in self.inst_verbs[inst] if a not in av]
                                if not other:continue
                                av.append(self.rng.choice(other))
                            fmt=lambda a,b:f'{GERUND[a]} → {GERUND[b]}'
                            opts=[fmt(a,b) for a,b in itertools.product(av,repeat=2)];ans=fmt(*aa)
                            self.add('D02',v,[f,h],f'What is the {display(inst)} doing to the {display(target)} in frame 1 and frame 2, respectively?',opts,ans,{'op':'temporal_verb','instrument':inst,'target':target},ans,tags={'instrument':inst,'target':target,'changed':aa[0]!=aa[1],'dt':dt});break
                        verbs={t[1] for t in ts[0] if t[0]==inst}&{t[1] for t in ts[1] if t[0]==inst}
                        for verb in sorted(verbs):
                            tt=[{t[2] for t in a if t[:2]==(inst,verb)} for a in ts]
                            if any(len(x)!=1 for x in tt):continue
                            aa=[next(iter(x)) for x in tt]
                            if not all({x[2] for x in s.ivt[v].get(k,set()) if x[:2]==(inst,verb)}=={a} for t,a in zip([f,h],aa) for k in range(t-1,t+2)):continue
                            av=list(dict.fromkeys(aa))
                            if len(av)==1:av.append(self.rng.choice([a for a in self.all_targets if a not in av]))
                            fmt=lambda a,b:f'{title(a)} → {title(b)}';opts=[fmt(a,b) for a,b in itertools.product(av,repeat=2)];ans=fmt(*aa)
                            self.add('D03',v,[f,h],f'Which target is the {display(inst)} {GERUND[verb].lower()} in frame 1 and frame 2, respectively?',opts,ans,{'op':'temporal_target','instrument':inst,'verb':verb},ans,tags={'instrument':inst,'verb':verb,'changed':aa[0]!=aa[1],'dt':dt});break
                    phases=[int(s.phase[v][t]['Phase_gt']) for t in [f,h]]
                    if min(phases)>0 and all(int(s.phase[v][k]['Phase_gt'])==p for t,p in zip([f,h],phases) for k in range(t-1,t+2)):
                        av=list(dict.fromkeys(phases))
                        if len(av)==1:av.append(self.rng.choice([p for p in range(1,7) if p not in av]))
                        fmt=lambda a,b:f'{PHASES[a]} → {PHASES[b]}';opts=[fmt(a,b) for a,b in itertools.product(av,repeat=2)];ans=fmt(*phases)
                        self.add('D04',v,[f,h],'Which surgical phase is shown in frame 1 and frame 2, respectively?',opts,ans,{'op':'temporal_phase'},ans,tags={'changed':phases[0]!=phases[1],'dt':dt})
                    for inst in common:
                        refs=[a for a in ANATOMIES if all(a in u for u in uu)];self.rng.shuffle(refs)
                        for ref in refs[:2]:
                            for dirs in [('left','right'),('above','below')]:
                                vals=[]
                                for t,u in zip([f,h],uu):
                                    vv=[p for p in dirs if s.spatial(v,t,u[inst],u[ref],p)]
                                    if len(vv)!=1:break
                                    vals.append(vv[0])
                                if len(vals)!=2:continue
                                fmt=lambda a,b:f'{a.capitalize()} → {b.capitalize()}';opts=[fmt(a,b) for a,b in itertools.product(dirs,repeat=2)];ans=fmt(*vals)
                                self.add('D05',v,[f,h],f'Relative to the {display(ref)} bounding-box center, is the {display(inst)} center {dirs[0]} or {dirs[1]} in frame 1 and frame 2, respectively?',opts,ans,{'op':'temporal_spatial','instrument':inst,'reference':ref,'axis':list(dirs)},ans,tags={'changed':vals[0]!=vals[1],'dt':dt})
                                break
                            else:continue
                            break

def main():
    p=argparse.ArgumentParser();p.add_argument('--ori',default='/home/ach18533cl/workspace/ori_data');p.add_argument('--root',default='/home/ach18533cl/workspace/SceneBench');a=p.parse_args();root=Path(a.root);cfg=json.loads((root/'config.json').read_text());s=Sources(a.ori,cfg['test_videos']);gen=Generator(s,cfg)
    for v in s.videos:
        for f in range(0,len(s.phase[v]),2):gen.frame(v,f)
        print('Generated single frames',v,{k:len(x) for k,x in gen.pool.items()},flush=True)
    gen.cvs();gen.dynamic()
    for k,rows in gen.pool.items():write_jsonl(root/f'work/candidates/{k}.jsonl',rows)
    write_json(root/'work/pool_summary.json',dict(counts={k:len(x) for k,x in gen.pool.items()},answers={k:dict(collections.Counter(x['answer_class'] for x in rr)) for k,rr in gen.pool.items()},source_rejections=dict(s.counts)))
    write_json(root/'work/source_cvs_rows.json',s.cvs_rows)
    print('DONE', {k:len(x) for k,x in gen.pool.items()},flush=True)
if __name__=='__main__':main()