File size: 25,521 Bytes
a1fe2e2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
"""Build and check manifests.

    vitakws-data add-dir  --dir recordings/hey_vita --label hey_vita --source human \\
                          --meta-csv recordings/speakers.csv --out data/human.jsonl
    vitakws-data import-fish --metadata /data/fish/metadata.jsonl --audio-out data/fish/audio \\
                          --out data/fish/manifest.jsonl
    vitakws-data add-carriers --manifest data/fish/manifest.jsonl --carriers /data/cmd/metadata.jsonl \\
                          --audio-out data/fish/audio_cmd --out data/fish/with_commands.jsonl
    vitakws-data merge    --inputs data/human.jsonl data/tts.jsonl --out data/all.jsonl
    vitakws-data split    --manifest data/all.jsonl --out data/manifest.jsonl --holdout-sources human
    vitakws-data validate --manifest data/manifest.jsonl --check-audio
    vitakws-data stats    --manifest data/manifest.jsonl
"""

from __future__ import annotations

import argparse
import csv
import hashlib
import json
import sys
from collections import Counter, defaultdict
from pathlib import Path

import numpy as np

from vitakws.data import audio
from vitakws.data.manifest import (
    KEYWORD_KIND,
    NEGATIVE_KINDS,
    SPLITS,
    Item,
    read_manifest,
    summarize,
    write_manifest,
)

META_COLUMNS = ("speaker", "gender", "region", "env", "text", "source")
REGIONS = ("north", "north_central", "central", "south", "unknown")
GENDERS = ("f", "m", "unknown")

# ViMD metadata carried by the Fish S2 generator: gender 0/1 and three regions.
# ViMD files Thanh Hoa, Nghe An and Ha Tinh under "Central"; this repo keeps
# them apart as north_central (docs/03_dataset.md section 3).
VIMD_GENDERS = {0: "f", 1: "m"}
VIMD_REGIONS = {"north": "north", "central": "central", "south": "south"}
VIMD_NORTH_CENTRAL = ("thanhhoa", "nghean", "hatinh")
FISH_SR = 16000


def read_meta_csv(path: Path) -> tuple[dict[str, dict], dict[str, dict]]:
    """Per-file rows (keyed by the ``file`` column) and per-speaker rows (keyed by ``speaker``).

    A row with a ``file`` value describes that file. A row without one describes
    a speaker and applies to every file of that speaker.
    """
    by_file, by_speaker = {}, {}
    with path.open(encoding="utf-8-sig", newline="") as f:
        for row in csv.DictReader(f):
            row = {k.strip(): (v or "").strip() for k, v in row.items() if k}
            if row.get("file"):
                by_file[row["file"]] = row
            elif row.get("speaker"):
                by_speaker[row["speaker"]] = row
    return by_file, by_speaker


def cmd_add_dir(args: argparse.Namespace) -> int:
    root = Path(args.dir)
    files = audio.list_audio(root)
    if not files:
        print(f"no audio files under {root}", file=sys.stderr)
        return 1
    by_file, by_speaker = read_meta_csv(Path(args.meta_csv)) if args.meta_csv else ({}, {})
    items, skipped = [], Counter()
    for path in files:
        try:
            sr, frames = audio.info(path)
        except Exception as e:  # unreadable or unsupported file
            skipped[f"unreadable ({type(e).__name__})"] += 1
            continue
        duration = frames / sr
        if duration < args.min_duration:
            skipped["too short"] += 1
            continue
        if args.max_duration and duration > args.max_duration:
            skipped["too long"] += 1
            continue
        rel = str(path.relative_to(root)) if root.is_dir() else path.name
        row = by_file.get(rel) or by_file.get(path.name) or {}
        if args.speaker_from == "parent":
            speaker = path.parent.name
        elif args.speaker_from == "prefix":
            speaker = path.stem.split("_")[0]
        else:
            speaker = path.stem  # every file its own speaker
        speaker = row.get("speaker") or speaker
        row = {**by_speaker.get(speaker, {}), **{k: v for k, v in row.items() if v}}
        item = Item(
            audio=str(path.resolve()),
            label=args.label,
            split=args.split,
            speaker=f"{args.speaker_prefix}{speaker}",
            gender=row.get("gender") or args.gender,
            region=row.get("region") or args.region,
            source=row.get("source") or args.source,
            env=row.get("env") or args.env,
            text=row.get("text") or args.text,
            duration=round(duration, 4),
        )
        for key in ("kw_start", "kw_end"):
            if row.get(key):
                setattr(item, key, float(row[key]))
        item.extra = {
            k: v
            for k, v in row.items()
            if v and k not in (*META_COLUMNS, "file", "kw_start", "kw_end")
        }
        items.append(item)
    out = Path(args.out)
    if args.append and out.exists():
        items = read_manifest(out) + items
    write_manifest(out, items)
    print(f"{len(files)} files found, {sum(skipped.values())} skipped {dict(skipped)}")
    print(f"{out} now has {len(items)} items")
    return 0


