File size: 11,293 Bytes
cfa2024 | 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 | """VLR data, step 1 (db, CPU): one record per QAP keyframe (train / val / test) with everything stage S1 needs.
Keyframes and questions: the QAP manifests (manifest_qap/keyframes_<split>.jsonl, <split>.jsonl), so the VQA
questions, splits and test set are exactly the benchmark's. Per keyframe:
video frame paths per camera. front: 16 consecutive frames kf-15..kf; the 7 others: kf-20,-16,-12,-8,-4,kf.
The keyframe image is replaced by the kf-1 image in train/val: the test release itself points frame 100
to the frame-99 image (metadata), so all splits see the same convention.
geo calibration (K, R, t, W, H per camera), ego kinematics, 4 past poses, route command: QAP context_qap.json
objects Spatial.object_relations: class, centre / size / yaw / velocity (ego frame), future positions, 2D boxes per
camera, semantic relations, conflict flags, devkit future-motion label, cross-view camera set
decision, counterfactual Driving decision (9 x 7 classes) and Counterfactual actions with their risk level
questions parsed QAP rows: subcategory, referenced camera / box / point / action, options, answer index
Output: <OUT>/<split>.pkl (list of dicts). Run (db): python vlr_build.py
"""
import json
import math
import os
import pickle
import re
import sys
from collections import defaultdict
from multiprocessing import Pool
from pathlib import Path
NUR = Path('/mnt/10TB_HDD/nuReasoning')
M = NUR / 'vljepa_testmatch' / 'manifest_qap'
OUT = NUR / 'vlr' / 'data'
CAMERAS = ['front', 'front_left', 'front_right', 'left', 'right', 'back', 'back_left', 'back_right']
FRONT_OFFS = list(range(-15, 1))
SIDE_OFFS = [-20, -16, -12, -8, -4, 0]
LON = ['Remain stopped', 'Quickly come to a stop', 'Gently come to a stop', 'Slow down quickly', 'Slow down gently',
'Quickly accelerate', 'Gently accelerate', 'Maintain speed', 'Reverse']
LAT = ['Slightly move left in the lane', 'Slightly move right in the lane', 'Left lane change', 'Right lane change',
'Turn left', 'Turn right', 'No lateral action']
ALIAS = {'Gently accelerate (speed up)': 'Gently accelerate', 'Quickly accelerate (speed up)': 'Quickly accelerate',
'Accelerate quickly': 'Quickly accelerate', 'Go straight': 'No lateral action'}
RISK = ['Safe', 'Unsafe', 'Suboptimal', 'Moderate risk', 'Highly dangerous']
CLASSES = ['car', 'truck', 'bus', 'motorcycle', 'bicycle', 'human', 'cone', 'construction', 'animal', 'other']
MOTION = ['approaching ego', 'moving away from ego', 'maintaining relative distance', 'stopped']
REL = ['stable_relative_distance', 'closing', 'separating', 'overtaking_ego', 'ego_overtaking', 'approaching', 'moving away']
BBOX_RE = re.compile(r'in the (?P<cam>[a-z ]+?) camera (?:with normalized 2D box|highlighted)[^\[]*\[(?P<x1>\d+), (?P<y1>\d+), (?P<x2>\d+), (?P<y2>\d+)\]')
CAM_RE = re.compile(r'in the (?P<cam>front left|front right|back left|back right|front|back|left|right) camera')
XY_RE = re.compile(r'\[x, y\] = \[(?P<x>-?\d+(?:\.\d+)?), (?P<y>-?\d+(?:\.\d+)?)\]')
RISK_Q = re.compile(r"risk level of: '(?P<lon>[^']+)' \(longitudinal\) \+ '(?P<lat>[^']+)' \(lateral\)")
def lon_i(s):
s = ALIAS.get(str(s).strip(), str(s).strip())
return LON.index(s) if s in LON else None
def lat_i(s):
s = ALIAS.get(str(s).strip(), str(s).strip())
return LAT.index(s) if s in LAT else None
def cls_i(cat):
c = str(cat).lower()
for k, v in (('pedestrian', 'human'), ('human', 'human'), ('bicycle', 'bicycle'), ('cyclist', 'bicycle'),
('motorcycle', 'motorcycle'), ('truck', 'truck'), ('trailer', 'truck'), ('bus', 'bus'),
('cone', 'cone'), ('barrier', 'construction'), ('construction', 'construction'),
('animal', 'animal'), ('car', 'car'), ('vehicle', 'car')):
if k in c:
return CLASSES.index(v)
return CLASSES.index('other')
def motion_label(rel):
"""devkit _future_motion_label."""
desc = str(rel.get('future_movement_description', '') or '').strip().lower()
if desc:
first = desc.split(';')[0].strip()
for k, v in (('approaching ego', 0), ('moving away from ego', 1), ('maintaining distance', 2)):
if k in first:
return v
pos, traj = rel.get('position_3d_ego') or {}, rel.get('future_trajectory_3d_ego') or []
if not traj:
return None
d0 = math.hypot(float(pos.get('x', 0)), float(pos.get('y', 0)))
d1 = math.hypot(float(traj[-1][0]), float(traj[-1][1]))
return 0 if d1 - d0 <= -2 else (1 if d1 - d0 >= 2 else 2)
def objects(sp):
views = {str(v.get('track_token')): sorted(v.get('views', [])) for v in (sp.get('cross_view_correspondence') or {}).values()}
out = []
for rel in sp.get('object_relations') or []:
p, v = rel.get('position_3d_ego') or {}, rel.get('velocity_3d_ego') or {}
obs = {c: [float(x) for x in o['detection_bbox_2d']] for c, o in (rel.get('camera_observations') or {}).items()
if o.get('detection_bbox_2d')}
b3 = next((o.get('detection_bbox_3d') for o in (rel.get('camera_observations') or {}).values() if o.get('detection_bbox_3d')), None) or {}
size = b3.get('size_lwh_m') or {}
traj = rel.get('future_trajectory_3d_ego') or []
sem, fc, geo = rel.get('semantic_relations') or {}, rel.get('future_conflict') or {}, rel.get('geometric_relations') or {}
out.append(dict(
token=str(rel.get('track_token')), cls=cls_i(rel.get('category')), cat=str(rel.get('category')),
center=[float(p.get('x', 0)), float(p.get('y', 0)), float(p.get('z', 0))],
size=[float(size.get('l', 0)), float(size.get('w', 0)), float(size.get('h', 0))] if size else None,
yaw=b3.get('yaw_ego_rad'), vel=[float(v.get('x', 0)), float(v.get('y', 0))],
fut=[[float(a), float(b)] for a, b, *_ in traj], dist=geo.get('euclidean_distance_m'), obs=obs,
views=views.get(str(rel.get('track_token')), sorted(obs)), front_rear=sem.get('front_rear'),
left_right=sem.get('left_right'), motion_rel=sem.get('motion_relation'),
motion=motion_label(rel), path_x=bool(fc.get('path_intersection_bev', False)),
conflict=bool(fc.get('conflict_with_ego', False))))
return out
def parse_question(r):
q = r.get('original_question') or r['question']
opts = r['option_texts'] if isinstance(r['option_texts'], list) else json.loads(r['option_texts'].replace("'", '"'))
out = dict(id=r['sample_id'], sub=r['subcategory'], options=opts,
answer=int(r['answer_index']) if str(r.get('answer_index', '')) not in ('', 'None') else -1)
m = BBOX_RE.search(q)
if m:
out['cam'] = m.group('cam').strip().replace(' ', '_')
out['box'] = [int(m.group(k)) for k in ('x1', 'y1', 'x2', 'y2')]
else:
m2 = CAM_RE.search(q)
if m2:
out['cam'] = m2.group('cam').replace(' ', '_')
m = XY_RE.search(q)
if m:
out['xy'] = [float(m.group('x')), float(m.group('y'))]
m = RISK_Q.search(q)
if m:
out['action'] = [lon_i(m.group('lon')), lat_i(m.group('lat'))]
if ' + ' in ' '.join(opts):
out['opt_actions'] = [[lon_i(a.split(' + ')[0]), lat_i(a.split(' + ')[1])] if ' + ' in a else None for a in opts]
return out
def record(args):
kf, rows, root, ctx = args
clip_dir = root / kf['clip']
try:
meta = json.load(open(clip_dir / 'metadata.json'))
except Exception as e:
return None, f'meta {e!r}'[:80]
frames = {f['frame_index']: f for f in meta['frames']}
k = int(kf['kf'])
is_test = 'test' in str(root)
def path(i, cam):
j = k - 1 if (i == k and not is_test) else i
f = frames.get(j)
return str(clip_dir / f['sensors']['cameras'][cam]) if f else None
video = {c: [path(k + o, c) for o in (FRONT_OFFS if c == 'front' else SIDE_OFFS)] for c in CAMERAS}
rec = dict(kf_id=kf['kf_id'], clip=kf['clip'], kf=k, video=video, geo=ctx, questions=[parse_question(r) for r in rows])
rf = next((f for f in [frames.get(k)] if f), None)
j = None
if rf and rf.get('reasoning'):
try:
j = json.load(open(clip_dir / rf['reasoning']))
except Exception:
j = None
if j is None:
for p in sorted((clip_dir / 'reasoning').glob('*.json')) if (clip_dir / 'reasoning').is_dir() else []:
try:
jj = json.load(open(p))
except Exception:
continue
if int(jj.get('frame_index', -1)) == k:
j = jj; break
if j is not None:
sp = j.get('Spatial'); sp = json.loads(sp) if isinstance(sp, str) and sp.strip() else sp
dr = j.get('Driving'); dr = json.loads(dr) if isinstance(dr, str) and dr.strip() else dr
cf = j.get('Counterfactual'); cf = json.loads(cf) if isinstance(cf, str) and cf.strip() else cf
rec['objects'] = objects(sp) if isinstance(sp, dict) else []
dd = (dr or {}).get('Driving decision') if isinstance(dr, dict) else None
rec['decision'] = [lon_i(dd.get('Longitudinal')), lat_i(dd.get('Lateral'))] if isinstance(dd, dict) else None
acts = []
for key in ('Alternative actions', 'Top safety-critical actions'):
for i_, a in enumerate((cf or {}).get(key) or []) if isinstance(cf, dict) else []:
if isinstance(a, dict) and a.get('Risk level') in RISK:
acts.append(dict(a=[lon_i(a.get('Longitudinal')), lat_i(a.get('Lateral'))], risk=RISK.index(a['Risk level']),
top=key.startswith('Top'), rank=i_))
rec['cf'] = acts
return rec, None
def main():
ctx = json.load(open(M / 'context_qap.json'))
roots = {}
for part in sorted((NUR / 'data' / 'train').glob('part_*')):
for c in os.listdir(part):
roots[c] = part
for c in os.listdir(NUR / 'data' / 'test'):
roots.setdefault(c, NUR / 'data' / 'test')
OUT.mkdir(parents=True, exist_ok=True)
for split in ('val', 'test', 'train'):
rows = defaultdict(list)
for line in (M / f'{split}.jsonl').open():
r = json.loads(line); rows[r['kf_id']].append(r)
kfs = [json.loads(line) for line in (M / f'keyframes_{split}.jsonl').open()]
jobs = [(k, rows[k['kf_id']], roots[k['clip']], ctx.get(f"{k['clip']}|{int(k['kf'])}")) for k in kfs if k['clip'] in roots]
with Pool(12) as pool:
res = pool.map(record, jobs, chunksize=4)
recs = [r for r, e in res if r is not None]
errs = [e for r, e in res if r is None]
pickle.dump(recs, open(OUT / f'{split}.pkl', 'wb'))
nq = sum(len(r['questions']) for r in recs)
nobj = sum(len(r.get('objects', [])) for r in recs)
miss = sum(1 for r in recs for v in r['video'].values() for p in v if p is None)
print(f'{split}: {len(recs)} keyframes ({len(kfs) - len(jobs)} without clip dir, {len(errs)} errors {errs[:2]}), '
f'{nq} questions, {nobj} objects, {sum(r.get("decision") is not None for r in recs)} decisions, '
f'{sum(len(r.get("cf", [])) for r in recs)} counterfactual actions, missing frame paths {miss}', flush=True)
if __name__ == '__main__':
main()
|