File size: 8,532 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
"""Fetch from the Hugging Face tars only what VLR needs for 8-camera keyframes (HTTP Range, member tables cached).

  --kind val    official validation clips (data/validation/*): metadata.json, map.pkl, reasoning/*, every
                ego_state and annotations pickle, reasoning_questions.json if present, and the 8-camera window of
                the decision keyframe nearest to frame 100 -> <out>/<clip>/
  --kind supp   db supplement clips (3 cameras on disk): the 5 missing cameras at the side-camera offsets of every
                decision keyframe -> written into the supplement clip folder itself
  --kind train  new HF train clips (round 2, train2_entries.txt): the light files as for val and the 8-camera window
                of every decision keyframe -> <train-out>/<clip>/
A clip is skipped (logged ok=false, a rerun resumes it) while the disk has less than --min-free-gb free.
Camera window (as vlr_build): front kf-15..kf, others kf-20,-16,-12,-8,-4,kf; the keyframe image is the kf-1 frame.
Every image written is listed in <clip>/_vlr_fetched.txt, so `--delete` removes exactly those after encoding.
The walk over tar headers is latency bound (~0.5 s per request), so many clips are walked at once:
--procs processes x --threads threads. Resumable (tables cached, files with the right size skipped).
Run (db): HF_TOKEN=... NUR_WORK=/mnt/10TB_HDD/nuReasoning/vljepa_testmatch/hub_tar_index \
          python vlr_hub_fetch.py --kind val --entries val_entries.txt --out /mnt/10TB_HDD/nuReasoning/data_val_official
"""
import argparse
import json
import os
import shutil
import sys
import tarfile
import time
from concurrent.futures import ThreadPoolExecutor, as_completed
from multiprocessing import Pool
from pathlib import Path

import requests

sys.path.insert(0, '/home/db/ThuongBui/localization/vljepa_testmatch/tools')
import fetch_clips as fc  # noqa: E402

fc.BLOCK = 1 << 14                       # small members (pickles, json) share blocks; one request per image header


def tar_index(entry, session):
    """fetch_clips.tar_index without the BufferedReader: tarfile reads each 512-byte header straight from the
    block cache, so a header costs one Range request instead of two (the walk is latency bound)."""
    cache = fc.paths.WORK / 'tar_index' / f'{entry}.json'
    clip = entry.rsplit('/', 1)[-1]
    rf = fc.RangeFile(f'{fc.REPO}/data/{entry}.tar', session)
    if cache.exists():
        return json.loads(cache.read_text()), rf
    index = {}
    with tarfile.open(fileobj=rf, mode='r:') as tf:
        for m in tf:
            if m.isfile():
                name = fc.local_name(m.name, clip)
                if name:
                    index[name] = [m.offset_data, m.size]
    cache.parent.mkdir(parents=True, exist_ok=True)
    tmp = cache.with_suffix('.tmp'); tmp.write_text(json.dumps(index)); tmp.replace(cache)
    return index, rf
SUPP = Path('/mnt/10TB_HDD/nuReasoning/data_supplement_20261022')
CAMS = ['front', 'front_left', 'front_right', 'left', 'right', 'back', 'back_left', 'back_right']
SUPP_MISSING = ['left', 'right', 'back', 'back_left', 'back_right']
FRONT_OFFS = list(range(-15, 1))
SIDE_OFFS = [-20, -16, -12, -8, -4, 0]
ROOT = {}
MIN_FREE = [0]


def init(roots, min_free):
    ROOT.update(roots); MIN_FREE[0] = min_free


def decision_frames(clip_dir, meta):
    out = []
    for f in meta['frames']:
        p = f.get('reasoning')
        if not p or not (clip_dir / p).is_file():
            continue
        try:
            j = json.loads((clip_dir / p).read_text())
        except Exception:  # noqa: BLE001
            continue
        if j.get('Driving'):
            out.append(int(f['frame_index']))
    return out


def window(meta, kf, cams):
    frames = {int(f['frame_index']): f for f in meta['frames']}
    want = set()
    for c in cams:
        for o in (FRONT_OFFS if c == 'front' else SIDE_OFFS):
            i = kf + o
            i = kf - 1 if i == kf else i
            if i in frames:
                want.add(frames[i]['sensors']['cameras'][c])
    return want


