-
Notifications
You must be signed in to change notification settings - Fork 242
/
features.py
1040 lines (926 loc) · 37.4 KB
/
features.py
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
"""Classes for configuring feature generation"""
from __future__ import annotations
import logging
import os
import re
import threading
import typing
from abc import abstractmethod
from pathlib import Path
from typing import TYPE_CHECKING, Any, Union
import dataclassy
from _kalpy.feat import paste_feats
from _kalpy.matrix import CompressedMatrix, FloatVector
from _kalpy.util import BaseFloatMatrixWriter, BaseFloatVectorWriter, CompressedMatrixWriter
from kalpy.data import KaldiMapping, MatrixArchive, Segment
from kalpy.feat.data import FeatureArchive
from kalpy.feat.fmllr import FmllrComputer
from kalpy.feat.mfcc import MfccComputer
from kalpy.feat.pitch import PitchComputer
from kalpy.feat.vad import VadComputer
from kalpy.gmm.data import AlignmentArchive
from kalpy.ivector.extractor import IvectorExtractor
from kalpy.utils import generate_write_specifier
from sqlalchemy.orm import joinedload
from montreal_forced_aligner import config
from montreal_forced_aligner.abc import KaldiFunction
from montreal_forced_aligner.data import MfaArguments, PhoneType
from montreal_forced_aligner.db import File, Job, Phone, SoundFile, Utterance
from montreal_forced_aligner.helper import mfa_open
from montreal_forced_aligner.utils import thread_logger
if TYPE_CHECKING:
SpeakerCharacterType = Union[str, int]
from montreal_forced_aligner.abc import MetaDict
__all__ = [
"FeatureConfigMixin",
"VadConfigMixin",
"IvectorConfigMixin",
"CalcFmllrFunction",
"ComputeVadFunction",
"VadArguments",
"MfccFunction",
"MfccArguments",
"CalcFmllrArguments",
"ExtractIvectorsFunction",
"ExtractIvectorsArguments",
"ExportIvectorsFunction",
"ExportIvectorsArguments",
]
logger = logging.getLogger("mfa")
# noinspection PyUnresolvedReferences
@dataclassy.dataclass(slots=True)
class VadArguments(MfaArguments):
"""Arguments for :class:`~montreal_forced_aligner.corpus.features.ComputeVadFunction`"""
vad_options: MetaDict
# noinspection PyUnresolvedReferences
@dataclassy.dataclass(slots=True)
class MfccArguments(MfaArguments):
"""
Arguments for :class:`~montreal_forced_aligner.corpus.features.MfccFunction`
"""
data_directory: Path
mfcc_computer: MfccComputer
pitch_computer: typing.Optional[PitchComputer]
# noinspection PyUnresolvedReferences
@dataclassy.dataclass(slots=True)
class FinalFeatureArguments(MfaArguments):
"""
Arguments for :class:`~montreal_forced_aligner.corpus.features.FinalFeatureFunction`
"""
data_directory: Path
uses_cmvn: bool
sliding_cmvn: bool
voiced_only: bool
subsample_feats: int
# noinspection PyUnresolvedReferences
@dataclassy.dataclass(slots=True)
class PitchArguments(MfaArguments):
"""
Arguments for :class:`~montreal_forced_aligner.corpus.features.MfccFunction`
"""
data_directory: Path
pitch_options: MetaDict
# noinspection PyUnresolvedReferences
@dataclassy.dataclass(slots=True)
class PitchRangeArguments(MfaArguments):
"""
Arguments for :class:`~montreal_forced_aligner.corpus.features.MfccFunction`
"""
data_directory: Path
pitch_options: MetaDict
# noinspection PyUnresolvedReferences
@dataclassy.dataclass(slots=True)
class CalcFmllrArguments(MfaArguments):
"""Arguments for :class:`~montreal_forced_aligner.corpus.features.CalcFmllrFunction`"""
working_directory: Path
ali_model_path: Path
model_path: Path
fmllr_options: MetaDict
thread_lock: threading.Lock
# noinspection PyUnresolvedReferences
@dataclassy.dataclass(slots=True)
class ExtractIvectorsArguments(MfaArguments):
"""Arguments for :class:`~montreal_forced_aligner.corpus.features.ExtractIvectorsFunction`"""
ivector_options: MetaDict
ivector_extractor_path: Path
ivectors_scp_path: Path
dubm_path: Path
# noinspection PyUnresolvedReferences
@dataclassy.dataclass(slots=True)
class ExportIvectorsArguments(MfaArguments):
"""Arguments for :class:`~montreal_forced_aligner.corpus.features.ExportIvectorsFunction`"""
use_xvector: bool
def feature_make_safe(value: Any) -> str:
"""
Transform an arbitrary value into a string
Parameters
----------
value: Any
Value to make safe
Returns
-------
str
Safe value
"""
if isinstance(value, bool):
return str(value).lower()
return str(value)
class MfccFunction(KaldiFunction):
"""
Multiprocessing function for generating MFCC features
See Also
--------
:meth:`.AcousticCorpusMixin.mfcc`
Main function that calls this function in parallel
:meth:`.AcousticCorpusMixin.mfcc_arguments`
Job method for generating arguments for this function
:kaldi_src:`compute-mfcc-feats`
Relevant Kaldi binary
:kaldi_src:`extract-segments`
Relevant Kaldi binary
:kaldi_src:`copy-feats`
Relevant Kaldi binary
:kaldi_src:`feat-to-len`
Relevant Kaldi binary
Parameters
----------
args: :class:`~montreal_forced_aligner.corpus.features.MfccArguments`
Arguments for the function
"""
def __init__(self, args: MfccArguments):
super().__init__(args)
self.data_directory = args.data_directory
self.pitch_computer = args.pitch_computer
self.mfcc_computer = args.mfcc_computer
def _run(self):
"""Run the function"""
with self.session() as session, thread_logger(
"kalpy.mfcc", self.log_path, job_name=self.job_name
) as mfcc_logger:
job: typing.Optional[Job] = session.get(Job, self.job_name)
raw_ark_path = job.construct_path(self.data_directory, "feats", "ark")
raw_pitch_ark_path = job.construct_path(self.data_directory, "pitch", "ark")
if raw_ark_path.exists():
return
min_length = 0.1
utterances = (
session.query(Utterance, SoundFile)
.join(Utterance.file)
.join(File.sound_file)
.filter(
Utterance.job_id == self.job_name,
Utterance.duration >= min_length,
)
.order_by(Utterance.kaldi_id)
)
mfcc_specifier = generate_write_specifier(raw_ark_path, True)
pitch_specifier = generate_write_specifier(raw_pitch_ark_path, True)
mfcc_writer = CompressedMatrixWriter(mfcc_specifier)
pitch_writer = None
if self.pitch_computer is not None:
pitch_writer = CompressedMatrixWriter(pitch_specifier)
num_done = 0
num_error = 0
for u, sf in utterances:
seg = Segment(str(sf.sound_file_path), u.begin, u.end, u.channel)
mfcc_logger.info(f"Thread {self.job_name}: Processing {u.kaldi_id}")
try:
mfccs = self.mfcc_computer.compute_mfccs_for_export(seg, compress=True)
except Exception as e:
mfcc_logger.warning(str(e))
num_error += 1
continue
mfcc_writer.Write(u.kaldi_id, mfccs)
if self.pitch_computer is not None:
pitch = self.pitch_computer.compute_pitch_for_export(seg, compress=True)
pitch_writer.Write(u.kaldi_id, pitch)
num_done += 1
self.callback(1)
mfcc_writer.Close()
if self.pitch_computer is not None:
pitch_writer.Close()
mfcc_logger.info(
f"Thread {self.job_name}: Done {num_done} utterances, errors on {num_error}."
)
class FinalFeatureFunction(KaldiFunction):
"""
Multiprocessing function for generating MFCC features
See Also
--------
:meth:`.AcousticCorpusMixin.mfcc`
Main function that calls this function in parallel
:meth:`.AcousticCorpusMixin.mfcc_arguments`
Job method for generating arguments for this function
:kaldi_src:`compute-mfcc-feats`
Relevant Kaldi binary
:kaldi_src:`extract-segments`
Relevant Kaldi binary
:kaldi_src:`copy-feats`
Relevant Kaldi binary
:kaldi_src:`feat-to-len`
Relevant Kaldi binary
Parameters
----------
args: :class:`~montreal_forced_aligner.corpus.features.MfccArguments`
Arguments for the function
"""
def __init__(self, args: FinalFeatureArguments):
super().__init__(args)
self.data_directory = args.data_directory
self.voiced_only = args.voiced_only
self.uses_cmvn = args.uses_cmvn
self.sliding_cmvn = args.sliding_cmvn
self.subsample_feats = args.subsample_feats
def _run(self) -> typing.Generator[int]:
"""Run the function"""
with self.session() as session, thread_logger(
"kalpy.mfcc", self.log_path, job_name=self.job_name
) as mfcc_logger:
job: typing.Optional[Job] = session.get(Job, self.job_name)
utterances = (
session.query(Utterance.kaldi_id, Utterance.speaker_id)
.filter(Utterance.job_id == self.job_name)
.order_by(Utterance.kaldi_id)
)
spk2utt = KaldiMapping(list_mapping=True)
utt2spk = KaldiMapping()
for utt_id, speaker_id in utterances:
utt_id = str(utt_id)
speaker_id = str(speaker_id)
utt2spk[utt_id] = speaker_id
if speaker_id not in spk2utt:
spk2utt[speaker_id] = []
spk2utt[speaker_id].append(utt_id)
feats_scp_path = job.construct_path(self.data_directory, "feats", "scp")
cmvn_ark_path = job.construct_path(self.data_directory, "cmvn", "scp")
pitch_scp_path = job.construct_path(self.data_directory, "pitch", "scp")
pitch_ark_path = job.construct_path(self.data_directory, "pitch", "ark")
vad_scp_path = job.construct_path(self.data_directory, "vad", "scp")
if not self.voiced_only or not os.path.exists(vad_scp_path):
vad_scp_path = None
raw_ark_path = job.construct_path(self.data_directory, "feats", "ark")
temp_ark_path = job.construct_path(self.data_directory, "final_features", "ark")
temp_scp_path = job.construct_path(self.data_directory, "final_features", "scp")
write_specifier = generate_write_specifier(temp_ark_path, write_scp=True)
feature_writer = CompressedMatrixWriter(write_specifier)
num_done = 0
num_error = 0
if self.uses_cmvn:
if not self.sliding_cmvn:
mfcc_archive = FeatureArchive(
feats_scp_path,
utt2spk=utt2spk,
cmvn_file_name=cmvn_ark_path,
vad_file_name=vad_scp_path,
subsample_n=self.subsample_feats,
)
else:
mfcc_archive = FeatureArchive(
feats_scp_path,
utt2spk=utt2spk,
vad_file_name=vad_scp_path,
subsample_n=self.subsample_feats,
use_sliding_cmvn=True,
)
else:
mfcc_archive = FeatureArchive(feats_scp_path)
if os.path.exists(pitch_scp_path):
pitch_archive = FeatureArchive(
pitch_scp_path, vad_file_name=vad_scp_path, subsample_n=self.subsample_feats
)
for (utt_id, feats), (utt_id2, pitch) in zip(mfcc_archive, pitch_archive):
assert utt_id == utt_id2
mfcc_logger.info(
f"Thread {self.job_name}: Processing {utt_id}: len = {feats.NumRows()}"
)
try:
feats = paste_feats([feats, pitch], 0)
except Exception as e:
mfcc_logger.warning(f"Thread {self.job_name}: Exception encountered: {e}")
num_error += 1
continue
feats = CompressedMatrix(feats)
feature_writer.Write(utt_id, feats)
num_done += 1
self.callback(1)
pitch_archive.close()
else:
for utt_id, mfccs in mfcc_archive:
mfcc_logger.info(
f"Thread {self.job_name}: Processing {utt_id}: len = {mfccs.NumCols()}"
)
mfccs = CompressedMatrix(mfccs)
feature_writer.Write(utt_id, mfccs)
num_done += 1
self.callback(1)
feature_writer.Close()
mfcc_archive.close()
os.remove(raw_ark_path)
if os.path.exists(pitch_scp_path):
os.remove(pitch_ark_path)
os.remove(pitch_scp_path)
os.remove(feats_scp_path)
os.rename(temp_scp_path, feats_scp_path)
mfcc_logger.info(
f"Thread {self.job_name}: Done {num_done} utterances, errors on {num_error}."
)
class ComputeVadFunction(KaldiFunction):
"""
Multiprocessing function to compute voice activity detection
See Also
--------
:meth:`.AcousticCorpusMixin.compute_vad`
Main function that calls this function in parallel
:meth:`.AcousticCorpusMixin.compute_vad_arguments`
Job method for generating arguments for this function
:kaldi_src:`compute-vad`
Relevant Kaldi binary
Parameters
----------
args: :class:`~montreal_forced_aligner.corpus.features.VadArguments`
Arguments for the function
"""
def __init__(self, args: VadArguments):
super().__init__(args)
self.vad_options = args.vad_options
def _run(self) -> None:
"""Run the function"""
with self.session() as session, thread_logger(
"kalpy.vad", self.log_path, job_name=self.job_name
):
job = (
session.query(Job)
.options(joinedload(Job.corpus, innerjoin=True))
.filter(Job.id == self.job_name)
.first()
)
vad_ark_path = job.construct_path(job.corpus.split_directory, "vad", "ark")
feature_archive = job.construct_feature_archive(job.corpus.split_directory)
computer = VadComputer(**self.vad_options)
computer.export_vad(
vad_ark_path, feature_archive, write_scp=True, callback=self.callback
)
class CalcFmllrFunction(KaldiFunction):
"""
Multiprocessing function for calculating fMLLR transforms
See Also
--------
:meth:`.AcousticCorpusMixin.calc_fmllr`
Main function that calls this function in parallel
:meth:`.AcousticCorpusMixin.calc_fmllr_arguments`
Job method for generating arguments for this function
:kaldi_src:`gmm-est-fmllr`
Relevant Kaldi binary
:kaldi_src:`gmm-est-fmllr-gpost`
Relevant Kaldi binary
:kaldi_src:`gmm-post-to-gpost`
Relevant Kaldi binary
:kaldi_src:`ali-to-post`
Relevant Kaldi binary
:kaldi_src:`weight-silence-post`
Relevant Kaldi binary
:kaldi_src:`compose-transforms`
Relevant Kaldi binary
:kaldi_src:`transform-feats`
Relevant Kaldi binary
Parameters
----------
args: :class:`~montreal_forced_aligner.corpus.features.CalcFmllrArguments`
Arguments for the function
"""
progress_pattern = re.compile(r"^LOG.*For speaker (?P<speaker>.*),.*$")
memory_error_pattern = re.compile(
r"^ERROR \(gmm-est-fmllr-gpost.*Failed to read vector from stream..*$"
)
def __init__(self, args: CalcFmllrArguments):
super().__init__(args)
self.working_directory = args.working_directory
self.ali_model_path = args.ali_model_path
self.model_path = args.model_path
self.fmllr_options = args.fmllr_options
self.thread_lock = args.thread_lock
def _run(self) -> typing.Generator[str]:
"""Run the function"""
with self.session() as session, thread_logger(
"kalpy.fmllr", self.log_path, job_name=self.job_name
) as fmllr_logger:
fmllr_logger.debug(f"Using acoustic model: {self.ali_model_path}\n")
job: typing.Optional[Job] = session.get(
Job, self.job_name, options=[joinedload(Job.dictionaries), joinedload(Job.corpus)]
)
silence_phones = [
x
for x, in session.query(Phone.mapping_id).filter(
Phone.phone_type.in_([PhoneType.silence, PhoneType.oov])
)
]
for dict_id in job.dictionary_ids:
fmllr_trans_path = job.construct_path(
job.corpus.split_directory, "trans", "scp", dictionary_id=dict_id
)
previous_transform_archive = None
if not fmllr_trans_path.exists():
fmllr_logger.debug("Computing transforms from scratch")
fmllr_trans_path = None
else:
fmllr_logger.debug(f"Updating previous transforms {fmllr_trans_path}")
previous_transform_archive = MatrixArchive(fmllr_trans_path)
spk2utt_path = job.construct_path(
job.corpus.current_subset_directory, "spk2utt", "scp", dictionary_id=dict_id
)
spk2utt = KaldiMapping(list_mapping=True)
spk2utt.load(spk2utt_path)
feature_archive = job.construct_feature_archive(self.working_directory, dict_id)
computer = FmllrComputer(
self.ali_model_path,
silence_phones,
spk2utt=spk2utt,
two_models=self.ali_model_path != self.model_path,
thread_lock=self.thread_lock,
**self.fmllr_options,
)
ali_path = job.construct_path(self.working_directory, "ali", "ark", dict_id)
fmllr_logger.debug(f"Processing {ali_path}")
alignment_archive = AlignmentArchive(ali_path)
temp_trans_path = job.construct_path(
self.working_directory, "trans", "ark", dict_id
)
computer.export_transforms(
temp_trans_path,
feature_archive,
alignment_archive,
previous_transform_archive=previous_transform_archive,
callback=self.callback,
)
feature_archive.close()
del previous_transform_archive
del feature_archive
del alignment_archive
del computer
if fmllr_trans_path is not None:
os.remove(fmllr_trans_path)
os.remove(fmllr_trans_path.with_suffix(".ark"))
trans_archive = MatrixArchive(temp_trans_path)
write_specifier = generate_write_specifier(
job.construct_path(
job.corpus.split_directory, "trans", "ark", dictionary_id=dict_id
),
write_scp=True,
)
writer = BaseFloatMatrixWriter(write_specifier)
for speaker, trans in trans_archive:
writer.Write(str(speaker), trans)
writer.Close()
del trans_archive
os.remove(temp_trans_path)
class FeatureConfigMixin:
"""
Class to store configuration information about MFCC generation
Attributes
----------
feature_type : str
Feature type, defaults to "mfcc"
use_energy : bool
Flag for whether first coefficient should be used, defaults to False
frame_shift : int
number of milliseconds between frames, defaults to 10
snip_edges : bool
Flag for enabling Kaldi's snip edges, should be better time precision
use_pitch : bool
Flag for including pitch in features, defaults to False
low_frequency : int
Frequency floor
high_frequency : int
Frequency ceiling
sample_frequency : int
Sampling frequency
allow_downsample : bool
Flag for whether to allow downsampling, default is True
allow_upsample : bool
Flag for whether to allow upsampling, default is True
uses_cmvn : bool
Flag for whether to use CMVN, default is True
uses_deltas : bool
Flag for whether to use delta features, default is True
uses_splices : bool
Flag for whether to use splices and LDA transformations, default is False
uses_speaker_adaptation : bool
Flag for whether to use speaker adaptation, default is False
fmllr_update_type : str
Type of fMLLR estimation, defaults to "full"
silence_weight : float
Weight of silence in calculating LDA or fMLLR
splice_left_context : int or None
Number of frames to splice on the left for calculating LDA
splice_right_context : int or None
Number of frames to splice on the right for calculating LDA
"""
def __init__(
self,
feature_type: str = "mfcc",
use_energy: bool = False,
frame_shift: int = 10,
frame_length: int = 25,
snip_edges: bool = True,
low_frequency: int = 20,
high_frequency: int = 7800,
sample_frequency: int = 16000,
allow_downsample: bool = True,
allow_upsample: bool = True,
dither: int = 1,
energy_floor: float = 0,
num_coefficients: int = 13,
num_mel_bins: int = 23,
cepstral_lifter: float = 22,
preemphasis_coefficient: float = 0.97,
uses_cmvn: bool = True,
uses_deltas: bool = True,
uses_splices: bool = False,
uses_voiced: bool = False,
adaptive_pitch_range: bool = False,
uses_speaker_adaptation: bool = False,
fmllr_update_type: str = "full",
silence_weight: float = 0.0,
splice_left_context: int = 3,
splice_right_context: int = 3,
use_pitch: bool = False,
use_voicing: bool = False,
use_delta_pitch: bool = False,
min_f0: float = 50,
max_f0: float = 800,
delta_pitch: float = 0.005,
penalty_factor: float = 0.1,
**kwargs,
):
super().__init__(**kwargs)
self.feature_type = feature_type
self.uses_cmvn = uses_cmvn
self.uses_deltas = uses_deltas
self.uses_splices = uses_splices
self.uses_voiced = uses_voiced
self.uses_speaker_adaptation = uses_speaker_adaptation
self.frame_shift = frame_shift
self.export_frame_shift = round(frame_shift / 1000, 4)
self.frame_length = frame_length
self.snip_edges = snip_edges
# MFCC options
self.use_energy = use_energy
self.low_frequency = low_frequency
self.high_frequency = high_frequency
self.sample_frequency = sample_frequency
self.allow_downsample = allow_downsample
self.allow_upsample = allow_upsample
self.dither = dither
self.energy_floor = energy_floor
self.num_coefficients = num_coefficients
self.num_mel_bins = num_mel_bins
self.cepstral_lifter = cepstral_lifter
self.preemphasis_coefficient = preemphasis_coefficient
# fMLLR options
self.fmllr_update_type = fmllr_update_type
self.silence_weight = silence_weight
# Splicing options
self.splice_left_context = splice_left_context
self.splice_right_context = splice_right_context
# Pitch features
self.adaptive_pitch_range = adaptive_pitch_range
self.use_pitch = use_pitch
self.use_voicing = use_voicing
self.use_delta_pitch = use_delta_pitch
self.min_f0 = min_f0
self.max_f0 = max_f0
self.delta_pitch = delta_pitch
self.penalty_factor = penalty_factor
self.normalize_pitch = True
if self.adaptive_pitch_range:
self.min_f0 = 50
self.max_f0 = 1200
self.mfcc_computer = MfccComputer(**self.mfcc_options)
self.pitch_computer = None
if self.use_pitch:
self.pitch_computer = PitchComputer(**self.pitch_options)
@property
def vad_options(self) -> MetaDict:
"""Abstract method for VAD options"""
raise NotImplementedError
@property
def alignment_model_path(self) -> str: # needed for fmllr
"""Abstract method for alignment model path"""
raise NotImplementedError
@property
def model_path(self) -> str: # needed for fmllr
"""Abstract method for model path"""
raise NotImplementedError
@property
def working_directory(self) -> Path:
"""Abstract method for working directory"""
raise NotImplementedError
@property
def corpus_output_directory(self) -> str:
"""Abstract method for working directory of corpus"""
raise NotImplementedError
@property
def data_directory(self) -> str:
"""Abstract method for corpus data directory"""
raise NotImplementedError
@property
def feature_options(self) -> MetaDict:
"""Parameters for feature generation"""
options = {
"type": self.feature_type,
"use_energy": self.use_energy,
"frame_shift": self.frame_shift,
"frame_length": self.frame_length,
"snip_edges": self.snip_edges,
"low_frequency": self.low_frequency,
"high_frequency": self.high_frequency,
"sample_frequency": self.sample_frequency,
"dither": self.dither,
"energy_floor": self.energy_floor,
"num_coefficients": self.num_coefficients,
"num_mel_bins": self.num_mel_bins,
"cepstral_lifter": self.cepstral_lifter,
"preemphasis_coefficient": self.preemphasis_coefficient,
"uses_cmvn": self.uses_cmvn,
"uses_deltas": self.uses_deltas,
"uses_voiced": self.uses_voiced,
"uses_splices": self.uses_splices,
"uses_speaker_adaptation": self.uses_speaker_adaptation,
"use_pitch": self.use_pitch,
"use_voicing": self.use_voicing,
"min_f0": self.min_f0,
"max_f0": self.max_f0,
"delta_pitch": self.delta_pitch,
"penalty_factor": self.penalty_factor,
"silence_weight": self.silence_weight,
"splice_left_context": self.splice_left_context,
"splice_right_context": self.splice_right_context,
}
return options
def calc_fmllr(self) -> None:
"""Abstract method for calculating fMLLR transforms"""
raise NotImplementedError
@property
def fmllr_options(self) -> MetaDict:
"""Options for use in calculating fMLLR transforms"""
return {
"fmllr_update_type": self.fmllr_update_type,
"silence_weight": self.silence_weight,
"acoustic_scale": getattr(self, "acoustic_scale", 0.1),
}
@property
def lda_options(self) -> MetaDict:
"""Options for computing LDA"""
if getattr(self, "acoustic_model", None) is not None:
return self.acoustic_model.lda_options
if getattr(self, "ivector_extractor", None) is not None:
return self.ivector_extractor.lda_options
return {
"splice_left_context": self.splice_left_context,
"splice_right_context": self.splice_right_context,
}
@property
def mfcc_options(self) -> MetaDict:
"""Parameters to use in computing MFCC features."""
if getattr(self, "acoustic_model", None) is not None:
return self.acoustic_model.mfcc_options
if getattr(self, "ivector_extractor", None) is not None:
return self.ivector_extractor.mfcc_options
return {
"use_energy": self.use_energy,
"dither": self.dither,
"energy_floor": self.energy_floor,
"num_coefficients": self.num_coefficients,
"num_mel_bins": self.num_mel_bins,
"cepstral_lifter": self.cepstral_lifter,
"preemphasis_coefficient": self.preemphasis_coefficient,
"frame_shift": self.frame_shift,
"frame_length": self.frame_length,
"low_frequency": self.low_frequency,
"high_frequency": self.high_frequency,
"sample_frequency": self.sample_frequency,
"allow_downsample": self.allow_downsample,
"allow_upsample": self.allow_upsample,
"snip_edges": self.snip_edges,
}
@property
def pitch_options(self) -> MetaDict:
"""Parameters to use in computing pitch features."""
if getattr(self, "acoustic_model", None) is not None:
return self.acoustic_model.pitch_options
if getattr(self, "ivector_extractor", None) is not None:
return self.ivector_extractor.pitch_options
use_pitch = self.use_pitch
use_voicing = self.use_voicing
use_delta_pitch = self.use_delta_pitch
normalize = self.normalize_pitch
options = {
"frame_shift": self.frame_shift,
"frame_length": self.frame_length,
"min_f0": self.min_f0,
"max_f0": self.max_f0,
"sample_frequency": self.sample_frequency,
"penalty_factor": self.penalty_factor,
"delta_pitch": self.delta_pitch,
"snip_edges": self.snip_edges,
"add_normalized_log_pitch": False,
"add_delta_pitch": False,
"add_pov_feature": False,
}
if use_pitch:
options["add_normalized_log_pitch"] = normalize
options["add_raw_log_pitch"] = not normalize
options["add_delta_pitch"] = use_delta_pitch
options["add_pov_feature"] = use_voicing
return options
class VadConfigMixin(FeatureConfigMixin):
"""
Abstract mixin class for performing voice activity detection
Parameters
----------
use_energy: bool
Flag for using the first coefficient of MFCCs
energy_threshold: float
Energy threshold above which a frame will be counted as voiced
energy_mean_scale: float
Proportion of the mean energy of the file that should be added to the energy_threshold
See Also
--------
:class:`~montreal_forced_aligner.corpus.features.FeatureConfigMixin`
For feature generation parameters
"""
def __init__(self, energy_threshold=5.5, energy_mean_scale=0.5, **kwargs):
super().__init__(**kwargs)
self.energy_threshold = energy_threshold
self.energy_mean_scale = energy_mean_scale
@property
def vad_options(self) -> MetaDict:
"""Options for performing VAD"""
return {
"energy_threshold": self.energy_threshold,
"energy_mean_scale": self.energy_mean_scale,
}
class IvectorConfigMixin(VadConfigMixin):
"""
Mixin class for ivector features
Parameters
----------
ivector_dimension: int
Dimension of ivectors
num_gselect: int
Gaussian-selection using diagonal model: number of Gaussians to select
posterior_scale: float
Scale on the acoustic posteriors, intended to account for inter-frame correlations
min_post : float
Minimum posterior to use (posteriors below this are pruned out)
max_count: int
The use of this option (e.g. --max-count 100) can make iVectors more consistent for different lengths of
utterance, by scaling up the prior term when the data-count exceeds this value. The data-count is after
posterior-scaling, so assuming the posterior-scale is 0.1, --max-count 100 starts having effect after 1000
frames, or 10 seconds of data.
See Also
--------
:class:`~montreal_forced_aligner.corpus.features.FeatureConfigMixin`
For feature generation parameters
"""
def __init__(
self,
num_gselect: int = 20,
posterior_scale: float = 1.0,
min_post: float = 0.025,
max_count: int = 100,
**kwargs,
):
super().__init__(**kwargs)
self.ivector_dimension = config.IVECTOR_DIMENSION
self.num_gselect = num_gselect
self.posterior_scale = posterior_scale
self.min_post = min_post
self.max_count = max_count
self.normalize_pitch = False
@abstractmethod
def extract_ivectors(self) -> None:
"""Abstract method for extracting ivectors"""
...
@property
def ivector_options(self) -> MetaDict:
"""Options for ivector training and extracting"""
return {
"num_gselect": self.num_gselect,
"posterior_scale": self.posterior_scale,
"min_post": self.min_post,
"silence_weight": self.silence_weight,
"max_count": self.max_count,
"ivector_dimension": self.ivector_dimension,
}
class ExtractIvectorsFunction(KaldiFunction):
"""
Multiprocessing function for extracting ivectors.
See Also
--------
:meth:`.IvectorCorpusMixin.extract_ivectors`
Main function that calls this function in parallel
:meth:`.IvectorCorpusMixin.extract_ivectors_arguments`
Job method for generating arguments for this function
:kaldi_src:`ivector-extract`
Relevant Kaldi binary
:kaldi_src:`gmm-global-get-post`
Relevant Kaldi binary
:kaldi_src:`weight-silence-post`
Relevant Kaldi binary
:kaldi_src:`weight-post`
Relevant Kaldi binary
:kaldi_src:`post-to-weights`
Relevant Kaldi binary
Parameters
----------
args: :class:`~montreal_forced_aligner.corpus.features.ExtractIvectorsArguments`
Arguments for the function
"""
def __init__(self, args: ExtractIvectorsArguments):
super().__init__(args)
self.ivector_options = args.ivector_options
self.ivector_extractor_path = args.ivector_extractor_path
self.ivectors_scp_path = args.ivectors_scp_path
self.dubm_path = args.dubm_path
def _run(self):
"""Run the function"""
if os.path.exists(self.ivectors_scp_path):
return
with self.session() as session, thread_logger(
"kalpy.ivector", self.log_path, job_name=self.job_name
):
job: Job = (
session.query(Job)
.options(joinedload(Job.corpus, innerjoin=True))
.filter(Job.id == self.job_name)
.first()
)
ivector_ark_path = self.ivectors_scp_path.with_suffix(".ark")
feature_archive = job.construct_feature_archive(job.corpus.current_subset_directory)
ivector_extractor = IvectorExtractor(
self.dubm_path,
self.ivector_extractor_path,
acoustic_weight=self.ivector_options["posterior_scale"],
max_count=self.ivector_options["max_count"],
num_gselect=self.ivector_options["num_gselect"],
min_post=self.ivector_options["min_post"],
)
ivector_extractor.export_ivectors(
ivector_ark_path, feature_archive, write_scp=True, callback=self.callback
)
class ExportIvectorsFunction(KaldiFunction):
"""
Multiprocessing function to compute voice activity detection
See Also
--------
:meth:`.AcousticCorpusMixin.compute_vad`
Main function that calls this function in parallel
:meth:`.AcousticCorpusMixin.compute_vad_arguments`
Job method for generating arguments for this function
:kaldi_src:`compute-vad`
Relevant Kaldi binary
Parameters
----------
args: :class:`~montreal_forced_aligner.corpus.features.VadArguments`
Arguments for the function
"""
def __init__(self, args: ExportIvectorsArguments):
super().__init__(args)