Download scripts/prepare_release.py from StyleInstructCaps/StyleInstructCapsDB: direct link, hf CLI and curl.
- Browser
- Download file 8.84 kB
-
https://huggingface.co/datasets/StyleInstructCaps/StyleInstructCapsDB/resolve/ecf484b472d2d0d7571b8a527a5cdcd8dca88aae/scripts/prepare_release.py
- Command line
-
hf download hf://datasets/StyleInstructCaps/StyleInstructCapsDB@ecf484b472d2d0d7571b8a527a5cdcd8dca88aae/scripts/prepare_release.py
-
curl -L -o prepare_release.py https://huggingface.co/datasets/StyleInstructCaps/StyleInstructCapsDB/resolve/ecf484b472d2d0d7571b8a527a5cdcd8dca88aae/scripts/prepare_release.py
8.84 kB
| #!/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", | |
| } | |
| STYLE_CAPTION_FIELDS = { | |
| "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 | |
| 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 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]) | |
| 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() | |