|
| 1 | +""" |
| 2 | +Dataset loading and canonicalisation utilities. |
| 3 | +
|
| 4 | +This module implements the dataset materialisation pipeline |
| 5 | +used by the public entrypoint `get_dataset`. |
| 6 | +
|
| 7 | +Responsibilities include: |
| 8 | +
|
| 9 | +- Resolving symbolic revisions (branches/tags) to commit SHAs. |
| 10 | +- Loading splits from Hugging Face via `datasets.load_dataset`. |
| 11 | +- Canonicalising dataset schemas into a uniform |
| 12 | + (system, question, answer) format. |
| 13 | +- Validating dataset structure. |
| 14 | +- Constructing a split-aware `VoiceDataset` instance. |
| 15 | +""" |
| 16 | + |
| 17 | +from __future__ import annotations |
| 18 | + |
| 19 | +from datasets import Dataset, load_dataset |
| 20 | +from huggingface_hub import HfApi |
| 21 | +from huggingface_hub.utils import HfHubHTTPError |
| 22 | + |
| 23 | +from voice.datasets._schema import Split |
| 24 | +from voice.datasets.dataset import ( |
| 25 | + DatasetSpec, |
| 26 | + VoiceDataset, |
| 27 | + _PinnedDatasetSpec, |
| 28 | +) |
| 29 | + |
| 30 | +# ----------------------------------------------------------------------------- |
| 31 | +# Utilities (revision resolution, schema canonicalisation .etc) |
| 32 | +# ----------------------------------------------------------------------------- |
| 33 | + |
| 34 | + |
| 35 | +def _resolve_revision(repo_id: str, revision: str) -> str: |
| 36 | + """ |
| 37 | + Resolve a symbolic revision (branch or tag) to a commit SHA. |
| 38 | +
|
| 39 | + :param repo_id: Hugging Face dataset repository id |
| 40 | + :param revision: Branch name, tag, or commit hash |
| 41 | + :return: Commit SHA corresponding to the revision |
| 42 | + :raises RuntimeError: If dataset or revision does not exist |
| 43 | + """ |
| 44 | + api = HfApi() |
| 45 | + |
| 46 | + try: |
| 47 | + info = api.dataset_info(repo_id=repo_id, revision=revision) |
| 48 | + except HfHubHTTPError as e: |
| 49 | + raise RuntimeError( |
| 50 | + f"Failed to resolve revision '{revision}' for dataset '{repo_id}'." |
| 51 | + ) from e |
| 52 | + |
| 53 | + return str(info.sha) |
| 54 | + |
| 55 | + |
| 56 | +def _extract_chat_style( |
| 57 | + column: dict[str, list[dict[str, str]]], |
| 58 | +) -> dict[str, str]: |
| 59 | + """ |
| 60 | + Extract (system, question, answer) dict from chat style example. |
| 61 | +
|
| 62 | + :param column: column containing chat-style messages |
| 63 | + :return: canonical dict |
| 64 | + """ |
| 65 | + messages = column["messages"] |
| 66 | + |
| 67 | + system = "" |
| 68 | + question = "" |
| 69 | + answer = "" |
| 70 | + |
| 71 | + for msg in messages: |
| 72 | + role = msg.get("role") |
| 73 | + content = msg.get("content", "") |
| 74 | + |
| 75 | + if role == "system": |
| 76 | + system = content |
| 77 | + elif role == "user": |
| 78 | + question = content |
| 79 | + elif role == "assistant": |
| 80 | + answer = content |
| 81 | + |
| 82 | + return { |
| 83 | + "system": system, |
| 84 | + "question": question, |
| 85 | + "answer": answer, |
| 86 | + } |
| 87 | + |
| 88 | + |
| 89 | +def _canonicalise_dataset(ds: Dataset) -> Dataset: |
| 90 | + """ |
| 91 | + Convert a HF dataset into canonical (system, question, answer) format. |
| 92 | +
|
| 93 | + Currently supported schemas: |
| 94 | + - Already canonical: columns {system, question, answer} |
| 95 | + - Chat style: column 'messages' with list[{role, content}] |
| 96 | +
|
| 97 | + :param ds: Raw Hugging Face dataset |
| 98 | + :return: Canonicalised QA dataset |
| 99 | + :raises NotImplementedError: If schema not recognised |
| 100 | + """ |
| 101 | + cols = set(ds.column_names) |
| 102 | + |
| 103 | + if {"system", "question", "answer"}.issubset(cols): |
| 104 | + return ds |
| 105 | + |
| 106 | + if "messages" in cols and len(cols) == 1: |
| 107 | + return ds.map( |
| 108 | + _extract_chat_style, |
| 109 | + remove_columns=ds.column_names, |
| 110 | + ) |
| 111 | + |
| 112 | + raise NotImplementedError( |
| 113 | + f"Unsupported dataset schema. Columns found: {sorted(cols)}" |
| 114 | + ) |
| 115 | + |
| 116 | + |
| 117 | +def _validate_canonical(ds: Dataset) -> None: |
| 118 | + """ |
| 119 | + Ensure dataset contains required canonical columns. |
| 120 | +
|
| 121 | + :param ds: Canonicalised dataset |
| 122 | + :return: None |
| 123 | + :raises ValueError: If required columns missing |
| 124 | + """ |
| 125 | + required = {"system", "question", "answer"} |
| 126 | + missing = required - set(ds.column_names) |
| 127 | + if not required.issubset(ds.column_names): |
| 128 | + raise ValueError(f"Missing required columns: {sorted(missing)}") |
| 129 | + |
| 130 | + |
| 131 | +# ----------------------------------------------------------------------------- |
| 132 | +# Public API |
| 133 | +# ----------------------------------------------------------------------------- |
| 134 | + |
| 135 | + |
| 136 | +def get_dataset(spec: DatasetSpec) -> VoiceDataset: |
| 137 | + """ |
| 138 | + Materialise a Hugging Face dataset as a VoiceDataset. |
| 139 | +
|
| 140 | + Steps: |
| 141 | + 1. Resolve DatasetSpec to _PinnedDatasetSpec. |
| 142 | + 2. Load requested splits from Hugging Face. |
| 143 | + 3. Canonicalise each split into (system, question, answer). |
| 144 | + 4. Validate canonical structure. |
| 145 | + 5. Construct VoiceDataset. |
| 146 | +
|
| 147 | + :param spec: Dataset specification |
| 148 | + :return: Split-aware VoiceDataset |
| 149 | + :raises RuntimeError: If a split cannot be loaded |
| 150 | + """ |
| 151 | + # Resolve dataset revision |
| 152 | + pinned: _PinnedDatasetSpec = spec._pin(_resolve_revision) |
| 153 | + |
| 154 | + # Load dataset splits |
| 155 | + datasets: dict[Split, Dataset] = {} |
| 156 | + |
| 157 | + for split in pinned.splits: |
| 158 | + try: |
| 159 | + ds = load_dataset( |
| 160 | + pinned.repo_id, |
| 161 | + split=split.value, |
| 162 | + revision=pinned.revision, |
| 163 | + ) |
| 164 | + except Exception as e: |
| 165 | + raise RuntimeError( |
| 166 | + f"Failed to load split '{split.value}' " |
| 167 | + f"from {pinned.repo_id}@{pinned.revision}" |
| 168 | + ) from e |
| 169 | + |
| 170 | + # Canonicalise and validate dataset |
| 171 | + ds = _canonicalise_dataset(ds) |
| 172 | + |
| 173 | + _validate_canonical(ds) |
| 174 | + |
| 175 | + datasets[split] = ds |
| 176 | + |
| 177 | + # Build VoiceDataset object |
| 178 | + return VoiceDataset( |
| 179 | + datasets=datasets, |
| 180 | + spec=pinned, |
| 181 | + ) |
0 commit comments