File size: 11,969 Bytes
15689bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
"""Shared infra: config, disk guard, manifest, failures, remote-zip access."""
import hashlib
import json
import os
import subprocess
import time
import zipfile

import yaml

CFG = yaml.safe_load(open(os.path.join(os.path.dirname(__file__), "..", "config.yaml")))
# BENCH_BASE / BENCH_WORK / BENCH_STORE (2026-09-07): relocate the data roots for off-cluster run packages
BASE = os.environ.get("BENCH_BASE") or CFG["paths"]["base"]
WORK = os.environ.get("BENCH_WORK") or (f"{BASE}/work" if os.environ.get("BENCH_BASE") else CFG["paths"]["work"])
STORE = os.environ.get("BENCH_STORE") or (f"{BASE}/store" if os.environ.get("BENCH_BASE") else CFG["paths"]["store"])
for d in (WORK, STORE, f"{STORE}/annotations", f"{STORE}/samples",
          f"{STORE}/needed_videos", f"{STORE}/normalized", f"{STORE}/audio",
          f"{BASE}/logs"):
    os.makedirs(d, exist_ok=True)

FAILURES = f"{BASE}/logs/failures.jsonl"
MANIFEST = f"{BASE}/logs/manifest.jsonl"
DEDUP_LOG = f"{BASE}/logs/dedup_log.csv"


def log_failure(stage, key, error, **kw):
    rec = dict(ts=time.strftime("%F %T"), stage=stage, key=key, error=str(error)[:500], **kw)
    with open(FAILURES, "a") as f:
        f.write(json.dumps(rec, ensure_ascii=False) + "\n")


def manifest_done():
    done = {}
    if os.path.exists(MANIFEST):
        with open(MANIFEST) as f:
            for line in f:
                try:
                    r = json.loads(line)
                    if r.get("status") == "done":
                        done[r["key"]] = r
                except Exception:
                    pass
    return done


def manifest_write(key, status, **kw):
    with open(MANIFEST, "a") as f:
        f.write(json.dumps(dict(key=key, status=status, ts=time.strftime("%F %T"), **kw),
                           ensure_ascii=False) + "\n")


def du_gb(path):
    r = subprocess.run(["du", "-sb", path], capture_output=True, text=True)
    try:
        return int(r.stdout.split()[0]) / 1e9
    except Exception:
        return 0.0


_DISK_GUARD_CACHE = {"ts": 0.0, "val": None}
DISK_GUARD_TTL_S = 600   # du over the store (~55k files on a network FS) takes seconds; with ~20
                         # concurrent stage_c processes a per-item du dominated wall time (2026-09-03)


def disk_guard(force=False):
    """Return (ok, work_gb, store_gb). Caller MUST stop when not ok.
    Result is cached per process for DISK_GUARD_TTL_S; a not-ok result is never cached."""
    now = time.time()
    c = _DISK_GUARD_CACHE
    if not force and c["val"] is not None and c["val"][0] and now - c["ts"] < DISK_GUARD_TTL_S:
        return c["val"]
    w, s = du_gb(WORK), du_gb(STORE)
    ok = w <= CFG["limits"]["work_dir_limit_gb"] and s <= CFG["limits"]["store_limit_gb"]
    c["ts"], c["val"] = now, (ok, w, s)
    return ok, w, s


def sha256_file(path, bufsize=1 << 20):
    h = hashlib.sha256()
    with open(path, "rb") as f:
        while True:
            b = f.read(bufsize)
            if not b:
                break
            h.update(b)
    return h.hexdigest()


def hf_token():
    p = os.path.expanduser("~/.cache/huggingface/token")
    return open(p).read().strip() if os.path.exists(p) else None


def api_tree(repo, revision=None):
    """Full recursive file listing with sizes. Uses huggingface_hub pagination —
    the raw /tree REST endpoint silently truncates at 1000 entries.
    revision=None keeps the historical behavior (default branch / main);
    pass a commit sha or tag to pin (see exp/watch/REVISION_PINNING.md)."""
    from huggingface_hub import HfApi
    out = []
    for it in HfApi(token=hf_token()).list_repo_tree(repo, repo_type="dataset",
                                                     recursive=True, expand=False,
                                                     revision=revision):
        if getattr(it, "size", None) is not None:  # RepoFile
            out.append(dict(type="file", path=it.path, size=it.size))
    return out


