File size: 8,387 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
import json, pickle, hashlib, collections, random, itertools, math
from pathlib import Path
import numpy as np
import openpyxl

INSTRUMENTS=['grasper','bipolar','hook','scissors','clipper','irrigator']
TOOLS=INSTRUMENTS+['specimen_bag']
ANATOMIES=['gallbladder','liver','omentum','gut','cystic_plate']
VERBS=['grasp','retract','dissect','coagulate','clip','cut','aspirate','irrigate','pack']
GERUND={'grasp':'Grasping','retract':'Retracting','dissect':'Dissecting','coagulate':'Coagulating','clip':'Clipping','cut':'Cutting','aspirate':'Aspirating','irrigate':'Irrigating','pack':'Packing'}
PARTICIPLE={'grasp':'grasped','retract':'retracted','dissect':'dissected','coagulate':'coagulated','clip':'clipped','cut':'cut','aspirate':'aspirated','irrigate':'irrigated','pack':'packed'}
PHASES={0:'Preparation',1:'Calot triangle dissection',2:'Clipping and cutting',3:'Gallbladder dissection',4:'Gallbladder packaging',5:'Cleaning and coagulation',6:'Gallbladder retraction'}
QUADS=['Upper left','Upper right','Lower left','Lower right']
INV={'left':'right','right':'left','above':'below','below':'above'}
FAMILIES={'P':'Perception','R':'Relation','C':'Composition','PR':'Procedure','V':'CVS','D':'Dynamic'}
def display(x):return x.replace('_',' ')
def title(x):return display(x).capitalize()
def digest(x):return hashlib.sha256(json.dumps(x,sort_keys=True,separators=(',',':')).encode()).hexdigest()
def write_json(p,x):Path(p).parent.mkdir(parents=True,exist_ok=True);Path(p).write_text(json.dumps(x,ensure_ascii=False,indent=2))
def read_jsonl(p):
    with open(p) as f:
        for l in f:
            if l.strip():yield json.loads(l)
def write_jsonl(p,rows):
    Path(p).parent.mkdir(parents=True,exist_ok=True)
    with open(p,'w') as f:
        for r in rows:f.write(json.dumps(r,ensure_ascii=False,separators=(',',':'))+'\n')
def family(task):return FAMILIES[''.join(x for x in task if x.isalpha())]