def fish_item(record: dict, base: Path, args: argparse.Namespace) -> tuple[Item | None, str]:
    """One Fish S2 metadata record -> (manifest item, "") or (None, reason it was dropped)."""
    clip, ref = record["audio"], record.get("reference", {})
    src = Path(clip["path"])
    if not src.exists():
        src = base / clip["relative_path"]
    try:
        wave = audio.load(src, FISH_SR)
    except Exception as e:  # missing or unreadable file
        return None, f"unreadable ({type(e).__name__})"
    label = record.get("label", "positive")
    label = args.keyword_label if label == "positive" else label
    is_keyword = label not in NEGATIVE_KINDS
    start, end = audio.active_region(wave, FISH_SR)
    speech = (end - start) / FISH_SR
    # Negatives such as a bare "hey" are legitimately shorter than any wake phrase.
    if speech < (args.min_speech if is_keyword else args.min_negative_speech):
        return None, "speech too short"
    # A keyword longer than the training window almost always carries extra words.
    if is_keyword and args.max_speech and speech > args.max_speech:
        return None, "speech too long"
    # The TTS sometimes runs on until its length limit; such clips are not the planned text.
    if not is_keyword and args.max_negative_speech and speech > args.max_negative_speech:
        return None, "negative too long"

    path = src
    if args.audio_out:
        path = Path(args.audio_out) / record.get("dataset_id", "fish") / src.name
        audio.save(path, wave, FISH_SR)
    province = str(ref.get("province_name") or "")
    region = VIMD_REGIONS.get(str(ref.get("region") or "").lower(), "unknown")
    if province.lower() in VIMD_NORTH_CENTRAL:
        region = "north_central"
    speaker = record["speaker_id"]
    item = Item(
        audio=str(path.resolve()),
        label=label,
        speaker=f"{args.speaker_prefix}{speaker}",
        gender=VIMD_GENDERS.get(ref.get("gender"), "unknown"),
        region=region,
        source=f"tts:{record.get('model', {}).get('id', 'fish')}:{speaker}",
        env=args.env,
        text=record.get("text_wakeupword") or record.get("text") or "",
        duration=round(len(wave) / FISH_SR, 4),
    )
    if is_keyword:
        item.kw_start, item.kw_end = round(start / FISH_SR, 4), round(end / FISH_SR, 4)
    extra = {
        "province": province,
        "style": record.get("style_prompt"),
        "phrase_index": record.get("phrase_index"),
        "style_index": record.get("style_index"),
        "dataset_id": record.get("dataset_id"),
        "sample_id": record.get("sample_id"),
    }
    item.extra = {k: v for k, v in extra.items() if v not in (None, "")}
    return item, ""


def cmd_import_fish(args: argparse.Namespace) -> int:
    items, skipped, total = [], Counter(), 0
    for meta in map(Path, args.metadata):
        with meta.open(encoding="utf-8") as f:
            for line in f:
                if not line.strip():
                    continue
                total += 1
                item, reason = fish_item(json.loads(line), meta.parent, args)
                if item is None:
                    skipped[reason] += 1
                else:
                    items.append(item)
    out = Path(args.out)
    if args.append and out.exists():
        items = read_manifest(out) + items
    write_manifest(out, items)
    print(f"{total} records read, {sum(skipped.values())} skipped {dict(skipped)}")
    print(f"{out} now has {len(items)} items")
    return 0


