#!/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, and writes parquet shards under release/data//. """ 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 # Expected row counts for verification. EXPECTED_COUNTS = { ("StyleInstructCaps", "train"): 1_031_840, ("StyleInstructCaps", "eval"): 14_756, ("OODPrompts", "test"): 32, ("MetaSet", "test"): 434, ("IDBalanced", "test"): 400, ("UDVCTK", "test"): 320, ("UnseenEval", "test"): 600, } RELEASE_SPECS: list[dict[str, Any]] = [ { "config": "StyleInstructCaps", "split": "train", "source": PROJECT_ROOT / "data/data/train_fullscale_with_desc_v2.json", "stream": True, }, { "config": "StyleInstructCaps", "split": "eval", "source": PROJECT_ROOT / "data/data/evaluation_holdout_with_desc_llama.json", "stream": False, }, { "config": "OODPrompts", "split": "test", "source": PROJECT_ROOT / "data/evaluation/data_input_dir/vctk_manifest_2utt_36prompts_unseen.json", "stream": False, }, { "config": "MetaSet", "split": "test", "source": PROJECT_ROOT / "data/evaluation/data_input_dir/tbd1_500_llama_global.json", "stream": False, }, { "config": "IDBalanced", "split": "test", "source": PROJECT_ROOT / "data/evaluation/data_input_dir/balance_acccent_gender_eval_set2_with_fields.json", "stream": False, }, { "config": "UDVCTK", "split": "test", "source": PROJECT_ROOT / "data/evaluation/data_input_dir/vctk_manifest_10prompts.json", "stream": False, }, { "config": "UnseenEval", "split": "test", "source": PROJECT_ROOT / "data/evaluation/data_input_dir/giga_manifest.json", "stream": False, }, ] STYLE_TEXT_FIELDS = { "speaker_idiosyncratic_style", "situational_contextual_style", "expressive_emotional_style", "linguistic_pragmatic_style", "perceptual_listener_centric_style", "holistic_creative_synthesis", "captions", } LIST_FIELDS = { "text_description", "intrinsic_tags", "situational_tags", "basic_tags", "all_tags", } 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)] FLOAT_FIELDS = { "duration", "snr", "utterance_pitch_mean", } def _to_float(value: Any) -> float | None: if value is None: return None return float(value) 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 "accent" in cleaned and cleaned["accent"] is None: cleaned["accent"] = "" for field in FLOAT_FIELDS: if field in cleaned: cleaned[field] = _to_float(cleaned[field]) return cleaned def sanitize_record(record: dict[str, Any]) -> dict[str, Any]: """Drop local absolute audio_path and normalize field types.""" return 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()