File size: 8,753 Bytes
dc1d281
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
prepare_data.py  —  Step 3: pull Igbo-English clips from AfriSwitch.

Runs in Google Colab. Streams the AfriSwitch dataset (does NOT download all
54h), saves N clips as .wav into audio/<language>/, and writes/append rows to
audio/ground_truth.csv with the true transcript for each clip.

Defensive by design: AfriSwitch's exact field names were not assumed. The
script prints the dataset's real schema first, then auto-detects the
transcript column from a list of likely names. If none match, it stops and
shows you the available columns so we fix ONE line instead of guessing.

Usage (in a Colab cell):
    !python prepare_data.py --language igbo --n 30

Config name / split handling is also auto-detected: AfriSwitch may expose
each language as a separate config, or as a column inside one dataset. Both
paths are tried.
"""

import argparse
import csv
import os
import re

import soundfile as sf
from datasets import (
    load_dataset,
    get_dataset_config_names,
    get_dataset_split_names,
)

DATASET_ID = "intronhealth/AfriSwitch"

# Likely names for the ground-truth transcript column, in priority order.
# The first one present in the dataset's features wins.
TRANSCRIPT_FIELD_CANDIDATES = [
    "transcript",
    "transcription",
    "text",
    "sentence",
    "target",
    "normalized_text",
]

# Likely names for the audio column.
AUDIO_FIELD_CANDIDATES = ["audio", "audio_file", "path", "file"]

# Map our simple --language values to whatever AfriSwitch might call them.
# We try each candidate as a config name; the first that loads wins.
LANGUAGE_ALIASES = {
    "igbo": ["igbo", "ig", "Igbo", "ibo"],
    "yoruba": ["yoruba", "yo", "Yoruba"],
    "hausa": ["hausa", "ha", "Hausa"],
    "pidgin": ["pidgin", "pcm", "Pidgin", "naija"],
}

REPO_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
AUDIO_DIR = os.path.join(REPO_ROOT, "audio")
GROUND_TRUTH_CSV = os.path.join(AUDIO_DIR, "ground_truth.csv")


def pick_split(config_name):
    """
    AfriSwitch has no 'train' split. Ask the dataset what splits it actually
    has and prefer test/validation/eval, else fall back to the first one.
    """
    try:
        splits = get_dataset_split_names(DATASET_ID, config_name)
    except Exception as e:  # noqa: BLE001
        print(f"[info] Could not list splits ({e}); defaulting to 'test'.")
        return "test"
    print(f"[info] Available splits for '{config_name}': {splits}")
    for preferred in ("test", "validation", "eval", "dev", "train"):
        if preferred in splits:
            return preferred
    return splits[0]


def detect_field(features, candidates, kind):
    """Return the first candidate present in the dataset features."""
    for name in candidates:
        if name in features:
            return name
    raise SystemExit(
        f"\n[STOP] Could not find the {kind} column.\n"
        f"Tried: {candidates}\n"
        f"Actual columns in this dataset: {list(features)}\n"
        f"Fix: add the correct name to the *_FIELD_CANDIDATES list at the top "
        f"of prepare_data.py and re-run."
    )


def load_language_stream(language):
    """
    Try to open a streaming split for the requested language.

    Strategy 1: language is its own config name (load_dataset(id, config)).
    Strategy 2: single dataset with a 'language' column we filter on.
    Returns (streaming_dataset, needs_language_filter, language_value_used).
    """
    aliases = LANGUAGE_ALIASES.get(language, [language])

    # What configs does this dataset actually expose?
    try:
        configs = get_dataset_config_names(DATASET_ID)
        print(f"[info] Available configs: {configs}")
    except Exception as e:  # noqa: BLE001
        configs = []
        print(f"[info] Could not list configs ({e}); will try default load.")

    # Strategy 1 — language as a config.
    for alias in aliases:
        if alias in configs:
            split = pick_split(alias)
            print(f"[info] Loading config '{alias}' split '{split}' (streaming)…")
            ds = load_dataset(DATASET_ID, alias, split=split, streaming=True)
            return ds, False, alias

    # Strategy 2 — default dataset, filter by a language column later.
    split = pick_split(None)
    print(f"[info] No per-language config matched; loading default split "
          f"'{split}' (streaming) and will filter by language column.")
    ds = load_dataset(DATASET_ID, split=split, streaming=True)
    return ds, True, aliases[0]


def extract_audio(audio):
    """
    Return (samples_ndarray, sampling_rate) from whatever the datasets library
    hands us. Handles two formats:
      - classic HF Audio feature: {"array": np.ndarray, "sampling_rate": int}
      - newer torchcodec AudioDecoder object (datasets >= 3.x with torchcodec)
    """
    import numpy as np

    # Classic dict format.
    if isinstance(audio, dict) and "array" in audio:
        return np.asarray(audio["array"]), int(audio["sampling_rate"])

    # torchcodec AudioDecoder — decode all samples to a tensor.
    if hasattr(audio, "get_all_samples"):
        samples = audio.get_all_samples()
        data = samples.data  # torch tensor, shape [channels, num_samples]
        arr = data.numpy() if hasattr(data, "numpy") else np.asarray(data)
        if arr.ndim == 2:
            arr = arr.T  # soundfile wants [num_samples, channels]
        return arr, int(samples.sample_rate)

    raise SystemExit(
        f"[STOP] Don't know how to read audio object of type {type(audio)}. "
        f"Attributes: {dir(audio)[:20]}"
    )


def slugify(value, fallback):
    value = re.sub(r"[^a-zA-Z0-9._-]", "_", str(value)).strip("_")
    return value or fallback


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--language", default="igbo",
                        choices=list(LANGUAGE_ALIASES))
    parser.add_argument("--n", type=int, default=30,
                        help="number of clips to pull")
    args = parser.parse_args()

    out_dir = os.path.join(AUDIO_DIR, args.language)
    os.makedirs(out_dir, exist_ok=True)

    ds, needs_filter, lang_value = load_language_stream(args.language)

    # Peek the first example to learn the schema before committing.
    first = next(iter(ds))
    print(f"\n[schema] Columns: {list(first.keys())}")
    audio_field = detect_field(first, AUDIO_FIELD_CANDIDATES, "audio")
    text_field = detect_field(first, TRANSCRIPT_FIELD_CANDIDATES, "transcript")
    lang_field = None
    if needs_filter:
        for cand in ("language", "lang", "locale"):
            if cand in first:
                lang_field = cand
                break
        if lang_field is None:
            raise SystemExit(
                f"[STOP] Need to filter by language but found no language "
                f"column. Columns: {list(first.keys())}"
            )
        print(f"[info] Filtering on '{lang_field}' == '{lang_value}'")

    print(f"[info] audio column  = '{audio_field}'")
    print(f"[info] text column   = '{text_field}'")

    # Re-open the stream so we start from the top (we consumed one above).
    ds, _, _ = load_language_stream(args.language)

    rows = []
    saved = 0
    scanned = 0
    for ex in ds:
        scanned += 1
        if needs_filter and str(ex.get(lang_field, "")).lower() != lang_value.lower():
            continue

        array, sr = extract_audio(ex[audio_field])

        clip_id = f"{args.language}_{saved:03d}"
        wav_path = os.path.join(out_dir, f"{clip_id}.wav")
        sf.write(wav_path, array, sr)

        transcript = str(ex[text_field]).strip()
        rows.append((clip_id, args.language, transcript))
        saved += 1
        print(f"  [{saved}/{args.n}] {clip_id}.wav  ← \"{transcript[:50]}…\"")

        if saved >= args.n:
            break

    # Write/refresh ground_truth.csv (header + all rows for this language).
    # Preserve any existing rows for OTHER languages.
    existing = []
    if os.path.exists(GROUND_TRUTH_CSV):
        with open(GROUND_TRUTH_CSV, newline="", encoding="utf-8") as f:
            reader = csv.reader(f)
            header = next(reader, None)
            for r in reader:
                if len(r) >= 3 and r[1] != args.language:
                    existing.append(tuple(r[:3]))

    with open(GROUND_TRUTH_CSV, "w", newline="", encoding="utf-8") as f:
        writer = csv.writer(f)
        writer.writerow(["clip_id", "language", "transcript"])
        writer.writerows(existing)
        writer.writerows(rows)

    print(f"\n[done] Saved {saved} clips to {out_dir}")
    print(f"[done] Wrote {len(rows)} rows for '{args.language}' to {GROUND_TRUTH_CSV}")
    print(f"[note] Scanned {scanned} dataset examples to collect them.")


if __name__ == "__main__":
    main()