def cmd_add_carriers(args: argparse.Namespace) -> int:
    """Join a spoken command after half of each voice's keyword clips.

    A driver says the command straight after the wake phrase, so the detector
    must fire while speech continues. Commands come from the Fish S2 generator
    (label "carrier") and are only joined to keyword clips of the same voice and
    style. The keyword boundaries stay where they were.
    """
    rng = np.random.default_rng(args.seed)
    commands: dict[tuple[str, str], list[tuple[np.ndarray, str]]] = defaultdict(list)
    skipped = Counter()
    for meta in map(Path, args.carriers):
        with meta.open(encoding="utf-8") as f:
            for line in f:
                if not line.strip():
                    continue
                record = json.loads(line)
                if record.get("label") != "carrier":
                    continue
                src = Path(record["audio"]["path"])
                if not src.exists():
                    src = meta.parent / record["audio"]["relative_path"]
                wave = audio.load(src, FISH_SR)
                start, end = audio.active_region(wave, FISH_SR)
                if not 0.2 <= (end - start) / FISH_SR <= args.max_command:
                    skipped["command length"] += 1
                    continue
                key = (
                    f"{args.speaker_prefix}{record['speaker_id']}",
                    record.get("style_prompt", ""),
                )
                commands[key].append((wave[start:end], record.get("text", "")))

    items = read_manifest(args.manifest)
    groups: dict[tuple[str, str], list[int]] = defaultdict(list)
    for n, item in enumerate(items):
        if item.kind == KEYWORD_KIND and item.kw_end is not None:
            groups[(item.speaker, item.extra.get("style", ""))].append(n)
    joined = 0
    for key, tails in sorted(commands.items()):
        members = groups.get(key, [])
        if not members:
            skipped["no keyword clip for this voice and style"] += len(tails)
            continue
        chosen = rng.permutation(members)[: (len(members) + 1) // 2]
        for k, n in enumerate(chosen):
            item = items[int(n)]
            tail, text = tails[k % len(tails)]
            head = audio.load(item.audio, FISH_SR)[: int(round(item.kw_end * FISH_SR))]
            gap = np.zeros(int(rng.uniform(*args.gap) * FISH_SR), np.float32)
            wave = np.concatenate([head, gap, tail])
            path = Path(args.audio_out) / f"{Path(item.audio).stem}_cmd.wav"
            audio.save(path, wave, FISH_SR)
            item.audio = str(path.resolve())
            item.text = f"{item.text} {text}".strip()
            item.duration = round(len(wave) / FISH_SR, 4)
            item.extra["command"] = text
            joined += 1
    write_manifest(args.out, items)
    keywords = sum(len(v) for v in groups.values())
    print(f"{joined} of {keywords} keyword clips now end in a command; skipped {dict(skipped)}")
    print(f"{args.out}: {len(items)} items")
    return 0


def cmd_merge(args: argparse.Namespace) -> int:
    items, seen = [], set()
    for path in args.inputs:
        for item in read_manifest(path):
            if item.audio in seen:
                continue
            seen.add(item.audio)
            items.append(item)
    write_manifest(args.out, items)
    print(f"{args.out}: {len(items)} items from {len(args.inputs)} manifests")
    return 0


def stable_hash(text: str, seed: int) -> float:
    digest = hashlib.sha256(f"{seed}:{text}".encode()).digest()
    return int.from_bytes(digest[:8], "big") / 2**64


def assign_splits(
    items: list[Item], dev: float, test: float, seed: int, holdout_sources: list[str]
) -> dict[str, str]:
    """Speaker -> split, spread evenly over (source type, region, gender).

    Speakers are ordered by a hash of their id, so the assignment is stable when
    data is added later. With ``holdout_sources`` only speakers from those
    sources (e.g. "human") may land in dev/test; the rest all train. Mined clips
    keep the speaker they came from and do not affect where that speaker goes.
    """
    profile: dict[str, tuple] = {}
    sources: dict[str, set[str]] = defaultdict(set)
    for item in items:
        sources[item.speaker]  # every speaker gets an entry, even mined-only ones
        if item.source_type == "mined":
            continue
        profile.setdefault(item.speaker, (item.source_type, item.region, item.gender))
        sources[item.speaker].add(item.source_type)
    eligible = {
        speaker: speaker in profile and (not holdout_sources or kinds <= set(holdout_sources))
        for speaker, kinds in sources.items()
    }

    strata: dict[tuple, list[str]] = defaultdict(list)
    for speaker, key in profile.items():
        if eligible[speaker]:
            strata[key].append(speaker)
    speaker_split = {speaker: "train" for speaker in eligible}
    # Carry the fractional remainder from one stratum to the next, so small
    # strata still contribute and the overall shares come out right.
    owed_test = owed_dev = 0.0
    for key in sorted(strata):
        pool = sorted(strata[key], key=lambda s: stable_hash(s, seed))
        owed_test += len(pool) * test
        owed_dev += len(pool) * dev
        n_test = min(int(owed_test), len(pool))
        n_dev = min(int(owed_dev), len(pool) - n_test)
        owed_test -= n_test
        owed_dev -= n_dev
        for i, speaker in enumerate(pool):
            if i < n_test:
                speaker_split[speaker] = "test"
            elif i < n_test + n_dev:
                speaker_split[speaker] = "dev"
    return speaker_split


def cmd_split(args: argparse.Namespace) -> int:
    items = read_manifest(args.manifest)
    mapping = assign_splits(items, args.dev, args.test, args.seed, args.holdout_sources)
    for item in items:
        item.split = mapping[item.speaker]
    write_manifest(args.out, items)
    counts = Counter(mapping.values())
    print(f"{len(mapping)} speakers -> {dict(counts)}")
    print_stats(items)
    return 0


def check_items(
    items: list[Item], classes: list[str] | None, check_audio: bool
) -> tuple[list, list]:
    errors, warnings = [], []
    speaker_splits: dict[str, set[str]] = defaultdict(set)
    seen_audio = set()
    for n, item in enumerate(items, 1):
        where = f"line {n} ({Path(item.audio).name})"
        if item.split not in SPLITS:
            errors.append(f"{where}: split {item.split!r} is not one of {SPLITS}")
        if classes and item.kind == KEYWORD_KIND and item.label not in classes:
            errors.append(
                f"{where}: label {item.label!r} is not a class {classes} or a negative kind"
            )
        if item.region not in REGIONS:
            warnings.append(f"{where}: region {item.region!r} is not one of {REGIONS}")
        if item.gender not in GENDERS:
            warnings.append(f"{where}: gender {item.gender!r} is not one of {GENDERS}")
        if item.audio in seen_audio:
            errors.append(f"{where}: duplicate audio path")
        seen_audio.add(item.audio)
        speaker_splits[item.speaker].add(item.split)
        if not Path(item.audio).is_file():
            errors.append(f"{where}: file not found")
            continue
        try:
            sr, frames = audio.info(item.audio)
        except Exception as e:
            errors.append(f"{where}: cannot read header ({e})")
            continue
        duration = frames / sr
        if duration <= 0:
            errors.append(f"{where}: empty audio")
        if sr < 16000:
            warnings.append(f"{where}: sample rate {sr} Hz is below 16 kHz")
        if item.kw_end is not None and item.kw_end > duration + 0.05:
            errors.append(f"{where}: kw_end {item.kw_end} is past the end ({duration:.2f}s)")
        if item.kw_start is not None and item.kw_end is not None and item.kw_start >= item.kw_end:
            errors.append(f"{where}: kw_start is not before kw_end")
        if item.kind == KEYWORD_KIND and item.kw_end is None and duration > 2.5:
            warnings.append(
                f"{where}: keyword clip is {duration:.1f}s long with no kw_end; "
                "the keyword is assumed to end at the end of the file"
            )
        if check_audio:
            wave = audio.load(item.audio, 16000)
            if not len(wave):
                errors.append(f"{where}: decodes to zero samples")
                continue
            peak = float(np.abs(wave).max())
            if (np.abs(wave) >= 0.999).mean() > 0.001:
                warnings.append(f"{where}: clipped (more than 0.1% of samples at full scale)")
            if item.kind != "background" and audio.db(peak) < -40:
                warnings.append(f"{where}: very quiet (peak {audio.db(peak):.0f} dBFS)")
    for speaker, splits in sorted(speaker_splits.items()):
        if len(splits) > 1:
            errors.append(f"speaker {speaker!r} appears in several splits: {sorted(splits)}")
    return errors, warnings


def cmd_validate(args: argparse.Namespace) -> int:
    items = read_manifest(args.manifest)
    errors, warnings = check_items(items, args.classes, args.check_audio)
    for line in warnings[: args.max_messages]:
        print(f"warning: {line}")
    for line in errors[: args.max_messages]:
        print(f"error: {line}")
    hidden = max(0, len(warnings) - args.max_messages) + max(0, len(errors) - args.max_messages)
    if hidden:
        print(f"... {hidden} more messages not shown (raise --max-messages)")
    print(f"{len(items)} items: {len(errors)} errors, {len(warnings)} warnings")
    return 1 if errors else 0


def print_table(title: str, rows: dict[str, Counter], columns: list[str]) -> None:
    print(f"\n{title}")
    width = max([len(r) for r in rows] + [5])
    print(f"{'':{width}} " + " ".join(f"{c:>14}" for c in columns) + f" {'total':>8}")
    for name, counts in sorted(rows.items()):
        cells = " ".join(f"{counts.get(c, 0):>14}" for c in columns)
        print(f"{name:{width}} {cells} {sum(counts.values()):>8}")


def print_stats(items: list[Item]) -> None:
    summary = summarize(items)
    print(
        f"\n{summary['total']} clips, {summary['hours']:.2f} hours, {summary['speakers']} speakers"
    )
    by_split: dict[str, Counter] = defaultdict(Counter)
    for item in items:
        by_split[item.label][item.split] += 1
    print_table("Clips per label and split", by_split, list(SPLITS))

    hours: dict[str, Counter] = defaultdict(Counter)
    for item in items:
        hours[item.label][item.split] += item.duration / 3600.0
    print("\nHours per label and split")
    for label, counts in sorted(hours.items()):
        print(f"  {label:18} " + "  ".join(f"{s} {counts.get(s, 0.0):7.2f}" for s in SPLITS))

    positives = [i for i in items if i.kind == KEYWORD_KIND]
    if positives:
        clips: dict[str, Counter] = defaultdict(Counter)
        speakers: dict[str, dict[str, set]] = defaultdict(lambda: defaultdict(set))
        for item in positives:
            clips[item.region][item.gender] += 1
            speakers[item.region][item.gender].add(item.speaker)
        print_table("Keyword clips: region x gender", clips, list(GENDERS))
        print_table(
            "Keyword speakers: region x gender",
            {r: Counter({g: len(s) for g, s in v.items()}) for r, v in speakers.items()},
            list(GENDERS),
        )
        source: dict[str, Counter] = defaultdict(Counter)
        for item in positives:
            source[item.source_type][item.split] += 1
        print_table("Keyword clips: source x split", source, list(SPLITS))
    negatives = Counter(i.label for i in items if i.label in NEGATIVE_KINDS)
    if negatives:
        print("\nNegative clips:", dict(negatives))


def cmd_stats(args: argparse.Namespace) -> int:
    print_stats(read_manifest(args.manifest))
    return 0


def build_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(
        description=__doc__, formatter_class=argparse.RawTextHelpFormatter
    )
    sub = parser.add_subparsers(dest="command", required=True)

    p = sub.add_parser("add-dir", help="scan a folder of audio into a manifest")
    p.add_argument("--dir", required=True)
    p.add_argument(
        "--label", required=True, help=f"keyword id, or one of {', '.join(NEGATIVE_KINDS)}"
    )
    p.add_argument("--out", required=True)
    p.add_argument("--append", action="store_true", help="add to --out instead of replacing it")
    p.add_argument("--meta-csv", help="CSV with a 'file' and/or 'speaker' column plus metadata")
    p.add_argument(
        "--speaker-from",
        choices=("parent", "prefix", "file"),
        default="parent",
        help="speaker id from the parent folder, the file-name prefix before '_', "
        "or one speaker per file",
    )
    p.add_argument(
        "--speaker-prefix", default="", help="prepended to speaker ids to keep corpora apart"
    )
    p.add_argument("--source", default="human")
    p.add_argument("--region", default="unknown", choices=REGIONS)
    p.add_argument("--gender", default="unknown", choices=GENDERS)
    p.add_argument("--env", default="unknown")
    p.add_argument("--text", default="")
    p.add_argument("--split", default="train", choices=SPLITS)
    p.add_argument("--min-duration", type=float, default=0.3)
    p.add_argument("--max-duration", type=float, default=0.0, help="0 disables the limit")
    p.set_defaults(func=cmd_add_dir)

    p = sub.add_parser(
        "import-fish", help="convert Fish S2 generator metadata.jsonl files into a manifest"
    )
    p.add_argument("--metadata", nargs="+", required=True, help="metadata.jsonl of each set")
    p.add_argument("--out", required=True)
    p.add_argument("--append", action="store_true", help="add to --out instead of replacing it")
    p.add_argument(
        "--audio-out", help="write 16 kHz mono copies here (default: point at the original files)"
    )
    p.add_argument(
        "--keyword-label", default="hey_vita", help="label for records marked 'positive'"
    )
    p.add_argument(
        "--speaker-prefix", default="vimd_", help="prepended to speaker ids to keep corpora apart"
    )
    p.add_argument("--env", default="tts_clean")
    p.add_argument(
        "--min-speech", type=float, default=0.45, help="keyword clips: seconds of active audio"
    )
    p.add_argument("--min-negative-speech", type=float, default=0.15)
    p.add_argument(
        "--max-speech", type=float, default=1.5, help="keyword clips only; 0 disables the limit"
    )
    p.add_argument(
        "--max-negative-speech",
        type=float,
        default=6.0,
        help="negative clips only; 0 disables the limit",
    )
    p.set_defaults(func=cmd_import_fish)

    p = sub.add_parser(
        "add-carriers", help="join spoken commands after half of each voice's keyword clips"
    )
    p.add_argument("--manifest", required=True, help="manifest from import-fish")
    p.add_argument("--carriers", nargs="+", required=True, help="Fish metadata.jsonl of commands")
    p.add_argument("--audio-out", required=True)
    p.add_argument("--out", required=True)
    p.add_argument("--speaker-prefix", default="vimd_")
    p.add_argument("--gap", type=float, nargs=2, default=[0.05, 0.30], help="pause range, seconds")
    p.add_argument("--max-command", type=float, default=6.0, help="seconds of command speech")
    p.add_argument("--seed", type=int, default=0)
    p.set_defaults(func=cmd_add_carriers)

    p = sub.add_parser("merge", help="concatenate manifests, dropping duplicate audio paths")
    p.add_argument("--inputs", nargs="+", required=True)
    p.add_argument("--out", required=True)
    p.set_defaults(func=cmd_merge)

    p = sub.add_parser("split", help="assign speaker-disjoint train/dev/test splits")
    p.add_argument("--manifest", required=True)
    p.add_argument("--out", required=True)
    p.add_argument("--dev", type=float, default=0.1)
    p.add_argument("--test", type=float, default=0.1)
    p.add_argument("--seed", type=int, default=0)
    p.add_argument(
        "--holdout-sources",
        nargs="*",
        default=[],
        help="only these source types may enter dev/test, e.g. 'human corpus'",
    )
    p.set_defaults(func=cmd_split)

    p = sub.add_parser("validate", help="check a manifest; exits 1 on errors")
    p.add_argument("--manifest", required=True)
    p.add_argument("--classes", nargs="*", help="model classes, to catch misspelled keyword labels")
    p.add_argument("--check-audio", action="store_true", help="decode every file (slow)")
    p.add_argument("--max-messages", type=int, default=50)
    p.set_defaults(func=cmd_validate)

    p = sub.add_parser("stats", help="print coverage tables")
    p.add_argument("--manifest", required=True)
    p.set_defaults(func=cmd_stats)
    return parser


def main(argv: list[str] | None = None) -> None:
    args = build_parser().parse_args(argv)
    sys.exit(args.func(args))


if __name__ == "__main__":
    main()