_fs = None

def hffs():
    global _fs
    if _fs is None:
        from huggingface_hub import HfFileSystem
        _fs = HfFileSystem(token=hf_token())
    return _fs


_zip_handles = {}

def remote_zip(repo, zip_path):
    """Open a zip inside an HF dataset repo with range reads. Cached per path."""
    key = f"datasets/{repo}/{zip_path}"
    if key not in _zip_handles:
        f = hffs().open(key, "rb")
        _zip_handles[key] = zipfile.ZipFile(f)
    return _zip_handles[key]


def zip_namelist(repo, zip_path):
    return remote_zip(repo, zip_path).namelist()


def extract_member(repo, zip_path, member, dest):
    """Stream ONE member out of a remote zip (only its bytes transferred)."""
    zf = remote_zip(repo, zip_path)
    with zf.open(member) as src, open(dest, "wb") as out:
        while True:
            b = src.read(1 << 20)
            if not b:
                break
            out.write(b)
    return dest


TAR_EXT = (".tar", ".tar.gz", ".tgz", ".tar.bz2")
TAR_COMPRESSED = (".tar.gz", ".tgz", ".tar.bz2")
TAR_STREAM_CAP_GB = 10  # compressed tars have no random access; cap full-stream size

_tar_handles = {}


class ConcatFile:
    """Read-only seekable concatenation of fsspec files (split .tar.part.* archives)."""

    def __init__(self, fs, paths, sizes=None):
        self.fs = fs
        self.parts = []
        off = 0
        for i, p in enumerate(paths):
            size = sizes[i] if sizes and sizes[i] is not None else fs.info(p)["size"]
            self.parts.append((off, size, p))
            off += size
        self.size = off
        self.pos = 0
        self._open = {}

    # tarfile callers use `with _open_remote(...) as f` — without these the
    # first chunked-archive access dies with AttributeError: __enter__
    def __enter__(self):
        return self

    def __exit__(self, *exc):
        self.close()
        return False

    def seek(self, pos, whence=0):
        if whence == 1:
            pos += self.pos
        elif whence == 2:
            pos += self.size
        self.pos = max(0, pos)
        return self.pos

    def tell(self):
        return self.pos

    def read(self, n=-1):
        if n is None or n < 0:
            n = self.size - self.pos
        out = []
        while n > 0 and self.pos < self.size:
            hit = next(((o, s, p) for o, s, p in self.parts if o <= self.pos < o + s), None)
            if hit is None:
                break
            off, size, p = hit
            f = self._open.get(p)
            if f is None:
                f = self._open[p] = self.fs.open(p, "rb")
            f.seek(self.pos - off)
            chunk = f.read(min(n, off + size - self.pos))
            if not chunk:
                break
            out.append(chunk)
            self.pos += len(chunk)
            n -= len(chunk)
        return b"".join(out)

    def seekable(self):
        return True

    def readable(self):
        return True

    def close(self):
        for f in self._open.values():
            f.close()


_glob_cache = {}


def _natsort_key(p):
    """Natural sort: 'x.part2' < 'x.part10' (lexicographic puts part10 between
    part1 and part2 and CORRUPTS concatenated split archives)."""
    import re
    return [int(t) if t.isdigit() else t for t in re.split(r"(\d+)", str(p))]


def _open_remote(key):
    """fsspec handle for a repo path; a '*' means split chunks joined in order.
    glob+sizes are cached per pattern: without this every per-key fallback
    redoes 1 glob + N info() calls against the HF paths-info API and the
    1000 req/5min quota dies (VideoEval-Pro: 194 keys x 36 calls -> 429)."""
    fs = hffs()
    if "*" in key:
        cached = _glob_cache.get(key)
        if cached is None:
            detail = fs.glob(key, detail=True)
            if not detail:
                raise FileNotFoundError(key)
            cached = sorted(((p, (info or {}).get("size"))
                             for p, info in detail.items()),
                            key=lambda x: _natsort_key(x[0]))
            _glob_cache[key] = cached
        return ConcatFile(fs, [p for p, _ in cached], [s for _, s in cached])
    return fs.open(key, "rb")


