-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathaudio_analysis.py
executable file
·2042 lines (1642 loc) · 69 KB
/
audio_analysis.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
#-*- coding: utf-8 -*-
# --------------------------------------------------------------------#
# --------------------------------------------------------------------#
# ---------- Made by pablo Arias @ircam on 11/2015
# ---------- Copyright (c) 2018 CREAM Lab // CNRS / IRCAM / Sorbonne Universite
# ----------
# ---------- Analyse audio and return sound features
# ----------
# --------------------------------------------------------------------#
# --------------------------------------------------------------------#
from __future__ import absolute_import
from __future__ import print_function
import os
import glob
from bisect import bisect
import soundfile
import pandas as pd
import numpy as np
from super_vp_commands import generate_LPC_analysis
from conversions import lin2db, get_file_without_path
from six.moves import range
from functools import reduce
import contextlib
import collections
import parselmouth
from parselmouth.praat import call
# --------------------------------------------------------------------#
# --------------------------------------------------------------------#
# ----------------- Spectral centroid
# -----------------
# --------------------------------------------------------------------#
def centroid(x, axis):
sum_x = np.sum(x)
if sum_x == 0:
return np.nan # Return NaN or an appropriate value to handle the divide-by-zero case
return np.sum(x * axis) / sum_x
def get_spectral_centroid(audio_file, window_size = 256, noverlap = 0, plot_specgram = False):
"""
parameters:
audio_file : file to anlayse
window_size : window size for FFT computing
plot_specgram : Do youw ant to plot specgram of analysis?
returns : time series with the spectral centroid and the time
warning :
this function only works for mono files
"""
#imports
import glob
from scipy import signal
#Read audio file
sound_in, fs = soundfile.read(audio_file)
#compute gaussian spectrogram
f, t, Sxx = signal.spectrogram(sound_in , fs , nperseg = window_size
, noverlap = noverlap , scaling ='spectrum'
, mode = 'magnitude'
)
#plot specgram
if plot_specgram:
plt.figure()
fig, ax = plt.subplots()
plt.pcolormesh(t, f, Sxx, cmap = 'nipy_spectral')
ax.axis('tight')
plt.ylabel('Frequency [Hz]')
plt.xlabel('Time [sec]')
plt.title("Normal FFT of audio signal")
plt.show()
centroid_list = []
for spectrum in np.transpose(Sxx):
centroid_list.append(centroid(spectrum, f))
return t, centroid_list
def get_mean_spectral_centroid_when_sound(audio_file, RMS_threshold = -55, window_size = 512):
"""
Get spectral centroid of audio file only when signal level is above amplitude threshold, and average centroid across these regions
Parameters:
audio_file : file to anlayse
RMS_threshold : min value of RMS to know if there is sound
window_size : window_size for the RMS compute
returns : spectral centroid when sound
Warning :
this function only works for mono files
"""
from bisect import bisect_left
t, centroid_list = get_spectral_centroid(audio_file, window_size = window_size, noverlap = 0, plot_specgram = False)
intervals = get_intervals_of_sound(audio_file, RMS_threshold = RMS_threshold, window_size = window_size)
centroid_means = []
for interval in intervals:
begin = bisect_left(t, interval[0])
end = bisect_left(t, interval[1])
local_mean = np.nanmean(centroid_list[begin:end])
centroid_means.append(local_mean)
return np.nanmean(centroid_means)
def get_intervals_of_sound(audio_file, RMS_threshold = -50, window_size = 512):
"""
parameters:
audio_file : file to anlayse
RMS_treshold : min value of RMS to know if there is sound
window_size : window_size for the RMS compute
returns : time series with the RMS and the time
warning :
this function only works for mono files
"""
t, rmss = get_RMS_over_time(audio_file, window_size = window_size)
inside_sound = False
intervals = []
for i in range(len(rmss)):
if inside_sound:
if rmss[i] < RMS_threshold:
end = t[i]
intervals.append([begin, end])
inside_sound = False
else:
if rmss[i] > RMS_threshold:
begin = t[i]
inside_sound = True
return intervals
def get_RMS_over_time(audio_file, window_size = 1024, in_db = True):
"""
parameters:
audio_file : file to anlayse
window_size : window size for FFT computing
returns : time series with the RMS and the time
warning :
this function only works for mono files
"""
import glob
from scipy import signal
import numpy as np
#Read audio file
sound_in, fs = soundfile.read(audio_file)
begin = 0
values = []
time_tags = []
while (begin + window_size) < len(sound_in):
data = sound_in[begin : begin + window_size]
time_tag = (begin + (window_size / 2)) / float(fs)
values.append(get_rms_from_data(data, in_db = in_db))
time_tags.append(time_tag)
begin = begin + window_size
return time_tags, values
def get_mean_spectral_centroid(audio_file, window_size = 256, noverlap = 0):
import numpy as np
#compute centroid
t, centroid = get_spectral_centroid_over_time(audio_file, window_size = 256, noverlap = 0, plot_specgram = False)
return np.mean(centroid)
def get_spectral_centroid_over_time(audio_file, window_size = 256, noverlap = 0, plot_specgram = False):
"""
parameters:
audio_file : file to anlayse
window_size : window size for FFT computing
plot_specgram : Do youw ant to plot specgram of analysis?
returns : time series with the spectral centroid and the time
warning :
this function only works for mono files
"""
import glob
from scipy import signal
#Read audio file
sound_in, fs = soundfile.read(audio_file)
#compute gaussian spectrogram
f, t, Sxx = signal.spectrogram(sound_in , fs , nperseg = window_size
, noverlap = noverlap , scaling ='spectrum'
, mode = 'magnitude'
)
#plot specgram
if plot_specgram:
plt.figure()
fig, ax = plt.subplots()
plt.pcolormesh(t, f, Sxx, cmap = 'nipy_spectral')
ax.axis('tight')
plt.ylabel('Frequency [Hz]')
plt.xlabel('Time [sec]')
plt.title("Normal FFT of audio signal")
plt.show()
centroid_list = []
for spectrum in np.transpose(Sxx):
centroid_list.append(centroid(spectrum, f))
return t, centroid_list
# Extract_ts_of_pitch_praat
def Extract_ts_of_pitch_praat(Fname
, time_step=0.001
, pitch_floor = 75
, pitch_ceiling = 350
, max_nb_candidates=15
, accuracy = 0
, silence_threshold = 0.03
, voicing_threshold = 0.45
, octave_cost = 0.01
, octave_jump_cost = 0.35
, voiced_unvoiced_cost = 0.14
, harmonicity_threshold = None
):
"""
Extract pitch time series using praat for the file Fname
Input:
Fname : input file name
time_step : time step to use for the analysis in seconds
pitch_floor : minimul pitch posible, in HZ
pitch_ceiling : maximum pitch posible, in HZ
accuracy : on or off
See parameters here : https://www.fon.hum.uva.nl/praat/manual/Sound__To_Pitch__raw_ac____.html
Also, use harmonicity threshold (from 0 to 1) to clean pitch estimation values.
Return: times, f0
"""
import subprocess
import os
import parselmouth
Fname = os.path.abspath(Fname)
#execture script with parselmouth
script = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'ts_pitch.praat')
_, out = parselmouth.praat.run_file(script
, Fname
, str(time_step)
, str(pitch_floor)
, str(max_nb_candidates)
, str(accuracy)
, str(silence_threshold)
, str(voicing_threshold)
, str(octave_cost)
, str(octave_jump_cost)
, str(voiced_unvoiced_cost)
, str(pitch_ceiling)
, capture_output=True
)
#Parse script
out = out.splitlines()
times = []
f0s = []
for line in out:
line = line.split()
times.append(line[0])
f0s.append(line[1])
f0s = [np.nan if item == u'--undefined--' else float(item) for item in f0s]
#If harmonicity threshold is defined, clean with harm thresh
if harmonicity_threshold:
times = [float(x) for x in times]
f0s = [float(x) for x in f0s]
from bisect import bisect_left
harm_time, harm_vals = get_harmonicity_ts(Fname, time_step=time_step, normalise=True)
cleaned_vals = []
cleaned_times = []
for index, time in enumerate(times):
idx_harm = bisect_left(harm_time, time)
if harmonicity_threshold < harm_vals[idx_harm-1]:
cleaned_vals.append(f0s[index])
cleaned_times.append(time)
times, f0s = cleaned_times, cleaned_vals
return times, f0s
def get_mean_pitch_praat(Fname, time_step=0.001 , pitch_floor = 75, pitch_ceiling = 350, harmonicity_threshold = None):
"""
Extract mean pitch using praat for the file Fname
Input:
time_step : time step to use for the analysis in seconds - 0.0 : auto
pitch_floor : minimul pitch posible, in HZ
pitch_ceiling : maximum pitch posible, in HZ
Output:
mean pitch
"""
times, f0s = Extract_ts_of_pitch_praat(Fname, time_step=time_step , pitch_floor = pitch_floor, pitch_ceiling = pitch_ceiling, harmonicity_threshold=harmonicity_threshold)
return np.nanmean(f0s)
def get_pitch_std(Fname, time_step=0.001 , pitch_floor = 75, pitch_ceiling = 350, harmonicity_threshold=None):
times, f0s = Extract_ts_of_pitch_praat(Fname=Fname, time_step=time_step , pitch_floor = pitch_floor, pitch_ceiling = pitch_ceiling, harmonicity_threshold=harmonicity_threshold)
return np.nanstd(f0s)
def get_pulse_features(sound, f0min=75, f0max=450, time_step=0.01, silence_threshold=0.1, periods_per_window=1.0, start=0, stop=0, period_floor=0.0001, period_ceiling = 0.02, max_period_factor=1.3):
shim_df = get_shimmer(sound
, f0min = f0min
, f0max = f0max
)
hnr_df = get_hnr(sound
, time_step = time_step
, f0min = f0min
, silence_threshold = silence_threshold
, periods_per_window = periods_per_window
, start = start
, stop = stop
)
jitt_df = get_jitter(sound
, f0min = f0min
, f0max = f0max
, start = start
, stop = stop
, period_floor = period_floor
, period_ceiling = period_ceiling
, max_period_factor = max_period_factor
)
pulses_df = jitt_df.merge(shim_df , on ="sound")
pulses_df = pulses_df.merge(hnr_df , on ="sound")
return pulses_df
# get_harmonicity_ts
def get_harmonicity_ts(file, time_step, min_pitch = 75, silence_threshold = 0.1, periods_per_window = 4.5, normalise=True):
"""
Use Parselmouth to extract harmonicity of file
See parameter explanation here : https://www.fon.hum.uva.nl/praat/manual/Sound__To_Harmonicity__ac____.html
"""
import numpy as np
import parselmouth
from parselmouth.praat import call
#Extract harmonicity with parselmouth
sound = parselmouth.Sound(file)
harm_obj = call(sound, "To Harmonicity (cc)...", time_step, min_pitch, silence_threshold, periods_per_window)
duration = harm_obj.duration
harm_time = np.arange(0, duration, time_step)
harm_vals = [harm_obj.get_value(i) for i in harm_time]
if normalise:
#Normalise between 0 and 1 using -200 as the lowest value
for cpt in range(len(harm_vals)):
if harm_vals[cpt] < -200:
harm_vals[cpt] = -200
if harm_vals[cpt] > 1:
harm_vals[cpt] = 1
for cpt in range(len(harm_vals)):
harm_vals[cpt] = (harm_vals[cpt] + 201) / 201
return harm_time, harm_vals
#from : https://osf.io/qe9k4/
def get_jitter(sound, f0min=75, f0max=450, start=0, stop=0, period_floor=0.0001, period_ceiling=0.02, max_period_factor=1.3):
"""
start and stop = 0 means analyse all sound. In seconds.
period floor : In seconds. The shortest possible interval that will be used in the computation of jitter, in seconds.
If an interval is shorter than this, it will be ignored in the computation of jitter (and the previous and next intervals will not be regarded as consecutive).
This setting will normally be very small, say 0.1 ms.
period ceiling : In seconds. The longest possible interval that will be used in the computation of jitter, in seconds.
If an interval is longer than this, it will be ignored in the computation of jitter (and the previous and next intervals will not be regarded as consecutive). For example, if the minimum frequency of periodicity is 50 Hz, set this setting to 0.02 seconds; intervals longer than that could be regarded as voiceless stretches and will be ignored in the computation.
Maximum period factor : the largest possible difference between consecutive intervals that will be used in the computation of jitter.
If the ratio of the durations of two consecutive intervals is greater than this, this pair of intervals will be ignored in the computation of jitter (each of the intervals could still take part in the computation of jitter in a comparison with its neighbour on the other side).
Check the documentation here : https://www.fon.hum.uva.nl/praat/manual/PointProcess__Get_jitter__local____.html
"""
df_aux = pd.DataFrame()
praat_sound = parselmouth.Sound(sound) # read the sound
pointProcess = call(praat_sound, "To PointProcess (periodic, cc)", f0min, f0max)
localJitter = call(pointProcess, "Get jitter (local)" , start, stop, period_floor, period_ceiling, max_period_factor)
localabsoluteJitter = call(pointProcess, "Get jitter (local, absolute)" , start, stop, period_floor, period_ceiling, max_period_factor)
rapJitter = call(pointProcess, "Get jitter (rap)" , start, stop, period_floor, period_ceiling, max_period_factor)
ppq5Jitter = call(pointProcess, "Get jitter (ppq5)" , start, stop, period_floor, period_ceiling, max_period_factor)
ddpJitter = call(pointProcess, "Get jitter (ddp)" , start, stop, period_floor, period_ceiling, max_period_factor)
#Collect data
df_aux["sound"] = [sound]
df_aux["localJitter"] = [localJitter]
df_aux["localabsoluteJitterrapJitter"] = [localabsoluteJitter]
df_aux["rapJitter"] = [rapJitter]
df_aux["ppq5Jitter"] = [ppq5Jitter]
df_aux["ddpJitter"] = [ddpJitter]
return df_aux
def get_hnr(sound, time_step=0.01, f0min=75, silence_threshold=0.1, periods_per_window=1.0, start=0, stop=0):
"""
if both start and stop = 0, compute descriptor for all sound
"""
praat_sound = parselmouth.Sound(sound) # read the sound
harmonicity = call(praat_sound, "To Harmonicity (cc)", time_step, f0min, silence_threshold, periods_per_window)
hnr = call(harmonicity, "Get mean" , start, stop)
df_aux = pd.DataFrame()
df_aux["sound"] = [sound]
df_aux["hnr"] = [hnr]
return df_aux
def get_shimmer(sound, f0min = 74, f0max = 350):
praat_sound = parselmouth.Sound(sound) # read the sound
pointProcess = call(praat_sound, "To PointProcess (periodic, cc)", f0min, f0max)
localShimmer = call([praat_sound, pointProcess], "Get shimmer (local)" , 0, 0, 0.0001, 0.02, 1.3, 1.6)
localdbShimmer = call([praat_sound, pointProcess], "Get shimmer (local_dB)" , 0, 0, 0.0001, 0.02, 1.3, 1.6)
apq3Shimmer = call([praat_sound, pointProcess], "Get shimmer (apq3)" , 0, 0, 0.0001, 0.02, 1.3, 1.6)
aqpq5Shimmer = call([praat_sound, pointProcess], "Get shimmer (apq5)" , 0, 0, 0.0001, 0.02, 1.3, 1.6)
apq11Shimmer = call([praat_sound, pointProcess], "Get shimmer (apq11)" , 0, 0, 0.0001, 0.02, 1.3, 1.6)
ddaShimmer = call([praat_sound, pointProcess], "Get shimmer (dda)" , 0, 0, 0.0001, 0.02, 1.3, 1.6)
df_aux = pd.DataFrame()
df_aux["sound"] = [sound]
df_aux["localShimmer"] = [localShimmer]
df_aux["localdbShimmer"] = [localdbShimmer]
df_aux["apq3Shimmer"] = [apq3Shimmer]
df_aux["aqpq5Shimmer"] = [aqpq5Shimmer]
df_aux["apq11Shimmer"] = [apq11Shimmer]
df_aux["ddaShimmer"] = [ddaShimmer]
return df_aux
# --------------------------------------------------------------------#
# --------------------------------------------------------------------#
# ----------------- All sort of ----------------------#
# ----------------- Formant related functions ----------------------#
# --------------------------------------------------------------------#
# --------------------------------------------------------------------#
def formant_from_audio(audio_file, nb_formants, ana_winsize=512):
"""
parameters:
audio_file : file to anlayse
nb_formants : number of formants to compute and return
This function returns an array of pandas data bases with
the formants inside (Frequency, Amplitude, Bandwith and Saliance).
warning :
this function only works for mono files
"""
#handle paths to create sdif analysis file
if os.path.dirname(audio_file) == "":
file_tag = get_file_without_path(audio_file)
formant_analysis = file_tag + "formant.sdif"
else:
file_tag = get_file_without_path(audio_file)
formant_analysis = os.path.dirname(audio_file)+ "/" + file_tag + "formant.sdif"
#generate svp sdif analysis and then read formants from sdif
from super_vp_commands import generate_formant_analysis
from parse_sdif import formant_from_sdif
generate_formant_analysis(audio_file, formant_analysis, nb_formants = nb_formants, ana_winsize = ana_winsize)
formants = formant_from_sdif(formant_analysis)
os.remove(formant_analysis)
return formants
def get_tidy_formants(audio_file, nb_formants=5, ana_winsize=512, add_harmonicity=False):
"""
Convert formant_from_audio data to a tidy dataframe
parameters:
audio_file : file to anlayse
nb_formants : number of formants to compute and return
ana_winsize : window size for the LPC estimation
add_harmonicity: Add harmonicity values to dataframe
"""
formants = formant_from_audio(audio_file, nb_formants, ana_winsize)
#tidy up formants
all_formants = pd.DataFrame()
for cpt in range(1, len(formants)+1):
formant = formants[cpt-1]
formant["Formant"] = ["F" + str(cpt) for i in range(len(formant))]
#all_formants = all_formants.append(formant)
all_formants = pd.concat([all_formants, formant])
all_formants.index.names = ['time']
#Add harmonicity row to formant estimation
if add_harmonicity:
def add_harm(row, *args):
from bisect import bisect
f0times = args[0]
f0harm = args[1]
formant_time = row["time"]
index = bisect(f0times, formant_time)
harm = f0harm[index-1]
return harm
harm_time, harm_vals = get_harmonicity_ts(audio_file, time_step=time_step, normalise=True)
all_formants = all_formants.reset_index()
all_formants["harmonicity"] = all_formants.apply(add_harm, axis=1, args=(harm_time, harm_vals,))
#return formants
return all_formants
def mean_formant_from_audio(audio_file, nb_formants, use_t_env = True, ana_winsize = 512, destroy_sdif_after_analysis = True):
"""
parameters:
audio_file : file to anlayse
nb_formants : number of formants to compute and return
use_t_env : Use true envelope for formant analysis
This function returns an array of pandas data bases with
the formants inside (Frequency, Amplitude, Bandwith and Saliance).
warning :
this function only works for mono files
"""
#Handle paths to create sdif analysis file
formant_tag = "_formant.sdif"
if os.path.dirname(audio_file) == "":
file_tag = get_file_without_path(audio_file)
formant_analysis = file_tag + formant_tag
else:
file_tag = get_file_without_path(audio_file)
formant_analysis = os.path.dirname(audio_file)+ "/" + file_tag + formant_tag
#Generate sdif analysis file
from super_vp_commands import generate_formant_analysis, generate_tenv_formant_analysis
from parse_sdif import mean_formant_from_sdif
if use_t_env:
generate_tenv_formant_analysis(audio_file, analysis = formant_analysis, nb_formants = 5, wait = True, ana_winsize = ana_winsize)
else:
generate_formant_analysis(audio_file, formant_analysis, nb_formants = nb_formants, ana_winsize = ana_winsize)
#Get mean formant from sdif analysis file
mean_formants = mean_formant_from_sdif(formant_analysis)
#destroy the sdif file generated if specified by parameter
if destroy_sdif_after_analysis:
os.remove(formant_analysis)
#Return mean formants
return mean_formants
def get_formant_data_frame(audio_file, nb_formants = 5 ,t_env_or_lpc = "lpc", destroy_sdif_after_analysis = True, ana_winsize = 512):
"""
parameters:
audio_file_name : pandas data frame with a formant
t_env_or_lpc : analysis kind
returns a tidy, good looking, dataframe with the formants' time series
warning :
this function only works for mono files
"""
from super_vp_commands import generate_formant_analysis, generate_tenv_formant_analysis
from parse_sdif import formant_from_sdif
#Perform formant analysis either with lpc or t_env
analysis_name = "formant_generated_analysis_X2345.sdif"
if t_env_or_lpc == "lpc":
generate_formant_analysis(audio_file, analysis = analysis_name, nb_formants = nb_formants, wait = True, ana_winsize = ana_winsize)
elif t_env_or_lpc == "t_env":
generate_tenv_formant_analysis(audio_file, analysis = analysis_name, nb_formants = nb_formants, wait = True, ana_winsize = ana_winsize)
else:
print("t_env_or_lpc should be either t_env or lpc")
formants = formant_from_sdif(analysis_name)
#parse sdif
frequencies, amplitudes, bandwidths, Saliances = formant_dataframe_to_arrays(formants)
#formant to data frame
formants_df = pd.DataFrame()
formant_names = ["F1", "F2", "F3", "F4", "F5"]
for i in range(nb_formants):
formant = pd.DataFrame()
formant_name = formant_names[i]
frequency = frequencies[i].to_frame("frequency")
amplitude = amplitudes[i].to_frame("amplitude")
bandwidth = bandwidths[i].to_frame("bandwidth")
salience = Saliances[i].to_frame("salience")
dfs = [frequency, amplitude, bandwidth, salience ]
formant = reduce(lambda left,right: pd.merge(left,right,right_index=True, left_index=True), dfs)
formant["Formant"] = [formant_name for i in range(len(formant))]
formants_df = pd.concat([formants_df, formant])
formants_df.index = formants_df.index.rename("time")
#destroy the sdif file generated if specified by parameter
if destroy_sdif_after_analysis:
os.remove(analysis_name)
return formants_df
def formant_dataframe_to_arrays(formants):
"""
parameters:
formants : pandas data frame with a formant
returns the formant Frequency, Amplitude, Bandwith and Saliance
as separate variables.
warning :
this function only works for mono files
"""
frequency = []
amplitude = []
bandwith = []
Saliance = []
for formant in formants:
frequency.append(formant['Frequency'])
amplitude.append(formant['Amplitude'])
bandwith.append(formant['Bw'])
Saliance.append(formant['Saliance'])
return frequency, amplitude, bandwith, Saliance
#get formant time series with praat
def get_formant_ts_praat(audio_file, time_step=0.001, window_size=0.1, nb_formants=5, max_formant_freq=5500, pre_emph=50.0, add_harmonicity=False):
"""
parameters:
audio_file : mono audio file PATH to be analysed, you have to give the ABSOLUTE PATH
time_step : Time step in seconds
window_size : Window Length this is useful for praat
nb_formants : Number of formants to compute
max_formant_freq : maximum formant frequency to use in the estimation
Pre emphasis from Hz : this is a praat parameter for formant estimation, check the get formant function praat's documentation
returns
Two beautiful dataframes, one with the frequnecies and one with the bandwidths
"""
#call praat to do the analysis
import subprocess
import os
#Take the absolulte path
audio_file = os.path.abspath(audio_file)
script = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'ts_formants.praat')
_, out = parselmouth.praat.run_file(script, audio_file, str(time_step) , str(nb_formants), str(max_formant_freq), str(window_size), str(pre_emph), capture_output=True)
content = out.splitlines()
#parse and organize praat's output
freqs_df = pd.DataFrame()
bws_df = pd.DataFrame()
for line in content:
line = [ np.nan if x == u'--undefined--' else float(x) for x in line.split()]
frequency = {}
bandwidth = {}
for index in range(0,nb_formants):
frequency['F'+str(index+1)] = line[index*2+1]
bandwidth['F'+str(index+1)] = line[index*2+2]
freq_df = pd.DataFrame(frequency, index=[line[0]])
bw_df = pd.DataFrame(bandwidth, index=[line[0]])
freqs_df = pd.concat([freqs_df, freq_df])
bws_df = pd.concat([bws_df, bw_df])
#Clean dataframes
freqs_df = freqs_df.dropna()
bws_df = bws_df.dropna()
freqs_df = freqs_df.stack().to_frame("Frequency")
freqs_df.index = freqs_df.index.rename(["time", "Formant"])
bws_df = bws_df.stack().to_frame("Bandwidth")
bws_df.index = bws_df.index.rename(["time", "Formant"])
#Add harmonicity row to formant estimation with super vp if harmonicty flag is on
if add_harmonicity:
def add_harm(row, *args):
from bisect import bisect
f0times = args[0]
f0harm = args[1]
formant_time = row["time"]
index = bisect(f0times, formant_time)
harm = f0harm[index-1]
return harm
#Could use praat here to do this
harm_time, harm_vals = get_harmonicity_ts(audio_file, time_step=time_step, normalise=True)
#Add harmonicity to bandwidth
bws_df = bws_df.reset_index()
bws_df["harmonicity"] = bws_df.apply(add_harm, axis=1, args=(harm_time, harm_vals,))
bws_df = bws_df.set_index("time")
#Add harmonicity to frequency
freqs_df = freqs_df.reset_index()
freqs_df["harmonicity"] = freqs_df.apply(add_harm, axis=1, args=(harm_time, harm_vals,))
freqs_df = freqs_df.set_index("time")
#Return frequencies and bandwidths dataframes
return freqs_df, bws_df
def get_mean_formant_praat_harmonicity(audio_file, time_step=0.001, window_size=0.1, nb_formants=5, max_formant_freq=5500, pre_emph=50.0, harmonicity_threshold=None, formant_method='mean'):
"""
get mean formant with praat, but exclucding all values under a certain harmonicity threshold
(if harmonicity_threshold is defined, if None, just compute mean of time series)
It's not recomended to use this function without the harmonicity threshold.
To keep only harmonic sounds use a threshold > 0.85
Input:
time_step: The time step to estimate the formants (this is passed to Praat)
window_size: The window size of the formant analysis IN SECONDS (this is passed to Praat)
nb_formants: Number of formants to estimate (this is passed to Praat)
max_formant_freq: Maximum formant frequency available, this is an important praat parameter
(5500 usually works well for female voices)
Check praat's documentation to know more
pre_emph: pre emphasis: check praat documentation on formant estimation
harmonicity_threshold: harmonicity threshold to exclude all the values below a certain harmonic threshold
formant_method: the method to use to mean across formants. Either 'mean' or 'median' .
Output;
Dataframe with mean formant frequencies and bandwidths
"""
if not harmonicity_threshold:
#Get mean formant
freqs_df, bws_df = get_formant_ts_praat(audio_file, time_step = time_step
, window_size = window_size
, nb_formants = nb_formants
, max_formant_freq = max_formant_freq
, pre_emph = pre_emph
, add_harmonicity = False
)
else:
freqs_df, bws_df = get_formant_ts_praat(audio_file, time_step = time_step
, window_size = window_size
, nb_formants = nb_formants
, max_formant_freq = max_formant_freq
, pre_emph = pre_emph
, add_harmonicity = True
)
freqs_df = freqs_df.loc[freqs_df["harmonicity"]>harmonicity_threshold]
bws_df = bws_df.loc[bws_df["harmonicity"]>harmonicity_threshold]
if formant_method=='median':
mean_bws_df = bws_df.reset_index().groupby(["Formant"]).median().reset_index()
bws_std_df = bws_df.reset_index().groupby(["Formant"]).std()
bws_std_df.drop(["time"], axis=1, inplace=True)
bws_std_df.columns = [x+"_std" for x in bws_std_df.columns]
bws_std_df.reset_index(inplace=True)
bws_df = mean_bws_df.merge(bws_std_df, on = ["Formant"])
#frequencies
mean_freqs_df = freqs_df.reset_index().groupby(["Formant"]).median().reset_index()
freqs_std_df = freqs_df.reset_index().groupby(["Formant"]).std()
freqs_std_df.drop(["time"], axis=1, inplace=True)
freqs_std_df.columns = [x+"_std" for x in freqs_std_df.columns]
freqs_std_df.reset_index(inplace=True)
freqs_df = mean_freqs_df.merge(freqs_std_df, on = ["Formant"])
elif formant_method=='mean':
mean_bws_df = bws_df.reset_index().groupby(["Formant"]).mean().reset_index()
bws_std_df = bws_df.reset_index().groupby(["Formant"]).std()
bws_std_df.drop(["time"], axis=1, inplace=True)
bws_std_df.columns = [x+"_std" for x in bws_std_df.columns]
bws_std_df.reset_index(inplace=True)
bws_df = mean_bws_df.merge(bws_std_df, on = ["Formant"])
#frequencies
mean_freqs_df = freqs_df.reset_index().groupby(["Formant"]).mean().reset_index()
freqs_std_df = freqs_df.reset_index().groupby(["Formant"]).std()
freqs_std_df.drop(["time"], axis=1, inplace=True)
freqs_std_df.columns = [x+"_std" for x in freqs_std_df.columns]
freqs_std_df.reset_index(inplace=True)
freqs_df = mean_freqs_df.merge(freqs_std_df, on = ["Formant"])
else:
raise ValueError("formant_method should be either 'mean' or 'median'")
return freqs_df, bws_df
#Extract mean formant with praat
def get_mean_formant_praat(Fname):
"""
Fname : file name to analyse
get mean formants with praat script (mean is computed inside praat)
"""
import subprocess
import os
Fname = os.path.abspath(Fname)
script = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'formants_mean.praat')
_, x = parselmouth.praat.run_file(script, Fname, capture_output=True)
Title, F1, F2, F3, F4, F5 = x.splitlines()
return float(F1), float(F2), float(F3), float(F4), float(F5)
#Extract mean formant with praat
def get_mean_tidy_formant_praat(Fname):
"""
Fname : file name to analyse
return mean formant values in dataframe
"""
import subprocess
import os
nb_formants = 5 # TODO parameterize this to Praat
formant_tags = ["F"+str(i) for i in range(1, nb_formants+1)]
formants = get_mean_formant_praat(Fname)
data = {'Formant': formant_tags, "Frequency": formants}
return pd.DataFrame.from_dict(data)
def get_formant_dispersion(Fname, nb_formants_fd=5
, time_step=0.001
, window_size=0.1
, nb_formants=5
, max_formant_freq=5500
, pre_emph=50.0
, harmonicity_threshold=None
, formant_method='mean'
):
"""
Inputs:
Fname : name of the file to use
nb_formants_fd : nuùmber of formants to use in the computation of formant dispersion
harmonicity_threshold : harmonicty threshold to exclude parts of the sound whenc omputing mean formant frequency
(between 0 and 1 : 1 is very harmonic, 0 is unharmonic)
nb_formants : number of formants to estimate
Check the help from get_mean_formant_praat_harmonicity to see other detailed parameters
Output:
Formant dispersion
Compute and return formant dispersion Following Fitch 1997 JASA Formula
"""
#Get formant frequencies
df, db = get_mean_formant_praat_harmonicity(Fname
, time_step = time_step
, window_size = window_size
, nb_formants = nb_formants
, max_formant_freq = max_formant_freq
, pre_emph = pre_emph
, harmonicity_threshold = harmonicity_threshold
, formant_method = formant_method
)
formants = df["Frequency"].values
#compute formant dispersion
fd = 0
for i in range(1, nb_formants_fd):
fd = fd + formants[i] - formants[i-1]
fd = fd / (nb_formants_fd -1)
#return formant dispersion
return fd
def estimate_vtl(Fname , speed_of_sound = 335
, time_step = 0.001
, window_size = 0.1
, nb_formants = 5
, max_formant_freq = 5500
, pre_emph = 50.0
, harmonicity_threshold = None
, formant_method = 'mean'
):
"""
Estimate vocal tract length following the formula in Fitch 1997
The speed_of_sound is usually ~335 m/s, and L is the vocal tract length in m.
Inputs:
Fname : name of the audio file to analyse (only works with mono files)
harmonicity_threshold : harmonicty threshold to exclude parts of the sound whenc omputing mean formant frequency
(between 0 and 1 : 1 is very harmonic, 0 is unharmonic)
speed_of_sound : speed of sound in m.s-1 (in this case the output will be in meters)
Check the help from get_mean_formant_praat_harmonicity for other detailed inputs
Outputs:
vtl : estimated vocal tract length in meters (depends on the unit of speed of sound)
"""
#compute formant dispersion
fd = get_formant_dispersion(Fname = Fname
, time_step = time_step
, window_size = window_size
, nb_formants = nb_formants
, max_formant_freq = max_formant_freq
, pre_emph = pre_emph
, harmonicity_threshold = harmonicity_threshold
, formant_method = formant_method
)
#estimate vocal tract length
vtl = speed_of_sound/(2*fd)
return vtl
# --------------------------------------------------------------------#
# --------------------------------------------------------------------#
# ----------------- Spectral Enveloppes
# ----------------- LPC and True Envelope
# --------------------------------------------------------------------#
# --------------------------------------------------------------------#
# ---------- get_mean_lpc_from_audio
def get_mean_lpc_from_audio(audio, wait = True, nb_coefs = 45, destroy_sdif_after_analysis = True):
"""
parameters:
audio : file to anlayse
analysis : sdif file to generate, if not defined analysis will have the same name as the audio file but with an sdif extension.
nb_coefs : number of lpc coeficients for the analysis
warning :
this function only works for mono files
"""
from parse_sdif import mean_matrix
path_and_name = get_file_without_path(audio)
analysis = path_and_name + ".sdif"
# first generate an sdif analysis file
generate_LPC_analysis(audio_file = audio, analysis = analysis, wait = True, nb_coefs = nb_coefs)
# then load and mean the sdif file generated
matrix_data = mean_matrix(analysis)
#destroy the sdif file generated if specified by parameter
if destroy_sdif_after_analysis:
os.remove(analysis)
return matrix_data