File size: 8,416 Bytes
82efbf8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/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/<repo>/<dir>/<file>.parquet
    row_group     int32           parquet row-group ordinal inside source_path
    row_in_group  int32           row ordinal inside that row group
    valid_offsets list<float64>   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 <repo>/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()