Repository navigation
Expand file tree
/
Copy pathprep_encodec_cond.py
More file actions
1755 lines (1527 loc) · 61.1 KB
/
Copy pathprep_encodec_cond.py
File metadata and controls
1755 lines (1527 loc) · 61.1 KB
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
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
Pre-compute VoiceCraft 16 kHz EnCodec latents and per-phone frame masks for the
phone-conditioned training pipeline (train_phone_ec_cond.py).
Data sources
------------
* LibriSpeech audio: /media/tom/SATAM/King/LibriSpeech/{subset}/...
* LibriSpeech phones: /media/tom/SATAM/librispeech-phone-alignments/{subset}/...
(per-utterance Praat TextGrids with an ARPAbet ``phones`` tier)
* VCTK (downsampled to 16 kHz on load from the existing 24 kHz ``*_safe`` wavs):
audio /media/tom/SATAM/lip/vctk_audio/{spk}_safe/*.wav
phones /media/tom/SATAM/lip/vctk_audio/aligned_json/{spk}_safe_aligned.json
Each NPZ stores continuous encoder latents ``z_e`` [T, D] float16 plus one
bool[T] mask per requested phone (``{phone}_mask``). Frame rate is 50 fps
(16 kHz audio, VoiceCraft EnCodec hop 320).
Examples
--------
python prep_encodec_cond.py --phone_masks s r
python prep_encodec_cond.py --phone_masks s r \\
--librispeech_subsets train-clean-100 train-clean-360
python prep_encodec_cond.py --phone_masks s r --skip_vctk
python prep_encodec_cond.py --phone_masks s r --vctk_only
python prep_encodec_cond.py --phone_masks s r --refresh_utterances
# Add new phones later without re-encoding existing NPZs:
python prep_encodec_cond.py --phone_masks z k --add_phones
# Reuse z_e / copy NPZs from a previous prep (any source):
python prep_encodec_cond.py --phone_masks s r --copy_npz_from /path/to/old_prep
python prep_encodec_cond.py --phone_masks s r --skip_vctk \\
--copy_npz_from /path/to/old_prep --output_dir /path/to/new_prep
Utterance lists are cached in ``<output_dir>/utterances_cache.json`` so reruns skip
the slow alignment scan. ``manifest.jsonl`` is rewritten at the end of each run.
With ``--add_phones``, pass only the new ``--phone_masks``; utterances that already
have ``z_e`` get the new mask arrays merged in and other masks are left untouched.
Without ``--add_phones``, each NPZ is re-encoded and stores only the requested masks.
"""
from __future__ import annotations
import argparse
import gc
import json
import logging
import re
import shutil
import sys
from collections import namedtuple
from pathlib import Path
from typing import Dict, Iterable, List, Optional, Sequence, Tuple
from concurrent.futures import ThreadPoolExecutor, as_completed
import numpy as np
import soundfile as sf
import torch
sys.path.insert(0, str(Path(__file__).parent))
from phone_labels import (
DEFAULT_TARGET_PHONES,
align_label,
build_alignment_char_vocab,
build_label_to_phone,
encode_label_to_ids,
mask_key,
)
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
log = logging.getLogger(__name__)
# ─────────────────────────────────────────────────────────────────────────────
# Paths
# ─────────────────────────────────────────────────────────────────────────────
LIBRISPEECH_AUDIO_ROOT = Path("/media/tom/SATAM/King/LibriSpeech")
LIBRISPEECH_ALIGN_ROOT = Path("/media/tom/SATAM/librispeech-phone-alignments")
VCTK_AUDIO_BASE = Path("/media/tom/SATAM/lip/vctk_audio")
VCTK_ALIGNED_DIR = VCTK_AUDIO_BASE / "aligned_json"
DEFAULT_OUTPUT_DIR = Path("/media/tom/SATAM/lip/encodec_npzs_cond")
DEFAULT_LIBRISPEECH_SUBSETS = (
"train-clean-100",
"train-clean-360",
"train-other-500",
)
UTTERANCES_CACHE_VERSION = 1
DEFAULT_GPU_CLEAR_EVERY = 50
# ─────────────────────────────────────────────────────────────────────────────
# Audio / codec config (VoiceCraft 16 kHz EnCodec)
# ─────────────────────────────────────────────────────────────────────────────
FS = 16_000
ENCODEC_FPS = 50.0
ENCODEC_DIM = 128
MAX_UTT_SEC = 2000.0
MIN_CONTEXT_SEC = 0.15
MIN_PHONE_DUR_SEC = 0.03
SKIP_PHONE_LABELS = frozenset({"", "sil", "spn", "<unk>"})
Span = Tuple[float, float]
PhoneSpans = Dict[str, List[Span]]
Utterance = namedtuple(
"Utterance",
[
"wav_path", "phone_spans", "pad_pre_sec", "pad_post_sec",
"speaker", "source", "phone_intervals",
],
defaults=((),),
)
_PHONE_INTERVAL_RE = re.compile(
r"intervals \[\d+\]:\s*\n"
r"\s*xmin = ([\d.]+)\s*\n"
r"\s*xmax = ([\d.]+)\s*\n"
r'\s*text = "([^"]*)"',
re.MULTILINE,
)
def default_output_dir() -> Path:
return DEFAULT_OUTPUT_DIR
# ─────────────────────────────────────────────────────────────────────────────
# TextGrid parsing (phones tier, ARPAbet)
# ─────────────────────────────────────────────────────────────────────────────
def parse_textgrid_phone_intervals(tg_path: Path) -> List[Tuple[float, float, str]]:
"""Return (xmin, xmax, label) intervals from the ``phones`` tier."""
try:
content = tg_path.read_text(encoding="utf-8")
except OSError as exc:
log.warning("Cannot read TextGrid %s: %s", tg_path, exc)
return []
marker = 'name = "phones"'
start = content.find(marker)
if start < 0:
return []
chunk = content[start:]
next_item = re.search(r"\nitem \[\d+\]:\s*\n\s*class", chunk[len(marker):])
if next_item is not None:
chunk = chunk[: len(marker) + next_item.start()]
return [
(float(m.group(1)), float(m.group(2)), m.group(3).strip())
for m in _PHONE_INTERVAL_RE.finditer(chunk)
]
def label_to_user_phone(label: str, label_to_phone: Dict[str, str]) -> Optional[str]:
if label in SKIP_PHONE_LABELS:
return None
if label in label_to_phone:
return label_to_phone[label]
# ARPAbet vowel stress digits, e.g. S0 -> S (already in map) or AH0 -> AH
base = re.sub(r"\d+$", "", label)
return label_to_phone.get(base)
def spans_from_phone_intervals(
intervals: Sequence[Tuple[float, float, str]],
phones: Sequence[str],
label_to_phone: Dict[str, str],
min_phone_dur: float,
) -> PhoneSpans:
phone_spans: PhoneSpans = {ph: [] for ph in phones}
for xmin, xmax, label in intervals:
user_phone = label_to_user_phone(label, label_to_phone)
if user_phone is None:
continue
if xmax - xmin < min_phone_dur:
continue
phone_spans[user_phone].append((xmin, xmax))
return phone_spans
def phone_intervals_from_mfa(
phone_dict: dict,
min_phone_dur: float = MIN_PHONE_DUR_SEC,
) -> List[Tuple[float, float, str]]:
"""All non-skip MFA phone intervals in time order."""
items: List[Tuple[float, float, str]] = []
for ph_entry in phone_dict.values():
label = str(ph_entry["text"]).strip()
if label in SKIP_PHONE_LABELS:
continue
xmin, xmax = float(ph_entry["xmin"]), float(ph_entry["xmax"])
if xmax - xmin < min_phone_dur:
continue
items.append((xmin, xmax, label))
return sorted(items, key=lambda x: x[0])
def spans_from_mfa_json_phones(
phone_dict: dict,
phones: Sequence[str],
label_to_phone: Dict[str, str],
min_phone_dur: float,
) -> PhoneSpans:
phone_spans: PhoneSpans = {ph: [] for ph in phones}
for ph_entry in phone_dict.values():
label = ph_entry["text"]
user_phone = label_to_user_phone(label, label_to_phone)
if user_phone is None:
continue
xmin, xmax = float(ph_entry["xmin"]), float(ph_entry["xmax"])
if xmax - xmin < min_phone_dur:
continue
phone_spans[user_phone].append((xmin, xmax))
return phone_spans
# ─────────────────────────────────────────────────────────────────────────────
# Utterance collection
# ─────────────────────────────────────────────────────────────────────────────
def _finalize_utterance(
wav_path: Path,
phone_spans_raw: PhoneSpans,
phones: Sequence[str],
speaker: str,
source: str,
min_context: float = MIN_CONTEXT_SEC,
max_utt_dur: float = MAX_UTT_SEC,
phone_intervals_raw: Optional[Sequence[Tuple[float, float, str]]] = None,
) -> Optional[Utterance]:
if not any(phone_spans_raw[ph] for ph in phones):
return None
try:
info = sf.info(str(wav_path))
except Exception as exc:
log.warning("sf.info failed for %s: %s", wav_path, exc)
return None
utt_dur = info.frames / info.samplerate
utt_end = min(utt_dur, max_utt_dur)
clipped: PhoneSpans = {}
for ph in phones:
spans = [(s, e) for s, e in phone_spans_raw[ph] if s < utt_end]
if spans:
clipped[ph] = spans
if not clipped:
return None
all_spans = [sp for spans in clipped.values() for sp in spans]
first_start = min(s for s, _ in all_spans)
last_end = max(e for _, e in all_spans)
pad_pre = max(0.0, min_context - first_start)
pad_post = max(0.0, min_context - (utt_end - last_end))
phone_spans_shifted = {
ph: [(s + pad_pre, e + pad_pre) for s, e in spans]
for ph, spans in clipped.items()
}
shifted_intervals: List[Tuple[float, float, str]] = []
if phone_intervals_raw:
for xmin, xmax, label in phone_intervals_raw:
if label in SKIP_PHONE_LABELS:
continue
if xmin >= utt_end:
continue
xmax = min(xmax, utt_end)
if xmax - xmin < MIN_PHONE_DUR_SEC:
continue
shifted_intervals.append((xmin + pad_pre, xmax + pad_pre, label))
return Utterance(
wav_path=wav_path,
phone_spans=phone_spans_shifted,
pad_pre_sec=pad_pre,
pad_post_sec=pad_post,
speaker=speaker,
source=source,
phone_intervals=tuple(shifted_intervals),
)
def collect_utterances_librispeech(
audio_root: Path,
align_root: Path,
subsets: Sequence[str],
phones: Sequence[str],
min_phone_dur: float = MIN_PHONE_DUR_SEC,
min_context: float = MIN_CONTEXT_SEC,
max_utt_dur: float = MAX_UTT_SEC,
) -> List[Utterance]:
utterances: List[Utterance] = []
label_to_phone = build_label_to_phone(phones)
for subset in subsets:
align_subset = align_root / subset
audio_subset = audio_root / subset
if not align_subset.is_dir():
log.warning("Alignment subset missing: %s", align_subset)
continue
if not audio_subset.is_dir():
log.warning("Audio subset missing: %s", audio_subset)
continue
n_subset = 0
for tg_path in sorted(align_subset.rglob("*.TextGrid")):
rel = tg_path.relative_to(align_subset)
wav_path = audio_subset / rel.with_suffix(".flac")
if not wav_path.is_file():
continue
parts = rel.parts
speaker = (
f"librispeech/{subset}/{'/'.join(parts[:-1])}"
if len(parts) >= 2
else f"librispeech/{subset}"
)
intervals = parse_textgrid_phone_intervals(tg_path)
phone_spans_raw = spans_from_phone_intervals(
intervals, phones, label_to_phone, min_phone_dur,
)
utt = _finalize_utterance(
wav_path,
phone_spans_raw,
phones,
speaker=speaker,
source=f"librispeech/{subset}",
min_context=min_context,
max_utt_dur=max_utt_dur,
phone_intervals_raw=intervals,
)
if utt is not None:
utterances.append(utt)
n_subset += 1
log.info(
"LibriSpeech %s: %d utterances with any of %s",
subset, n_subset, list(phones),
)
log.info("Collected %d LibriSpeech utterances total", len(utterances))
return utterances
def _subset_tag(subset: str) -> str:
"""
Map LibriSpeech subset names to the numeric tag used in aligned-* dirs.
Examples:
train-clean-100 -> 100
train-clean-360 -> 360
train-other-500 -> 500
"""
m = re.search(r"(\d+)$", subset)
return m.group(1) if m else subset
def _iter_librispeech_mfa_jsons(align_root: Path, subset: str) -> Iterable[Path]:
"""
Yield LibriSpeech MFA-style alignment JSONs.
Expected layout (per user):
/media/tom/SATAM/librispeech-phone-alignments/aligned-100/...
/media/tom/SATAM/librispeech-phone-alignments/aligned-360/...
/media/tom/SATAM/librispeech-phone-alignments/aligned-500/...
where JSON structure is similar to VCTK aligned_json (top-level dict of utterances,
each with a "phones" dict of {id: {xmin,xmax,text}} entries).
"""
tag = _subset_tag(subset)
# Primary: aligned-<tag> directory (your actual layout).
direct_dash = align_root / f"aligned-{tag}"
if direct_dash.is_dir():
yield from sorted(direct_dash.rglob("*.json"))
return
# Backward-compatible fallback: aligned_<subset> (old guess).
direct_us = align_root / f"aligned_{subset}"
if direct_us.is_dir():
yield from sorted(direct_us.rglob("*.json"))
return
# Last resort: scan any aligned-* / aligned_* dirs that mention the tag/subset.
for d in sorted(p for p in align_root.glob("aligned-*") if p.is_dir()):
if tag not in d.name and subset not in d.name:
continue
yield from sorted(d.rglob("*.json"))
def _resolve_librispeech_mfa_audio_path(audio_subset: Path, wav_key: str) -> Optional[Path]:
"""
Resolve a LibriSpeech MFA JSON utterance key to an audio file.
JSON keys look like '16-122828-0057.flac' (flat filename, .flac suffix).
Audio is stored as:
{audio_subset}/{speaker}/{chapter}/{speaker}-{chapter}-{utterance}.wav
e.g. wav-360/16/122828/16-122828-0057.wav
We parse the stem on the first two '-' delimiters to recover speaker and chapter,
then try both .wav and .flac in the nested directory. If parsing fails we fall back
to trying the key flat (both suffixes) directly under audio_subset.
"""
stem = Path(wav_key).stem # e.g. '16-122828-0057'
parts = stem.split("-", 2) # ['16', '122828', '0057']
if len(parts) == 3:
speaker, chapter = parts[0], parts[1]
nested = audio_subset / speaker / chapter / stem
for suffix in (".wav", ".flac"):
p = nested.with_suffix(suffix)
if p.is_file():
return p
# Fallback: flat key under audio_subset (both suffixes).
flat = audio_subset / stem
for suffix in (".wav", ".flac"):
p = flat.with_suffix(suffix)
if p.is_file():
return p
return None
def collect_utterances_librispeech_mfa(
audio_root: Path,
align_root: Path,
subsets: Sequence[str],
phones: Sequence[str],
min_phone_dur: float = MIN_PHONE_DUR_SEC,
min_context: float = MIN_CONTEXT_SEC,
max_utt_dur: float = MAX_UTT_SEC,
num_workers: int = 1,
) -> List[Utterance]:
"""
LibriSpeech utterances using MFA JSON alignments (instead of ARPAbet TextGrids).
"""
utterances: List[Utterance] = []
label_to_phone = build_label_to_phone(phones)
for subset in subsets:
tag = _subset_tag(subset)
# Audio lives under wav-<tag>, not the Libri subset name.
audio_subset = audio_root / f"wav-{tag}"
if not audio_subset.is_dir():
log.warning(
"Audio subset dir missing for %s: tried %s", subset, audio_subset
)
continue
jsons = list(_iter_librispeech_mfa_jsons(align_root, subset))
if not jsons:
log.warning("No Libri MFA JSONs found for %s under %s", subset, align_root)
continue
n_subset = 0
n_missing_audio = 0
def _scan_one_json(jf: Path) -> tuple[int, int, List[Utterance]]:
"""Return (n_ok, n_missing_audio, utterances_from_file)."""
try:
with open(jf, encoding="utf-8") as fh:
data = json.load(fh)
except (OSError, json.JSONDecodeError) as exc:
log.warning("Unreadable Libri MFA JSON %s: %s", jf, exc)
return 0, 0, []
if not isinstance(data, dict):
return 0, 0, []
out: List[Utterance] = []
ok = missing = 0
for wav_key, entry in data.items():
if not isinstance(entry, dict):
continue
wav_path = _resolve_librispeech_mfa_audio_path(audio_subset, str(wav_key))
if wav_path is None or not wav_path.is_file():
missing += 1
continue
# Your JSON keys end with .flac, so speaker dirs like aligned-360/16/*.json
# naturally group by the parent directory of the key (if any). If the key is
# just "16-....flac", we group under the JSON's parent folder name.
rel = Path(str(wav_key))
if len(rel.parts) >= 2:
speaker_bucket = rel.parent.as_posix()
else:
speaker_bucket = jf.parent.name
speaker = f"librispeech/{subset}/{speaker_bucket}"
phone_spans_raw = spans_from_mfa_json_phones(
entry.get("phones", {}), phones, label_to_phone, min_phone_dur,
)
intervals = phone_intervals_from_mfa(entry.get("phones", {}), min_phone_dur)
utt = _finalize_utterance(
wav_path,
phone_spans_raw,
phones,
speaker=speaker,
source=f"librispeech/{subset}",
min_context=min_context,
max_utt_dur=max_utt_dur,
phone_intervals_raw=intervals,
)
if utt is not None:
out.append(utt)
ok += 1
return ok, missing, out
workers = max(1, int(num_workers or 1))
if workers == 1:
for jf in jsons:
ok, miss, out = _scan_one_json(jf)
n_subset += ok
n_missing_audio += miss
utterances.extend(out)
else:
# Threaded JSON parsing + metadata reading can speed up on multicore.
# This does not parallelize EnCodec encoding (still done later, sequentially).
with ThreadPoolExecutor(max_workers=workers) as ex:
futs = [ex.submit(_scan_one_json, jf) for jf in jsons]
for fut in as_completed(futs):
ok, miss, out = fut.result()
n_subset += ok
n_missing_audio += miss
utterances.extend(out)
log.info(
"LibriSpeech %s (MFA JSON): %d utterances with any of %s (missing audio=%d)",
subset, n_subset, list(phones), n_missing_audio,
)
log.info("Collected %d LibriSpeech utterances total (MFA JSON)", len(utterances))
return utterances
def collect_utterances_vctk(
audio_base: Path,
aligned_dir: Path,
phones: Sequence[str],
min_phone_dur: float = MIN_PHONE_DUR_SEC,
min_context: float = MIN_CONTEXT_SEC,
max_utt_dur: float = MAX_UTT_SEC,
) -> List[Utterance]:
"""VCTK utterances; audio is resampled 24 kHz -> 16 kHz during encoding prep."""
utterances: List[Utterance] = []
label_to_phone = build_label_to_phone(phones)
for jf in sorted(aligned_dir.glob("*_aligned.json")):
spk_dir = audio_base / jf.stem.replace("_aligned", "")
if not spk_dir.is_dir():
continue
speaker = spk_dir.name
with open(jf, encoding="utf-8") as fh:
data = json.load(fh)
for wav_name, entry in data.items():
wav_path = spk_dir / wav_name
if not wav_path.is_file():
continue
phone_spans_raw = spans_from_mfa_json_phones(
entry.get("phones", {}), phones, label_to_phone, min_phone_dur,
)
intervals = phone_intervals_from_mfa(entry.get("phones", {}), min_phone_dur)
utt = _finalize_utterance(
wav_path,
phone_spans_raw,
phones,
speaker=speaker,
source="vctk",
min_context=min_context,
max_utt_dur=max_utt_dur,
phone_intervals_raw=intervals,
)
if utt is not None:
utterances.append(utt)
log.info(
"Collected %d VCTK utterances containing any of %s (from %s)",
len(utterances), list(phones), aligned_dir,
)
return utterances
def collect_utterances(
phones: Sequence[str],
librispeech_subsets: Sequence[str],
include_librispeech: bool,
include_vctk: bool,
audio_root: Path = LIBRISPEECH_AUDIO_ROOT,
align_root: Path = LIBRISPEECH_ALIGN_ROOT,
vctk_audio: Path = VCTK_AUDIO_BASE,
vctk_aligned: Path = VCTK_ALIGNED_DIR,
libri_mfa: bool = False,
num_workers: int = 1,
**kwargs,
) -> List[Utterance]:
utterances: List[Utterance] = []
if include_librispeech:
if libri_mfa:
utterances.extend(
collect_utterances_librispeech_mfa(
audio_root,
align_root,
librispeech_subsets,
phones,
num_workers=num_workers,
**kwargs,
)
)
else:
utterances.extend(
collect_utterances_librispeech(
audio_root, align_root, librispeech_subsets, phones, **kwargs,
)
)
if include_vctk:
utterances.extend(
collect_utterances_vctk(vctk_audio, vctk_aligned, phones, **kwargs)
)
return utterances
# ─────────────────────────────────────────────────────────────────────────────
# Utterance cache (skip slow TextGrid / JSON scan on reruns)
# ─────────────────────────────────────────────────────────────────────────────
def utterances_cache_path(out_dir: Path) -> Path:
return out_dir / "utterances_cache.json"
def utterance_collection_config(
phones: Sequence[str],
librispeech_subsets: Sequence[str],
include_librispeech: bool,
include_vctk: bool,
audio_root: Path,
align_root: Path,
vctk_audio: Path,
vctk_aligned: Path,
libri_mfa: bool,
) -> dict:
return {
"version": UTTERANCES_CACHE_VERSION,
"phones": list(phones),
"librispeech_subsets": list(librispeech_subsets),
"include_librispeech": include_librispeech,
"include_vctk": include_vctk,
"librispeech_audio": str(audio_root),
"librispeech_align": str(align_root),
"librispeech_align_format": "mfa_json" if libri_mfa else "textgrid_arpabet",
"vctk_audio": str(vctk_audio),
"vctk_aligned": str(vctk_aligned),
"min_phone_dur_sec": MIN_PHONE_DUR_SEC,
"min_context_sec": MIN_CONTEXT_SEC,
"max_utt_sec": MAX_UTT_SEC,
}
def utterance_to_dict(utt: Utterance) -> dict:
return {
"wav_path": str(utt.wav_path),
"phone_spans": utt.phone_spans,
"pad_pre_sec": utt.pad_pre_sec,
"pad_post_sec": utt.pad_post_sec,
"speaker": utt.speaker,
"source": utt.source,
"phone_intervals": [list(item) for item in utt.phone_intervals],
}
def utterance_from_dict(data: dict) -> Utterance:
intervals = data.get("phone_intervals") or ()
return Utterance(
wav_path=Path(data["wav_path"]),
phone_spans={ph: [tuple(sp) for sp in spans] for ph, spans in data["phone_spans"].items()},
pad_pre_sec=float(data["pad_pre_sec"]),
pad_post_sec=float(data["pad_post_sec"]),
speaker=data["speaker"],
source=data["source"],
phone_intervals=tuple(tuple(x) for x in intervals),
)
def save_utterances_cache(
cache_path: Path,
config: dict,
utterances: Sequence[Utterance],
) -> None:
cache_path.parent.mkdir(parents=True, exist_ok=True)
payload = {
**config,
"n_utterances": len(utterances),
"utterances": [utterance_to_dict(u) for u in utterances],
}
tmp = cache_path.with_suffix(".json.tmp")
with open(tmp, "w", encoding="utf-8") as fh:
json.dump(payload, fh)
tmp.replace(cache_path)
log.info("Saved utterance cache (%d records) -> %s", len(utterances), cache_path)
def load_utterances_cache(cache_path: Path, expected: dict) -> Optional[List[Utterance]]:
if not cache_path.is_file():
return None
try:
with open(cache_path, encoding="utf-8") as fh:
payload = json.load(fh)
except (OSError, json.JSONDecodeError) as exc:
log.warning("Unreadable utterance cache %s: %s", cache_path, exc)
return None
for key, value in expected.items():
if payload.get(key) != value:
log.info(
"Utterance cache stale (%s: %r != %r) — recollecting",
key, payload.get(key), value,
)
return None
utterances = [utterance_from_dict(item) for item in payload.get("utterances", [])]
log.info("Loaded %d utterances from cache %s", len(utterances), cache_path)
return utterances
def load_or_collect_utterances(
phones: Sequence[str],
librispeech_subsets: Sequence[str],
include_librispeech: bool,
include_vctk: bool,
audio_root: Path,
align_root: Path,
vctk_audio: Path,
vctk_aligned: Path,
libri_mfa: bool,
num_workers: int,
cache_path: Path,
refresh: bool,
**kwargs,
) -> List[Utterance]:
config = utterance_collection_config(
phones, librispeech_subsets, include_librispeech, include_vctk,
audio_root, align_root, vctk_audio, vctk_aligned, libri_mfa,
)
if not refresh:
cached = load_utterances_cache(cache_path, config)
if cached is not None:
return cached
utterances = collect_utterances(
phones=phones,
librispeech_subsets=librispeech_subsets,
include_librispeech=include_librispeech,
include_vctk=include_vctk,
audio_root=audio_root,
align_root=align_root,
vctk_audio=vctk_audio,
vctk_aligned=vctk_aligned,
libri_mfa=libri_mfa,
num_workers=num_workers,
**kwargs,
)
if utterances:
save_utterances_cache(cache_path, config, utterances)
return utterances
# ─────────────────────────────────────────────────────────────────────────────
# GPU helpers
# ─────────────────────────────────────────────────────────────────────────────
def clear_gpu_cache(device: str, *, sync: bool = True) -> None:
if not device.startswith("cuda") or not torch.cuda.is_available():
return
gc.collect()
if sync:
torch.cuda.synchronize()
torch.cuda.empty_cache()
# ─────────────────────────────────────────────────────────────────────────────
def load_encodec(device: str, checkpoint: Path):
from voicecraft_encodec import load_voicecraft_encodec as _load_voicecraft_encodec
return _load_voicecraft_encodec(device, checkpoint, load_decoder=False)
@torch.no_grad()
def extract_ze(model, wav_np: np.ndarray, device: str) -> np.ndarray:
"""float32 mono @ FS Hz -> z_e [T, D] float16 (pre-quantization encoder output)."""
pcm = torch.from_numpy(wav_np).float().unsqueeze(0).unsqueeze(0).to(device)
z_e = model.encoder(pcm)
out = z_e.squeeze(0).t().cpu().half().numpy()
del pcm, z_e
return out
def build_phone_mask(spans: List[Span], T: int, fps: float = ENCODEC_FPS) -> np.ndarray:
mask = np.zeros(T, dtype=bool)
for t_start, t_end in spans:
f_start = max(0, int(t_start * fps))
f_end = min(T, int(np.ceil(t_end * fps)))
if f_end > f_start:
mask[f_start:f_end] = True
return mask
def build_phone_seq_arrays(
phone_intervals: Sequence[Tuple[float, float, str]],
T: int,
char2id: Dict[str, int],
) -> Optional[Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]]:
"""Char-tokenize the utterance phone string with per-phone frame alignment."""
phone_ids: List[int] = []
phone_starts: List[int] = []
phone_ends: List[int] = []
phone_nchars: List[int] = []
for start, end, label in phone_intervals:
char_ids = encode_label_to_ids(label, char2id)
if not char_ids:
continue
f0 = max(0, int(start * ENCODEC_FPS))
f1 = min(T, int(np.ceil(end * ENCODEC_FPS)))
if f1 <= f0:
continue
phone_starts.append(f0)
phone_ends.append(f1)
phone_nchars.append(len(char_ids))
phone_ids.extend(char_ids)
if not phone_ids:
return None
return (
np.asarray(phone_ids, dtype=np.int16),
np.asarray(phone_starts, dtype=np.int32),
np.asarray(phone_ends, dtype=np.int32),
np.asarray(phone_nchars, dtype=np.int16),
)
def npz_full_phone_ok(data) -> bool:
if not {"phone_ids", "phone_starts", "phone_ends", "phone_nchars"} <= set(data.files):
return False
n_phones = int(data["phone_starts"].shape[0])
return (
n_phones > 0
and int(data["phone_ends"].shape[0]) == n_phones
and int(data["phone_nchars"].shape[0]) == n_phones
and int(data["phone_nchars"].sum()) == int(data["phone_ids"].shape[0])
)
def attach_phone_seq_arrays(
arrays: Dict[str, np.ndarray],
utt: Utterance,
T: int,
char2id: Dict[str, int],
) -> bool:
if not utt.phone_intervals:
return False
seq = build_phone_seq_arrays(utt.phone_intervals, T, char2id)
if seq is None:
return False
phone_ids, phone_starts, phone_ends, phone_nchars = seq
arrays["phone_ids"] = phone_ids
arrays["phone_starts"] = phone_starts
arrays["phone_ends"] = phone_ends
arrays["phone_nchars"] = phone_nchars
return True
def resample_wav(wav: np.ndarray, orig_sr: int, target_sr: int) -> np.ndarray:
if orig_sr == target_sr:
return wav
try:
import librosa
return librosa.resample(wav, orig_sr=orig_sr, target_sr=target_sr)
except ImportError:
import torchaudio
t = torch.from_numpy(wav).float().unsqueeze(0)
t = torchaudio.functional.resample(t, orig_sr, target_sr)
return t.squeeze(0).numpy()
def load_wav_padded(utt: Utterance, target_sr: int = FS) -> Optional[np.ndarray]:
try:
info = sf.info(str(utt.wav_path))
read_frames = min(info.frames, int(MAX_UTT_SEC * info.samplerate))
wav, sr = sf.read(
str(utt.wav_path),
stop=read_frames,
dtype="float32",
always_2d=False,
)
except Exception as exc:
log.warning("Read failed for %s: %s", utt.wav_path, exc)
return None
if wav.ndim > 1:
wav = wav.mean(axis=1)
if sr != target_sr:
wav = resample_wav(wav, sr, target_sr)
if utt.pad_pre_sec > 0:
n = int(round(utt.pad_pre_sec * target_sr))
wav = np.concatenate([np.zeros(n, np.float32), wav])
if utt.pad_post_sec > 0:
n = int(round(utt.pad_post_sec * target_sr))
wav = np.concatenate([wav, np.zeros(n, np.float32)])
return wav.astype(np.float32, copy=False)
# ─────────────────────────────────────────────────────────────────────────────
# NPZ I/O
# ─────────────────────────────────────────────────────────────────────────────
def phones_needing_mask_update(
utt: Utterance,
npz_path: Path,
phones: Sequence[str],
) -> Tuple[bool, List[str]]:
"""Return (need_encode, phones whose masks are missing or stale)."""
try:
with np.load(npz_path) as d:
if "z_e" not in d:
return True, list(phones)
stale: List[str] = []
for ph in phones:
key = mask_key(ph)
if key not in d:
stale.append(ph)
continue
should_have = bool(utt.phone_spans.get(ph))
has_frames = bool(d[key].any())
if should_have != has_frames:
stale.append(ph)
return False, stale
except Exception:
return True, list(phones)
def npz_masks_up_to_date(
utt: Utterance,
npz_path: Path,
phones: Sequence[str],
*,
add_phones: bool,
full_phone: bool = False,
) -> bool:
if add_phones:
need_encode, stale = phones_needing_mask_update(utt, npz_path, phones)
if need_encode or stale:
return False
else:
try:
with np.load(npz_path) as d:
if "z_e" not in d:
return False
for ph in phones:
key = mask_key(ph)
if key not in d:
return False
should_have = bool(utt.phone_spans.get(ph))
has_frames = bool(d[key].any())
if should_have != has_frames:
return False
except Exception:
return False
if full_phone:
try:
with np.load(npz_path) as d:
return npz_full_phone_ok(d)
except Exception:
return False
return True
def phones_from_npz(d) -> List[str]:
suffix = "_mask"
return sorted(
key[: -len(suffix)]
for key in d.files
if key.endswith(suffix)
)
def manifest_record_from_npz(
npz_path: Path,
wav_path: Path,
speaker: str,
source: str,
*,
full_phone: bool = False,