"""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 .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)