#!/usr/bin/env python3 """Build per-directory window index parquets for remote data parquets on HF. For every directory of data parquets in a HF dataset repo, this script reads only parquet footers plus the `duration` column (HTTP range requests, no audio download), computes sliding-window offsets per row, and writes one index parquet per directory: source_path string e.g. hf://datasets///.parquet row_group int32 parquet row-group ordinal inside source_path row_in_group int32 row ordinal inside that row group valid_offsets list window start seconds within the session num_windows int32 len(valid_offsets) Offsets follow the NeMo semantic: every full window that fits (stepping by --shift-sec); a session shorter than one window still yields a single 0.0 offset so the loader can pad it. Example: python build_window_index.py \ --repo-id tsw0411/Real_sd_ds_0701 --output-dir data/index --upload """ from __future__ import annotations import argparse import logging import time from concurrent.futures import ThreadPoolExecutor from pathlib import Path import pyarrow as pa import pyarrow.parquet as pq from huggingface_hub import HfApi, HfFileSystem LOG = logging.getLogger("build_window_index") INDEX_SCHEMA = pa.schema( [ pa.field("source_path", pa.string()), pa.field("row_group", pa.int32()), pa.field("row_in_group", pa.int32()), pa.field("valid_offsets", pa.list_(pa.float64())), pa.field("num_windows", pa.int32()), ] ) def compute_valid_offsets(duration: float, window_sec: float, shift_sec: float) -> list[float]: """Every full window that fits; short sessions get a single padded window at 0.""" offsets: list[float] = [] offset = 0.0 while offset + window_sec <= duration + 1e-6: offsets.append(round(offset, 6)) offset += shift_sec if not offsets and duration > 0: offsets.append(0.0) return offsets def index_one_parquet( fs: HfFileSystem, fs_path: str, window_sec: float, shift_sec: float, max_retries: int = 4, ) -> list[dict]: """Read footer + duration column of one remote parquet and index its rows. Transient network failures (SSL resets, closed HTTP clients) are retried with a fresh, uncached filesystem instance because a failed request can leave the shared HfFileSystem's HTTP client closed for all threads. """ source_path = f"hf://{fs_path}" for attempt in range(max_retries + 1): try: records: list[dict] = [] with fs.open(fs_path, "rb") as handle: parquet_file = pq.ParquetFile(handle) for group in range(parquet_file.num_row_groups): durations = parquet_file.read_row_group(group, columns=["duration"]) for row_in_group, duration in enumerate( durations.column("duration").to_pylist() ): offsets = compute_valid_offsets(float(duration), window_sec, shift_sec) records.append( { "source_path": source_path, "row_group": group, "row_in_group": row_in_group, "valid_offsets": offsets, "num_windows": len(offsets), } ) return records except Exception as exc: if attempt == max_retries: raise delay = min(30.0, 2.0**attempt) LOG.warning( "%s: read failed (%s: %s); retry %d/%d in %.0fs", fs_path, type(exc).__name__, exc, attempt + 1, max_retries, delay, ) time.sleep(delay) fs = HfFileSystem(skip_instance_cache=True) raise AssertionError("unreachable") def build_index_for_dir( fs: HfFileSystem, dir_name: str, fs_paths: list[str], output_path: Path, window_sec: float, shift_sec: float, workers: int, ) -> None: with ThreadPoolExecutor(max_workers=workers) as pool: per_file = list( pool.map( lambda path: index_one_parquet(fs, path, window_sec, shift_sec), sorted(fs_paths), ) ) records = [record for file_records in per_file for record in file_records] output_path.parent.mkdir(parents=True, exist_ok=True) pq.write_table(pa.Table.from_pylist(records, schema=INDEX_SCHEMA), output_path) LOG.info( "%s: %d files, %d rows, %d windows -> %s", dir_name, len(fs_paths), len(records), sum(record["num_windows"] for record in records), output_path, ) def main() -> None: parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) parser.add_argument("--repo-id", required=True, help="HF dataset repo, e.g. user/name") parser.add_argument("--output-dir", type=Path, required=True, help="Local staging directory") parser.add_argument("--window-sec", type=float, default=90.0) parser.add_argument("--shift-sec", type=float, default=8.0) parser.add_argument( "--test-suffix", default="_test", help="Directories ending with this suffix use --test-shift-sec (default: _test)", ) parser.add_argument( "--test-shift-sec", type=float, default=None, help="Shift for test directories; defaults to --window-sec (non-overlapping windows)", ) parser.add_argument("--workers", type=int, default=8, help="Concurrent remote reads per directory") parser.add_argument("--dirs", nargs="*", help="Only process these directory names") parser.add_argument("--force", action="store_true", help="Rebuild even if local index exists") parser.add_argument("--upload", action="store_true", help="Upload indexes to /index/") args = parser.parse_args() logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s") fs = HfFileSystem() repo_prefix = f"datasets/{args.repo_id}" all_parquets = fs.glob(f"{repo_prefix}/**/*.parquet") by_dir: dict[str, list[str]] = {} for fs_path in all_parquets: relative = fs_path[len(repo_prefix) + 1 :] parts = relative.split("/") if parts[0] == "index" or len(parts) < 2: continue # skip existing indexes and any root-level parquet by_dir.setdefault("/".join(parts[:-1]), []).append(fs_path) if args.dirs: missing = sorted(set(args.dirs) - set(by_dir)) if missing: parser.error(f"Directories not found in repo: {missing}") by_dir = {name: by_dir[name] for name in args.dirs} test_shift_sec = args.test_shift_sec if args.test_shift_sec is not None else args.window_sec LOG.info( "Indexing %d directories (window=%ss, shift=%ss, %s-suffix shift=%ss)", len(by_dir), args.window_sec, args.shift_sec, args.test_suffix, test_shift_sec, ) for dir_name in sorted(by_dir): output_path = args.output_dir / f"{dir_name.replace('/', '__')}.parquet" if output_path.exists() and not args.force: LOG.info("%s: index exists, skipping (use --force to rebuild)", dir_name) continue shift_sec = test_shift_sec if dir_name.endswith(args.test_suffix) else args.shift_sec LOG.info("%s: shift=%ss", dir_name, shift_sec) build_index_for_dir( fs=fs, dir_name=dir_name, fs_paths=by_dir[dir_name], output_path=output_path, window_sec=args.window_sec, shift_sec=shift_sec, workers=args.workers, ) if args.upload: LOG.info("Uploading %s -> %s/index/", args.output_dir, args.repo_id) HfApi().upload_folder( folder_path=str(args.output_dir), path_in_repo="index", repo_id=args.repo_id, repo_type="dataset", commit_message="feat: add per-directory window index parquets", ) LOG.info("Upload complete") if __name__ == "__main__": main()