def process(args):
    entry, kind, token = args
    clip = entry.rsplit('/', 1)[-1]
    cdir = ROOT[kind] / clip
    fc.clip_dir = lambda e: ROOT[kind] / e.rsplit('/', 1)[-1]          # members land in <root>/<clip>/
    if shutil.disk_usage(ROOT[kind]).free < MIN_FREE[0]:
        raise RuntimeError('disk guard: free space below --min-free-gb')
    sess = requests.Session(); sess.headers['Authorization'] = f'Bearer {token}'
    index, rf = tar_index(entry, sess)
    written = 0
    if kind in ('val', 'train'):
        light = [n for n in index if n in ('metadata.json', 'map.pkl', 'reasoning_questions.json')
                 or n.split('/')[0] in ('reasoning', 'ego_state', 'annotations')]
        written += fc.write_members(rf, entry, light, index)
    meta = json.loads((cdir / 'metadata.json').read_text())
    kfs = decision_frames(cdir, meta)
    if kind == 'val':
        kfs = sorted(kfs, key=lambda k: abs(k - 100))[:1] or [100]
        cams = CAMS
    elif kind == 'train':
        cams = CAMS
    else:
        cams = SUPP_MISSING
    imgs = set()
    for k in kfs:
        imgs |= window(meta, k, cams)
    missing = sorted(n for n in imgs if n not in index)
    imgs = sorted(n for n in imgs if n in index)
    written += fc.write_members(rf, entry, imgs, index)
    lst = cdir / '_vlr_fetched.txt'
    old = set(lst.read_text().split()) if lst.is_file() else set()
    lst.write_text('\n'.join(sorted(old | set(imgs))) + '\n')
    return entry, written, len(imgs), kfs, missing


def run_chunk(args):
    entries, kind, token, threads, tag, log = args
    t0, done, err, total = time.time(), 0, 0, 0
    with ThreadPoolExecutor(threads) as pool, open(log, 'a') as out:
        futs = {pool.submit(process, (e, kind, token)): e for e in entries}
        for f in as_completed(futs):
            try:
                e, w, n, kfs, miss = f.result()
                out.write(json.dumps(dict(entry=e, ok=True, bytes=w, images=n, kfs=kfs, missing=miss)) + '\n')
                total += w
            except Exception as ex:  # noqa: BLE001  a rerun resumes the failures
                err += 1
                out.write(json.dumps(dict(entry=futs[f], ok=False, err=f'{type(ex).__name__}: {ex}'[:300])) + '\n')
            out.flush(); done += 1
            if done % 20 == 0 or done == len(entries):
                el = time.time() - t0
                print(f'[{tag}] {done}/{len(entries)} errors {err} {total / 1e9:.1f} GB {el / 60:.0f} min '
                      f'eta {el / done * (len(entries) - done) / 60:.0f} min', flush=True)
    return done, err


def delete(kind, entries):
    n = b = 0
    for e in entries:
        cdir = ROOT[kind] / e.rsplit('/', 1)[-1]
        lst = cdir / '_vlr_fetched.txt'
        if not lst.is_file():
            continue
        for name in lst.read_text().split():
            p = cdir / name
            if p.is_file():
                b += p.stat().st_size; p.unlink(); n += 1
        lst.unlink()
    print(f'deleted {n} fetched images, {b / 1e9:.1f} GB', flush=True)


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument('--kind', choices=['val', 'supp', 'train'], required=True); ap.add_argument('--entries', required=True)
    ap.add_argument('--out', default='/mnt/10TB_HDD/nuReasoning/data_val_official')
    ap.add_argument('--procs', type=int, default=4); ap.add_argument('--threads', type=int, default=64)
    ap.add_argument('--limit', type=int, default=0); ap.add_argument('--delete', action='store_true')
    ap.add_argument('--log', default='')
    ap.add_argument('--train-out', default='/mnt/10TB_HDD/nuReasoning/data_train_hub')
    ap.add_argument('--min-free-gb', type=float, default=800)
    a = ap.parse_args()
    roots = dict(val=Path(a.out), supp=SUPP, train=Path(a.train_out))
    ROOT.update(roots); roots['train'].mkdir(parents=True, exist_ok=True)
    ents = [e for e in Path(a.entries).read_text().split() if e]
    if a.limit:
        ents = ents[:a.limit]
    if a.delete:
        return delete(a.kind, ents)
    token = os.environ['HF_TOKEN']
    log = a.log or f'hub_fetch_{a.kind}.jsonl'
    chunks = [(ents[i::a.procs], a.kind, token, a.threads, f'p{i}', log) for i in range(a.procs)]
    with Pool(a.procs, initializer=init, initargs=(roots, a.min_free_gb * 1e9)) as pool:
        res = pool.map(run_chunk, chunks)
    print('finished', sum(d for d, _ in res), 'clips,', sum(e for _, e in res), 'errors', flush=True)


if __name__ == '__main__':
    main()