def remote_tar(repo, tar_path):
    """Seekable tarfile for plain .tar (range reads). None for compressed.
    If tar_path itself doesn't exist, looks for split parts <tar_path>.part*."""
    import tarfile
    key = f"datasets/{repo}/{tar_path}"
    if key not in _tar_handles:
        if tar_path.lower().endswith(TAR_COMPRESSED) or "*" in tar_path:
            _tar_handles[key] = None
        else:
            fs = hffs()
            if fs.exists(key):
                f = fs.open(key, "rb")
            else:
                parts = sorted(fs.glob(key + ".part*"), key=_natsort_key)
                if not parts:
                    raise FileNotFoundError(key)
                f = ConcatFile(fs, parts)
            _tar_handles[key] = tarfile.open(fileobj=f, mode="r:")
    return _tar_handles[key]


def tar_namelist(repo, tar_path):
    """Member listing with a disk cache — remote tar walks cost ~0.1s/member."""
    import tarfile
    cache_dir = f"{STORE}/tar_index"
    os.makedirs(cache_dir, exist_ok=True)
    cache = f"{cache_dir}/{repo.replace('/', '__')}__{tar_path.replace('/', '__')}.json"
    if os.path.exists(cache):
        return json.load(open(cache))
    tf = remote_tar(repo, tar_path)
    if tf is not None:
        names = [m.name for m in tf.getmembers() if m.isfile()]
    else:
        names = []
        with _open_remote(f"datasets/{repo}/{tar_path}") as f, \
                tarfile.open(fileobj=f, mode="r|*") as t:
            for m in t:
                if m.isfile():
                    names.append(m.name)
    tmp = f"{cache}.tmp{os.getpid()}"    # atomic: concurrent shards write it
    json.dump(names, open(tmp, "w"))
    os.replace(tmp, cache)
    return names


def extract_tar_member(repo, tar_path, member, dest):
    import shutil
    import tarfile
    tf = remote_tar(repo, tar_path)
    if tf is not None:
        src = tf.extractfile(member)
        with open(dest, "wb") as out:
            shutil.copyfileobj(src, out, 1 << 20)
        return dest
    with _open_remote(f"datasets/{repo}/{tar_path}") as f, \
            tarfile.open(fileobj=f, mode="r|*") as t:
        for m in t:
            if m.name == member:
                with open(dest, "wb") as out:
                    shutil.copyfileobj(t.extractfile(m), out, 1 << 20)
                return dest
    raise KeyError(f"{member} not in {tar_path}")


def extract_tar_members_bulk(repo, tar_path, members, dest_dir):
    """One streaming pass through a (compressed) tar, extracting every wanted
    member — avoids re-streaming the whole archive per video."""
    import shutil
    import tarfile
    os.makedirs(dest_dir, exist_ok=True)
    want = set(members)
    got = {}
    with _open_remote(f"datasets/{repo}/{tar_path}") as f, \
            tarfile.open(fileobj=f, mode="r|*") as t:
        for m in t:
            if m.name in want:
                dest = os.path.join(dest_dir, m.name.replace("/", "_"))
                with open(dest, "wb") as out:
                    shutil.copyfileobj(t.extractfile(m), out, 1 << 20)
                got[m.name] = dest
                if len(got) == len(want):
                    break
    return got


def hf_download_file(repo, path, dest_dir, revision=None):
    """revision=None keeps the historical behavior (default branch / main);
    pass a commit sha to pin (see exp/watch/REVISION_PINNING.md)."""
    from huggingface_hub import hf_hub_download
    return hf_hub_download(repo_id=repo, filename=path, repo_type="dataset",
                           local_dir=dest_dir, token=hf_token(), revision=revision)


def ffprobe(path):
    r = subprocess.run(["ffprobe", "-v", "error", "-print_format", "json",
                        "-show_format", "-show_streams", path],
                       capture_output=True, text=True, timeout=300)
    return json.loads(r.stdout)