File size: 6,109 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
"""VLR data repair on db: the db extraction kept only CAM_M_F / L0 / R0 for many clips. Fetch, from the Hugging Face
tars (HTTP Range, member offsets from the QAP tar indexes), exactly the frames of the missing cameras that the VLR
records use, and write them at their original paths so vlr_encode_local.py encodes them. Every written file is listed in
<ROOT>/fetched_side_<split>.txt; --delete removes them again (after encoding). Token: $HF_TOKEN, else ~/.cache/huggingface/token (needs access to the gated dataset).
Run (db): python vlr_fetch_side.py --splits val train [--dry] [--retry]      python vlr_fetch_side.py --splits val train --delete
"""
import argparse
import json
import os
import pickle
import threading
import time
from collections import defaultdict
from concurrent.futures import ThreadPoolExecutor, as_completed
from pathlib import Path

import requests

ROOT = Path('/mnt/10TB_HDD/nuReasoning/vlr')
INDEX = Path('/mnt/10TB_HDD/nuReasoning/vljepa_testmatch/hub_tar_index/tar_index')
REPO = 'https://huggingface.co/datasets/nureasoning/nuReasoning/resolve/main/data'
CAMERAS = ['front', 'front_left', 'front_right', 'left', 'right', 'back', 'back_left', 'back_right']
LOCAL = threading.local()


def entry_member(path):
    rel = path.split('/data/', 1)[1]                 # train/part_2/<clip>/cameras/... or test/<clip>/cameras/...
    parts = rel.split('/')
    k = 3 if parts[0] == 'train' else 2
    return '/'.join(parts[:k]), '/'.join(parts[k:])


def session(token):
    if not hasattr(LOCAL, 's'):
        LOCAL.s = requests.Session(); LOCAL.s.headers['Authorization'] = f'Bearer {token}'
    return LOCAL.s


def fetch(token, entry, start, length):
    url = f'{REPO}/{entry}.tar'
    for attempt in range(8):
        try:
            r = session(token).get(url, headers={'Range': f'bytes={start}-{start + length - 1}'}, timeout=120)
            if r.status_code == 206 and len(r.content) == length:
                return r.content
        except requests.RequestException:
            pass
        time.sleep(min(2 ** attempt, 30))
    raise RuntimeError(f'range read failed {entry} {start}+{length}')


def needed(split, retry=False):
    """{(entry, member): local path} for the frames of cameras whose folder is absent; with retry also the cameras whose
    folder was created by an earlier run (its failed frames are fetched again, existing files are skipped later)."""
    lst = ROOT / f'fetched_side_{split}.txt'
    made = {os.path.dirname(f) for f in lst.read_text().split()} if retry and lst.is_file() else set()
    out = {}
    for r in pickle.load(open(ROOT / 'data' / f'{split}.pkl', 'rb')):
        for c in CAMERAS:
            d = os.path.dirname(r['video'][c][-1])
            if os.path.isdir(d) and d not in made:
                continue
            for p in r['video'][c]:
                out[entry_member(p)] = p
    return out


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument('--splits', nargs='+', default=['val', 'train'])
    ap.add_argument('--threads', type=int, default=48)
    ap.add_argument('--dry', action='store_true'); ap.add_argument('--delete', action='store_true')
    ap.add_argument('--retry', action='store_true', help='fetch again the frames that failed in an earlier run')
    a = ap.parse_args()
    if a.delete:
        for split in a.splits:
            lst = ROOT / f'fetched_side_{split}.txt'
            files = lst.read_text().split() if lst.is_file() else []
            for f in files:
                Path(f).unlink(missing_ok=True)
            for d in sorted({os.path.dirname(f) for f in files}, reverse=True):
                try:
                    os.rmdir(d)
                except OSError:
                    pass
            print(split, 'deleted', len(files), 'fetched files', flush=True)
        return
    token = os.environ.get('HF_TOKEN') or Path('~/.cache/huggingface/token').expanduser().read_text().strip()
    for split in a.splits:
        need = needed(split, a.retry)
        by = defaultdict(list)
        for (entry, member), p in need.items():
            by[entry].append((member, p))
        jobs, miss_idx, size = [], 0, 0
        for entry, ms in by.items():
            idx_f = INDEX / f'{entry}.json'
            if not idx_f.is_file():
                miss_idx += len(ms); continue
            idx = json.loads(idx_f.read_text())
            for member, p in ms:
                if member in idx and not os.path.isfile(p):
                    jobs.append((entry, idx[member][0], idx[member][1], p)); size += idx[member][1]
                elif member not in idx:
                    miss_idx += 1
        print(f'{split}: {len(need)} frames of absent cameras in {len(by)} clips, {len(jobs)} to fetch ({size / 1e9:.1f} GB), '
              f'{miss_idx} not in the tar index', flush=True)
        if a.dry or not jobs:
            continue
        lst = (ROOT / f'fetched_side_{split}.txt').open('a')
        t0, done, nbytes, lock = time.time(), 0, 0, threading.Lock()

        def one(job):
            entry, start, length, p = job
            data = fetch(token, entry, start, length)
            os.makedirs(os.path.dirname(p), exist_ok=True)
            tmp = p + '.part'
            with open(tmp, 'wb') as f:
                f.write(data)
            os.replace(tmp, p)
            return p, length

        with ThreadPoolExecutor(a.threads) as pool:
            for fut in as_completed([pool.submit(one, j) for j in jobs]):
                try:
                    p, n = fut.result()
                except Exception as e:  # noqa: BLE001
                    print('failed', repr(e)[:200], flush=True); continue
                with lock:
                    lst.write(p + '\n'); done += 1; nbytes += n
                if done % 2000 == 0 or done == len(jobs):
                    lst.flush(); el = time.time() - t0
                    print(f'{split} {done}/{len(jobs)} {nbytes / el / 1e6:.0f} MB/s eta {(len(jobs) - done) / (done / el) / 60:.0f} min', flush=True)
        lst.close()
    print('FETCH_DONE', flush=True)


if __name__ == '__main__':
    main()