File size: 9,524 Bytes
563ce83
 
 
 
8b2bea8
563ce83
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8b2bea8
 
 
 
 
 
 
 
563ce83
 
8b2bea8
 
 
 
 
 
 
563ce83
 
 
 
8b2bea8
563ce83
 
 
 
 
8b2bea8
563ce83
 
 
 
 
8b2bea8
563ce83
 
 
 
 
 
8b2bea8
563ce83
 
 
 
 
 
8b2bea8
563ce83
 
 
 
 
 
8b2bea8
563ce83
 
 
 
 
 
8b2bea8
563ce83
 
 
 
 
 
 
8b2bea8
 
 
 
 
 
 
563ce83
8b2bea8
 
563ce83
 
 
 
 
 
8b2bea8
563ce83
 
 
8b2bea8
 
 
563ce83
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8b2bea8
 
 
 
 
 
 
 
 
 
563ce83
 
 
 
 
 
 
 
 
 
 
 
 
8b2bea8
 
563ce83
 
 
 
8b2bea8
 
 
 
 
563ce83
8b2bea8
 
563ce83
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Convert source JSON manifests into Hugging Face release parquet files.

Reads source files under data/ (read-only), drops local absolute audio_path,
filters to release columns only, and writes parquet shards under release/data/<config>/.
"""

from __future__ import annotations

import argparse
import json
import sys
from pathlib import Path
from typing import Any, Iterator

import ijson
from datasets import Dataset
from tqdm import tqdm

PROJECT_ROOT = Path(__file__).resolve().parents[2]
RELEASE_ROOT = PROJECT_ROOT / "release"
DATA_ROOT = RELEASE_ROOT / "data"

ROWS_PER_SHARD = 100_000

# Hugging Face config names (directory names under release/data/).
CONFIG_STYLE_INSTRUCT_CAPS = "StyleInstructCaps"
CONFIG_STYLE_INSTRUCT_CAPS_METASET = "StyleInstructCaps-MetaSet"
CONFIG_IN_DOMAIN_BALANCED = "In_domain_balanced_set"
CONFIG_VCTK_SPEAKER_PROMPTS = "VCTK_speaker_prompts"
CONFIG_VCTK_UNSEEN_PROMPTS = "VCTK_unseen_prompts"
CONFIG_GIGASPEECH_SPEECHCRAFT = "Gigaspeech_SpeechCraft_captions"

# Expected row counts for verification.
EXPECTED_COUNTS = {
    (CONFIG_STYLE_INSTRUCT_CAPS, "train"): 1_031_840,
    (CONFIG_STYLE_INSTRUCT_CAPS, "eval"): 14_756,
    (CONFIG_VCTK_UNSEEN_PROMPTS, "test"): 32,
    (CONFIG_STYLE_INSTRUCT_CAPS_METASET, "test"): 434,
    (CONFIG_IN_DOMAIN_BALANCED, "test"): 400,
    (CONFIG_VCTK_SPEAKER_PROMPTS, "test"): 320,
    (CONFIG_GIGASPEECH_SPEECHCRAFT, "test"): 600,
}

RELEASE_SPECS: list[dict[str, Any]] = [
    {
        "config": CONFIG_STYLE_INSTRUCT_CAPS,
        "split": "train",
        "source": PROJECT_ROOT / "data/data/train_fullscale_with_desc_v2.json",
        "stream": True,
    },
    {
        "config": CONFIG_STYLE_INSTRUCT_CAPS,
        "split": "eval",
        "source": PROJECT_ROOT / "data/data/evaluation_holdout_with_desc_llama.json",
        "stream": False,
    },
    {
        "config": CONFIG_VCTK_UNSEEN_PROMPTS,
        "split": "test",
        "source": PROJECT_ROOT
        / "data/evaluation/data_input_dir/vctk_manifest_2utt_36prompts_unseen.json",
        "stream": False,
    },
    {
        "config": CONFIG_STYLE_INSTRUCT_CAPS_METASET,
        "split": "test",
        "source": PROJECT_ROOT
        / "data/evaluation/data_input_dir/tbd1_500_llama_global.json",
        "stream": False,
    },
    {
        "config": CONFIG_IN_DOMAIN_BALANCED,
        "split": "test",
        "source": PROJECT_ROOT
        / "data/evaluation/data_input_dir/balance_acccent_gender_eval_set2_with_fields.json",
        "stream": False,
    },
    {
        "config": CONFIG_VCTK_SPEAKER_PROMPTS,
        "split": "test",
        "source": PROJECT_ROOT
        / "data/evaluation/data_input_dir/vctk_manifest_10prompts.json",
        "stream": False,
    },
    {
        "config": CONFIG_GIGASPEECH_SPEECHCRAFT,
        "split": "test",
        "source": PROJECT_ROOT
        / "data/evaluation/data_input_dir/giga_manifest.json",
        "stream": False,
    },
]

BASE_FIELDS = {
    "source",
    "relative_audio_path",
    "transcription",
    "speakerid",
    "duration",
}

STYLE_CAPTION_FIELDS = {
    "text_description",
    "speaker_idiosyncratic_style",
    "situational_contextual_style",
    "expressive_emotional_style",
    "linguistic_pragmatic_style",
    "perceptual_listener_centric_style",
    "holistic_creative_synthesis",
    "ground_truth_caption",
    "captions",
}

STYLE_TEXT_FIELDS = STYLE_CAPTION_FIELDS - {"text_description"}

LIST_FIELDS = {"text_description"}


def _to_text(value: Any) -> str | None:
    if value is None:
        return None
    if isinstance(value, str):
        return value
    if isinstance(value, list):
        parts = [str(item) for item in value if item is not None]
        return " ".join(parts) if parts else None
    return str(value)


def _to_string_list(value: Any) -> list[str]:
    if value is None:
        return []
    if isinstance(value, str):
        return [value]
    if isinstance(value, list):
        return [str(item) for item in value if item is not None]
    return [str(value)]


def _to_float(value: Any) -> float | None:
    if value is None:
        return None
    return float(value)


def is_instruction_field(key: str) -> bool:
    return key.endswith("_instruction") or (
        key.startswith("prompt") and "_instruction" in key
    )


def is_release_field(key: str) -> bool:
    return key in BASE_FIELDS or key in STYLE_CAPTION_FIELDS or is_instruction_field(key)


def normalize_record(record: dict[str, Any]) -> dict[str, Any]:
    """Normalize heterogeneous JSON values to parquet-friendly types."""
    cleaned = dict(record)
    cleaned.pop("audio_path", None)

    for field in STYLE_TEXT_FIELDS:
        if field in cleaned:
            cleaned[field] = _to_text(cleaned[field])

    for field in LIST_FIELDS:
        if field in cleaned:
            cleaned[field] = _to_string_list(cleaned[field])

    if "duration" in cleaned:
        cleaned["duration"] = _to_float(cleaned["duration"])

    return cleaned


def filter_release_record(record: dict[str, Any]) -> dict[str, Any]:
    """Keep only base metadata plus style captions and instructions."""
    return {key: value for key, value in record.items() if is_release_field(key)}


def sanitize_record(record: dict[str, Any]) -> dict[str, Any]:
    """Normalize, drop audio_path, and filter to release columns."""
    return filter_release_record(normalize_record(record))


def iter_annotation_records(source_path: Path) -> Iterator[dict[str, Any]]:
    """Stream records from a large JSON file with an annotation array."""
    with source_path.open("rb") as handle:
        for record in ijson.items(handle, "annotation.item"):
            yield sanitize_record(record)


def load_annotation_records(source_path: Path) -> list[dict[str, Any]]:
    with source_path.open("r", encoding="utf-8") as handle:
        payload = json.load(handle)
    records = payload["annotation"]
    return [sanitize_record(record) for record in records]


def write_single_parquet(
    records: list[dict[str, Any]],
    output_dir: Path,
    split: str,
) -> int:
    output_dir.mkdir(parents=True, exist_ok=True)
    dataset = Dataset.from_list(records)
    output_path = output_dir / f"{split}-00000-of-00001.parquet"
    dataset.to_parquet(str(output_path))
    return len(records)


def write_sharded_parquet(
    record_iter: Iterator[dict[str, Any]],
    output_dir: Path,
    split: str,
    rows_per_shard: int,
) -> int:
    """Write parquet shards from a streaming iterator."""
    output_dir.mkdir(parents=True, exist_ok=True)

    total_rows = 0
    shard_rows: list[dict[str, Any]] = []
    shard_paths: list[Path] = []

    def flush_shard(rows: list[dict[str, Any]], index: int) -> None:
        if not rows:
            return
        path = output_dir / f"{split}-shard-{index:05d}.parquet"
        Dataset.from_list(rows).to_parquet(str(path))
        shard_paths.append(path)

    for record in tqdm(record_iter, desc=f"{output_dir.name}/{split}", unit="rows"):
        shard_rows.append(record)
        total_rows += 1
        if len(shard_rows) >= rows_per_shard:
            flush_shard(shard_rows, len(shard_paths))
            shard_rows = []

    if shard_rows:
        flush_shard(shard_rows, len(shard_paths))

    total_shards = len(shard_paths)
    for index, shard_path in enumerate(shard_paths):
        final_name = output_dir / f"{split}-{index:05d}-of-{total_shards:05d}.parquet"
        shard_path.rename(final_name)

    return total_rows


def process_spec(spec: dict[str, Any], rows_per_shard: int) -> tuple[str, str, int]:
    config = spec["config"]
    split = spec["split"]
    source: Path = spec["source"]
    output_dir = DATA_ROOT / config

    if not source.exists():
        raise FileNotFoundError(f"Missing source file: {source}")

    print(f"\nProcessing {config}/{split} from {source}")

    if spec.get("stream"):
        print(
            "  Streaming large file with ijson (~3.3 GB JSON). "
            "Recommend >=16 GB free RAM for parquet conversion."
        )
        row_count = write_sharded_parquet(
            iter_annotation_records(source),
            output_dir=output_dir,
            split=split,
            rows_per_shard=rows_per_shard,
        )
    else:
        records = load_annotation_records(source)
        row_count = write_single_parquet(records, output_dir=output_dir, split=split)

    expected = EXPECTED_COUNTS.get((config, split))
    if expected is not None and row_count != expected:
        print(
            f"  WARNING: row count mismatch for {config}/{split}: "
            f"got {row_count}, expected {expected}",
            file=sys.stderr,
        )
    else:
        print(f"  Wrote {row_count} rows to {output_dir}")

    return config, split, row_count


def main() -> None:
    parser = argparse.ArgumentParser(description="Prepare Hugging Face release parquet files.")
    parser.add_argument(
        "--rows-per-shard",
        type=int,
        default=ROWS_PER_SHARD,
        help="Rows per parquet shard for the large train split.",
    )
    args = parser.parse_args()

    print(f"Project root: {PROJECT_ROOT}")
    print(f"Release data dir: {DATA_ROOT}")

    summary: list[tuple[str, str, int]] = []
    for spec in RELEASE_SPECS:
        summary.append(process_spec(spec, rows_per_shard=args.rows_per_shard))

    print("\nSummary:")
    for config, split, count in summary:
        print(f"  {config}/{split}: {count:,} rows")


if __name__ == "__main__":
    main()