Download code/vlr_crit_labels.py from ThuongBuiRVC/datariengcuathuongbui: direct link, hf CLI and curl.
- Browser
- Download file 5.86 kB
-
https://huggingface.co/datasets/ThuongBuiRVC/datariengcuathuongbui/resolve/main/code/vlr_crit_labels.py
- Command line
-
hf download hf://datasets/ThuongBuiRVC/datariengcuathuongbui/code/vlr_crit_labels.py
-
curl -L -o vlr_crit_labels.py https://huggingface.co/datasets/ThuongBuiRVC/datariengcuathuongbui/resolve/main/code/vlr_crit_labels.py
5.86 kB
| """Critical-component labels from the annotation text only (db, CPU) -> data/crit_<split>.pkl {kf_id: {c, has_cc, raw}}. | |
| For every keyframe: the Driving -> Critical components of its reasoning file, each mapped to one class of CRIT_CLS | |
| (the group of the component name, with the type for traffic lights, signs, routing intent and ego state). Nothing is | |
| computed from the map or matched to objects (positions are not labelled: deferred until audited). `raw` keeps the | |
| original (name, type) pairs for the audit. Workers get (kf_id, clip dir, kf) only (low memory). | |
| Run (db): python vlr_crit_labels.py --splits train val val_off train_supp --workers 3 | |
| """ | |
| import argparse | |
| import json | |
| import pickle | |
| import re | |
| from collections import Counter | |
| from multiprocessing import Pool | |
| from pathlib import Path | |
| from vlr_joint import CRIT_CLS | |
| OUT = Path('/mnt/10TB_HDD/nuReasoning/vlr/data') | |
| def group_of(g): | |
| """fava/crit_labels.group_of (the agreed grouping of the free-text component names).""" | |
| g = re.sub(r'\s*\d+$', '', str(g)).strip().lower() | |
| if any(k in g for k in ('pedestrian', 'vru', 'cyclist', 'bicycl')): | |
| return 'VRU' | |
| if g.startswith('road event'): | |
| return 'Road events' | |
| if 'traffic light' in g or 'traffic controller' in g: | |
| return 'Traffic Light' | |
| if g.startswith('traffic sign'): | |
| return 'Traffic sign' | |
| if any(k in g for k in ('vehicle', 'bus', 'trailer')): | |
| return 'Vehicle' | |
| if any(k in g for k in ('construction', 'cone', 'barrier', 'obstacle', 'barrel')): | |
| return 'Construction' | |
| if g.startswith('routing'): | |
| return 'Routing intent' | |
| if g.startswith('visibility'): | |
| return 'Visibility' | |
| if g.startswith('weather'): | |
| return 'Weather' | |
| if g.startswith('ego state'): | |
| return 'Ego states' | |
| if any(k in g for k in ('lane', 'curb', 'median', 'road boundar', 'road edge')): | |
| return 'Lane' | |
| return 'ODD' | |
| def crit_class(group, typ): | |
| t = str(typ).lower() | |
| if group == 'Traffic Light': | |
| if t.startswith('red') or 'flashing red' in t: | |
| return CRIT_CLS.index('TL red') | |
| if 'yellow' in t: | |
| return CRIT_CLS.index('TL yellow') | |
| return CRIT_CLS.index('TL green' if t.startswith('green') else 'TL other') | |
| if group == 'Traffic sign': | |
| return CRIT_CLS.index('Sign stop' if 'stop' in t else 'Sign yield' if 'yield' in t else 'Sign other') | |
| if group == 'Routing intent': | |
| return CRIT_CLS.index('Route left' if 'left' in t else 'Route right' if 'right' in t | |
| else 'Route straight' if ('straight' in t or 'follow' in t) else 'Route other') | |
| if group == 'Ego states': | |
| return CRIT_CLS.index('Ego stopped' if 'stop' in t else 'Ego other') | |
| return CRIT_CLS.index(group) | |
| def reasoning_of(cdir, kf, meta): | |
| f = next((x for x in meta['frames'] if int(x['frame_index']) == kf), None) | |
| rf = (f or {}).get('reasoning') or '' | |
| if rf and (cdir / rf).is_file(): | |
| return json.loads((cdir / rf).read_text()) | |
| for p in sorted((cdir / 'reasoning').glob('*.json')): # QAP keyframes: the file whose frame_index is kf | |
| j = json.loads(p.read_text()) | |
| if int(j.get('frame_index', -1)) == kf: | |
| return j | |
| return None | |
| def clip_jobs(job): | |
| """all keyframes of one clip (metadata.json read once per clip: the db HDD is the bottleneck).""" | |
| cdir, kfs = job | |
| try: | |
| meta = json.loads((Path(cdir) / 'metadata.json').read_text()) | |
| except Exception as e: # noqa: BLE001 | |
| return [(k, None, f'{type(e).__name__}: {e}'[:120]) for k, _ in kfs] | |
| return [one(k, Path(cdir), kf, meta) for k, kf in kfs] | |
| def one(kf_id, cdir, kf, meta): | |
| try: | |
| j = reasoning_of(cdir, kf, meta) | |
| except Exception as e: # noqa: BLE001 | |
| return kf_id, None, f'{type(e).__name__}: {e}'[:120] | |
| if j is None: | |
| return kf_id, None, 'no reasoning file' | |
| if int(j.get('frame_index', kf)) != kf: | |
| return kf_id, None, f'frame mismatch {j.get("frame_index")} != {kf}' | |
| dr = j.get('Driving'); dr = json.loads(dr) if isinstance(dr, str) and dr.strip() else dr | |
| cc = dr.get('Critical components') if isinstance(dr, dict) else None | |
| raw, cls = [], [] | |
| for k, v in (cc.items() if isinstance(cc, dict) else []): | |
| typ = v.get('Type', '') if isinstance(v, dict) else '' | |
| raw.append((str(k), str(typ))) | |
| cls.append(crit_class(group_of(k), typ)) | |
| return kf_id, dict(c=cls, has_cc=isinstance(cc, dict), raw=raw), None | |
| def main(): | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument('--splits', nargs='+', default=['train', 'val', 'val_off', 'train_supp']) | |
| ap.add_argument('--workers', type=int, default=3) | |
| a = ap.parse_args() | |
| for s in a.splits: | |
| p = OUT / f'{s}.pkl' | |
| if not p.is_file(): | |
| print(s, 'missing'); continue | |
| by_clip = {} | |
| for r in pickle.load(open(p, 'rb')): | |
| by_clip.setdefault(str(Path(r['video']['front'][0]).parents[2]), []).append((r['kf_id'], int(r['kf']))) | |
| jobs = sorted(by_clip.items()) | |
| with Pool(a.workers) as pool: | |
| res = [x for part in pool.map(clip_jobs, jobs, chunksize=8) for x in part] | |
| lab = {k: v for k, v, _ in res if v is not None} | |
| errs = Counter(e.split(':')[0] for _, v, e in res if v is None) | |
| pickle.dump(lab, open(OUT / f'crit_{s}.pkl', 'wb')) | |
| n = Counter(len(v['c']) for v in lab.values()) | |
| cls = Counter(CRIT_CLS[c] for v in lab.values() for c in v['c']) | |
| print(f'{s}: {len(lab)} / {len(res)} keyframes, errors {dict(errs)}, with Critical components ' | |
| f'{sum(v["has_cc"] for v in lab.values())}, components per keyframe {sorted(n.items())}', flush=True) | |
| print(' classes', dict(cls.most_common()), flush=True) | |
| if __name__ == '__main__': | |
| main() | |