class Sources:
    def __init__(self,ori,videos):
        self.ori=Path(ori);self.videos=videos;self.phase={};self.ivt={};self.graphs={};self.action_starts={};self.cvt={};self.counts=collections.Counter()
        for fn in ['train/1fps_100_0.pickle','val/1fps.pickle','test/1fps.pickle']:
            p=self.ori/' Cholec80_labels/labels'/fn
            with p.open('rb') as f:d=pickle.load(f)
            for key,rows in d.items():
                v=int(key[5:])
                if v in videos:
                    self.phase[v]=rows
                    assert all(int(r['Original_frame_id'])==i*25 for i,r in enumerate(rows)),('alignment',v)
        vocab={int(a):tuple(b.split(',')) for line in (self.ori/'CholecT45/dict/triplet.txt').read_text().splitlines() for a,b in [line.split(':',1)]}
        for v in videos:
            self.ivt[v]={};starts={}
            for line in (self.ori/f'CholecT45/triplet/VID{v:02d}.txt').read_text().splitlines():
                row=list(map(int,line.split(',')));f=row[0];ts={vocab[i] for i,a in enumerate(row[1:]) if a}
                for t in ts:
                    if t not in starts:starts[t]=f
                    self.action_starts[v,f,t]=starts[t]
                starts={t:starts[t] for t in ts};self.ivt[v][f]=ts
            for f in range(len(self.phase[v])):
                p=self.ori/f'scene_graph/VID{v:02d}_{f}.json'
                if p.exists():
                    try:self.graphs[v,f]=json.loads(p.read_text())['scenes'][0]
                    except (KeyError,IndexError,ValueError):self.counts['invalid_sg']+=1
        self.cvs_rows=[]
        ws=openpyxl.load_workbook(self.ori/'Cholec80_CVS/cholec80-CVS.xlsx',data_only=True).active
        for i,row in enumerate(ws.values):
            if not i or int(row[0]) not in videos:continue
            r=dict(row=i+1,video=int(row[0]),start=int(row[2])*60+int(row[3]),end=int(row[4])*60+int(row[5]),scores=list(map(int,row[6:9])),total=int(row[9]),cv=int(row[1]))
            assert sum(r['scores'])==r['total'] and int(r['total']>=5)==r['cv']
            self.cvs_rows.append(r)
        for v in videos:
            first=next(i for i,r in enumerate(self.phase[v]) if r['Phase_gt']==2)
            rs=[r for r in self.cvs_rows if r['video']==v and r['start']<=r['end']]
            good={}
            for f in range(first):
                if self.phase[v][f]['Phase_gt']!=1:continue
                rr=[r for r in rs if r['start']<=f<=r['end']];vals={tuple(r['scores']) for r in rr}
                if len(vals)>1:self.counts['cvs_conflicting_seconds']+=1;continue
                score=next(iter(vals)) if vals else (0,0,0)
                good[f]=dict(scores=list(score),cv=int(sum(score)>=5),rows=[r['row'] for r in rr],source='explicit_interval' if rr else 'protocol_default_zero')
            for k in range(4):
                segments=[]
                for f,r in good.items():
                    value=r['scores'][k] if k<3 else r['cv']
                    if segments and segments[-1]['end']==f-1 and segments[-1]['value']==value:segments[-1]['end']=f
                    else:segments.append(dict(start=f,end=f,value=value))
                for seg in segments:
                    for f in range(seg['start'],seg['end']+1):
                        good[f][f'episode_{k}']=seg
            self.cvt[v]=good
        print('Source loaded',len(self.graphs),'graphs;',sum(len(x) for x in self.ivt.values()),'IVT frames',flush=True)
    def image_path(self,v,f):return self.ori/f'CholecT45/data/VID{v:02d}/{f:06d}.png'
    def tools(self,v,f):
        t=self.phase[v][f]['Tool_gt']
        return None if t is None else {TOOLS[i] for i,a in enumerate(t) if a}
    def clean_objects(self,v,f):
        g=self.graphs.get((v,f),{});out={}
        for i,o in enumerate(g.get('objects',[])):
            b=o.get('bbox');c=o.get('center')
            if not b or not c or len(b)!=4:continue
            x,y,X,Y=b
            if not (0<=x<X<=430 and 0<=y<Y<=240):continue
            if abs(c[0]-(x+X)/2)>0.01 or abs(c[1]-(y+Y)/2)>0.01:continue
            w=X-x;h=Y-y
            if o['type']=='instrument' and (w<15 or h<10 or w*h<450):continue
            if o['type']=='anatomy' and (w<25 or h<18 or w*h<1000):continue
            out[i]=o
        return out
    def unique(self,v,f):
        objs=self.clean_objects(v,f);cnt=collections.Counter(o['component'] for o in self.graphs.get((v,f),{}).get('objects',[]))
        return {o['component']:i for i,o in objs.items() if cnt[o['component']]==1}
    def spatial(self,v,f,a,b,p,require_edge=True):
        if a==b:return False
        o=self.graphs[v,f]['objects'];axis=0 if p in ['left','right'] else 1
        d=(o[a]['center'][axis]-o[b]['center'][axis])*(1 if p in ['right','below'] else -1)
        if d<(.05*(430 if axis==0 else 240)):return False
        if not require_edge:return True
        r=self.graphs[v,f]['relationships'];return a in r.get(p,[[]]*len(o))[b] and b in r.get(INV[p],[[]]*len(o))[a]
    def definite(self,v,f,a,b,p):
        if a==b:return True
        o=self.graphs[v,f]['objects'];axis=0 if p in ['left','right'] else 1
        return abs(o[a]['center'][axis]-o[b]['center'][axis])>=.05*(430 if axis==0 else 240)
    def consistent(self,v,f,a,b,p):
        return self.definite(v,f,a,b,p) and (not self.spatial(v,f,a,b,p,False) or self.spatial(v,f,a,b,p,True))
    def quadrant(self,v,f,a,b=None):
        o=self.graphs[v,f]['objects'];x,y=o[a]['center'];X,Y=(215,120) if b is None else o[b]['center']
        if abs(x-X)<21.5 or abs(y-Y)<12:return None
        p='left' if x<X else 'right';q='above' if y<Y else 'below'
        if b is not None and not (self.spatial(v,f,a,b,p) and self.spatial(v,f,a,b,q)):return None
        return ('Upper' if y<Y else 'Lower')+(' left' if x<X else ' right')
    def action_edge(self,v,f,inst,verb,target):
        u=self.unique(v,f)
        if inst not in u or target not in u:return False
        g=self.graphs[v,f];return u[target] in g['relationships'].get(verb,[[]]*len(g['objects']))[u[inst]]
    def source_evidence(self,v,frames):
        out=[]
        for f in frames:
            r=self.phase[v][f];g=self.graphs.get((v,f))
            out.append(dict(video=f'VID{v:02d}',frame_1fps=f,original_frame_id=int(r['Original_frame_id']),phase=int(r['Phase_gt']),tools=None if r['Tool_gt'] is None else list(map(int,r['Tool_gt'])),ivt=sorted(self.ivt[v].get(f,set())),scene_graph=g,source_image=str(self.image_path(v,f))))
        return out