-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstutter.py
2539 lines (2062 loc) · 94.2 KB
/
stutter.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 -*-
"""stutter.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1HgnhhcxE8s5CiX8KcqRejpy_G2ISutCR
This is an in-progress recreation of the FluentNet LSTM neural network by T. Kourkounakis et al.
The intended use is to learn how to classify audio clips into stuttered speech or clean speech, and furthermore each subcategory of stuttered or non-stutt
# Data Extraction
"""
#@title Install Libraries { form-width: "10%", display-mode: "form" }
# install libraries for data generation below
!pip install pydub -qU
#@title Import Libraries { form-width: "10%", display-mode: "form" }
# Import libraries
#!conda info
#!conda list
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import os
import csv
import math
import random
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import torchaudio
import torchaudio.functional as F
import torchaudio.transforms as T
from torch.autograd import Variable
from sklearn.preprocessing import MinMaxScaler
import scipy.signal as signal
from scipy.io import wavfile
import soundfile as sf
!pip install pydub
from pydub import AudioSegment
#@title Prepare data and utility functions. (From Pytorch documentation) { display-mode: "form" }
#@markdown You do not need to look into this cell.
#@markdown Just execute once and you are good to go.
#@markdown In this tutorial, we will use a speech data from [VOiCES dataset](https://iqtlabs.github.io/voices/), which is licensed under Creative Commos BY 4.0.
#-------------------------------------------------------------------------------
# Installation of missing packages
#-------------------------------------------------------------------------------
!pip install boto3
#-------------------------------------------------------------------------------
# Preparation of data and helper functions.
#-------------------------------------------------------------------------------
import io
import os
import math
import tarfile
import multiprocessing
import scipy
import librosa
import boto3
from botocore import UNSIGNED
from botocore.config import Config
import requests
import matplotlib
import matplotlib.pyplot as plt
import pandas as pd
import time
from IPython.display import Audio, display
[width, height] = matplotlib.rcParams['figure.figsize']
if width < 10:
matplotlib.rcParams['figure.figsize'] = [width * 2.5, height]
_SAMPLE_DIR = "_sample_data"
SAMPLE_WAV_URL = "https://pytorch-tutorial-assets.s3.amazonaws.com/steam-train-whistle-daniel_simon.wav"
SAMPLE_WAV_PATH = os.path.join(_SAMPLE_DIR, "steam.wav")
SAMPLE_WAV_SPEECH_URL = "https://pytorch-tutorial-assets.s3.amazonaws.com/VOiCES_devkit/source-16k/train/sp0307/Lab41-SRI-VOiCES-src-sp0307-ch127535-sg0042.wav"
SAMPLE_WAV_SPEECH_PATH = os.path.join(_SAMPLE_DIR, "speech.wav")
SAMPLE_RIR_URL = "https://pytorch-tutorial-assets.s3.amazonaws.com/VOiCES_devkit/distant-16k/room-response/rm1/impulse/Lab41-SRI-VOiCES-rm1-impulse-mc01-stu-clo.wav"
SAMPLE_RIR_PATH = os.path.join(_SAMPLE_DIR, "rir.wav")
SAMPLE_NOISE_URL = "https://pytorch-tutorial-assets.s3.amazonaws.com/VOiCES_devkit/distant-16k/distractors/rm1/babb/Lab41-SRI-VOiCES-rm1-babb-mc01-stu-clo.wav"
SAMPLE_NOISE_PATH = os.path.join(_SAMPLE_DIR, "bg.wav")
SAMPLE_MP3_URL = "https://pytorch-tutorial-assets.s3.amazonaws.com/steam-train-whistle-daniel_simon.mp3"
SAMPLE_MP3_PATH = os.path.join(_SAMPLE_DIR, "steam.mp3")
SAMPLE_GSM_URL = "https://pytorch-tutorial-assets.s3.amazonaws.com/steam-train-whistle-daniel_simon.gsm"
SAMPLE_GSM_PATH = os.path.join(_SAMPLE_DIR, "steam.gsm")
SAMPLE_TAR_URL = "https://pytorch-tutorial-assets.s3.amazonaws.com/VOiCES_devkit.tar.gz"
SAMPLE_TAR_PATH = os.path.join(_SAMPLE_DIR, "sample.tar.gz")
SAMPLE_TAR_ITEM = "VOiCES_devkit/source-16k/train/sp0307/Lab41-SRI-VOiCES-src-sp0307-ch127535-sg0042.wav"
S3_BUCKET = "pytorch-tutorial-assets"
S3_KEY = "VOiCES_devkit/source-16k/train/sp0307/Lab41-SRI-VOiCES-src-sp0307-ch127535-sg0042.wav"
YESNO_DATASET_PATH = os.path.join(_SAMPLE_DIR, "yes_no")
os.makedirs(YESNO_DATASET_PATH, exist_ok=True)
os.makedirs(_SAMPLE_DIR, exist_ok=True)
def _fetch_data():
uri = [
(SAMPLE_WAV_URL, SAMPLE_WAV_PATH),
(SAMPLE_WAV_SPEECH_URL, SAMPLE_WAV_SPEECH_PATH),
(SAMPLE_RIR_URL, SAMPLE_RIR_PATH),
(SAMPLE_NOISE_URL, SAMPLE_NOISE_PATH),
(SAMPLE_MP3_URL, SAMPLE_MP3_PATH),
(SAMPLE_GSM_URL, SAMPLE_GSM_PATH),
(SAMPLE_TAR_URL, SAMPLE_TAR_PATH),
]
for url, path in uri:
with open(path, 'wb') as file_:
file_.write(requests.get(url).content)
_fetch_data()
def _download_yesno():
if os.path.exists(os.path.join(YESNO_DATASET_PATH, "waves_yesno.tar.gz")):
return
torchaudio.datasets.YESNO(root=YESNO_DATASET_PATH, download=True)
YESNO_DOWNLOAD_PROCESS = multiprocessing.Process(target=_download_yesno)
YESNO_DOWNLOAD_PROCESS.start()
def _get_sample(path, resample=None):
effects = [
["remix", "1"]
]
if resample:
effects.extend([
["lowpass", f"{resample // 2}"],
["rate", f'{resample}'],
])
return torchaudio.sox_effects.apply_effects_file(path, effects=effects)
def get_speech_sample(*, resample=None):
return _get_sample(SAMPLE_WAV_SPEECH_PATH, resample=resample)
def get_sample(*, resample=None):
return _get_sample(SAMPLE_WAV_PATH, resample=resample)
def get_rir_sample(*, resample=None, processed=False):
rir_raw, sample_rate = _get_sample(SAMPLE_RIR_PATH, resample=resample)
if not processed:
return rir_raw, sample_rate
rir = rir_raw[:, int(sample_rate*1.01):int(sample_rate*1.3)]
rir = rir / torch.norm(rir, p=2)
rir = torch.flip(rir, [1])
return rir, sample_rate
def get_noise_sample(*, resample=None):
return _get_sample(SAMPLE_NOISE_PATH, resample=resample)
def print_stats(waveform, sample_rate=None, src=None):
if src:
print("-" * 10)
print("Source:", src)
print("-" * 10)
if sample_rate:
print("Sample Rate:", sample_rate)
print("Shape:", tuple(waveform.shape))
print("Dtype:", waveform.dtype)
print(f" - Max: {waveform.max().item():6.3f}")
print(f" - Min: {waveform.min().item():6.3f}")
print(f" - Mean: {waveform.mean().item():6.3f}")
print(f" - Std Dev: {waveform.std().item():6.3f}")
print()
print(waveform)
print()
def plot_waveform(waveform, sample_rate, title="Waveform", xlim=None, ylim=None):
waveform = waveform.numpy()
num_channels, num_frames = waveform.shape
time_axis = torch.arange(0, num_frames) / sample_rate
figure, axes = plt.subplots(num_channels, 1)
if num_channels == 1:
axes = [axes]
for c in range(num_channels):
axes[c].plot(time_axis, waveform[c], linewidth=1)
axes[c].grid(True)
if num_channels > 1:
axes[c].set_ylabel(f'Channel {c+1}')
if xlim:
axes[c].set_xlim(xlim)
if ylim:
axes[c].set_ylim(ylim)
figure.suptitle(title)
plt.show(block=False)
def plot_specgram(waveform, sample_rate, title="Spectrogram", xlim=None):
waveform = waveform.numpy()
num_channels, num_frames = waveform.shape
time_axis = torch.arange(0, num_frames) / sample_rate
figure, axes = plt.subplots(num_channels, 1)
if num_channels == 1:
axes = [axes]
for c in range(num_channels):
axes[c].specgram(waveform[c], Fs=sample_rate)
if num_channels > 1:
axes[c].set_ylabel(f'Channel {c+1}')
if xlim:
axes[c].set_xlim(xlim)
figure.suptitle(title)
plt.show(block=False)
def play_audio(waveform, sample_rate):
waveform = waveform.numpy()
num_channels, num_frames = waveform.shape
if num_channels == 1:
display(Audio(waveform[0], rate=sample_rate))
elif num_channels == 2:
display(Audio((waveform[0], waveform[1]), rate=sample_rate))
else:
raise ValueError("Waveform with more than 2 channels are not supported.")
def inspect_file(path):
print("-" * 10)
print("Source:", path)
print("-" * 10)
print(f" - File size: {os.path.getsize(path)} bytes")
print(f" - {torchaudio.info(path)}")
def plot_spectrogram(spec, title=None, ylabel='freq_bin', aspect='auto', xmax=None):
fig, axs = plt.subplots(1, 1)
axs.set_title(title or 'Spectrogram (db)')
axs.set_ylabel(ylabel)
axs.set_xlabel('frame')
im = axs.imshow(librosa.power_to_db(spec), origin='lower', aspect=aspect)
if xmax:
axs.set_xlim((0, xmax))
fig.colorbar(im, ax=axs)
plt.show(block=False)
def plot_mel_fbank(fbank, title=None):
fig, axs = plt.subplots(1, 1)
axs.set_title(title or 'Filter bank')
axs.imshow(fbank, aspect='auto')
axs.set_ylabel('frequency bin')
axs.set_xlabel('mel bin')
plt.show(block=False)
def get_spectrogram(
n_fft = 400,
win_len = None,
hop_len = None,
power = 2.0,
):
waveform, _ = get_speech_sample()
spectrogram = T.Spectrogram(
n_fft=n_fft,
win_length=win_len,
hop_length=hop_len,
center=True,
pad_mode="reflect",
power=power,
)
return spectrogram(waveform)
def plot_pitch(waveform, sample_rate, pitch):
figure, axis = plt.subplots(1, 1)
axis.set_title("Pitch Feature")
axis.grid(True)
end_time = waveform.shape[1] / sample_rate
time_axis = torch.linspace(0, end_time, waveform.shape[1])
axis.plot(time_axis, waveform[0], linewidth=1, color='gray', alpha=0.3)
axis2 = axis.twinx()
time_axis = torch.linspace(0, end_time, pitch.shape[1])
ln2 = axis2.plot(
time_axis, pitch[0], linewidth=2, label='Pitch', color='green')
axis2.legend(loc=0)
plt.show(block=False)
def plot_kaldi_pitch(waveform, sample_rate, pitch, nfcc):
figure, axis = plt.subplots(1, 1)
axis.set_title("Kaldi Pitch Feature")
axis.grid(True)
end_time = waveform.shape[1] / sample_rate
time_axis = torch.linspace(0, end_time, waveform.shape[1])
axis.plot(time_axis, waveform[0], linewidth=1, color='gray', alpha=0.3)
time_axis = torch.linspace(0, end_time, pitch.shape[1])
ln1 = axis.plot(time_axis, pitch[0], linewidth=2, label='Pitch', color='green')
axis.set_ylim((-1.3, 1.3))
axis2 = axis.twinx()
time_axis = torch.linspace(0, end_time, nfcc.shape[1])
ln2 = axis2.plot(
time_axis, nfcc[0], linewidth=2, label='NFCC', color='blue', linestyle='--')
lns = ln1 + ln2
labels = [l.get_label() for l in lns]
axis.legend(lns, labels, loc=0)
plt.show(block=False)
DEFAULT_OFFSET = 201
SWEEP_MAX_SAMPLE_RATE = 48000
DEFAULT_LOWPASS_FILTER_WIDTH = 6
DEFAULT_ROLLOFF = 0.99
DEFAULT_RESAMPLING_METHOD = 'sinc_interpolation'
def _get_log_freq(sample_rate, max_sweep_rate, offset):
"""Get freqs evenly spaced out in log-scale, between [0, max_sweep_rate // 2]
offset is used to avoid negative infinity `log(offset + x)`.
"""
half = sample_rate // 2
start, stop = math.log(offset), math.log(offset + max_sweep_rate // 2)
return torch.exp(torch.linspace(start, stop, sample_rate, dtype=torch.double)) - offset
def _get_inverse_log_freq(freq, sample_rate, offset):
"""Find the time where the given frequency is given by _get_log_freq"""
half = sample_rate // 2
return sample_rate * (math.log(1 + freq / offset) / math.log(1 + half / offset))
def _get_freq_ticks(sample_rate, offset, f_max):
# Given the original sample rate used for generating the sweep,
# find the x-axis value where the log-scale major frequency values fall in
time, freq = [], []
for exp in range(2, 5):
for v in range(1, 10):
f = v * 10 ** exp
if f < sample_rate // 2:
t = _get_inverse_log_freq(f, sample_rate, offset) / sample_rate
time.append(t)
freq.append(f)
t_max = _get_inverse_log_freq(f_max, sample_rate, offset) / sample_rate
time.append(t_max)
freq.append(f_max)
return time, freq
def plot_sweep(waveform, sample_rate, title, max_sweep_rate=SWEEP_MAX_SAMPLE_RATE, offset=DEFAULT_OFFSET):
x_ticks = [100, 500, 1000, 5000, 10000, 20000, max_sweep_rate // 2]
y_ticks = [1000, 5000, 10000, 20000, sample_rate//2]
time, freq = _get_freq_ticks(max_sweep_rate, offset, sample_rate // 2)
freq_x = [f if f in x_ticks and f <= max_sweep_rate // 2 else None for f in freq]
freq_y = [f for f in freq if f >= 1000 and f in y_ticks and f <= sample_rate // 2]
figure, axis = plt.subplots(1, 1)
axis.specgram(waveform[0].numpy(), Fs=sample_rate)
plt.xticks(time, freq_x)
plt.yticks(freq_y, freq_y)
axis.set_xlabel('Original Signal Frequency (Hz, log scale)')
axis.set_ylabel('Waveform Frequency (Hz)')
axis.xaxis.grid(True, alpha=0.67)
axis.yaxis.grid(True, alpha=0.67)
figure.suptitle(f'{title} (sample rate: {sample_rate} Hz)')
plt.show(block=True)
def get_sine_sweep(sample_rate, offset=DEFAULT_OFFSET):
max_sweep_rate = sample_rate
freq = _get_log_freq(sample_rate, max_sweep_rate, offset)
delta = 2 * math.pi * freq / sample_rate
cummulative = torch.cumsum(delta, dim=0)
signal = torch.sin(cummulative).unsqueeze(dim=0)
return signal
def benchmark_resample(
method,
waveform,
sample_rate,
resample_rate,
lowpass_filter_width=DEFAULT_LOWPASS_FILTER_WIDTH,
rolloff=DEFAULT_ROLLOFF,
resampling_method=DEFAULT_RESAMPLING_METHOD,
beta=None,
librosa_type=None,
iters=5
):
if method == "functional":
begin = time.time()
for _ in range(iters):
F.resample(waveform, sample_rate, resample_rate, lowpass_filter_width=lowpass_filter_width,
rolloff=rolloff, resampling_method=resampling_method)
elapsed = time.time() - begin
return elapsed / iters
elif method == "transforms":
resampler = T.Resample(sample_rate, resample_rate, lowpass_filter_width=lowpass_filter_width,
rolloff=rolloff, resampling_method=resampling_method, dtype=waveform.dtype)
begin = time.time()
for _ in range(iters):
resampler(waveform)
elapsed = time.time() - begin
return elapsed / iters
elif method == "librosa":
waveform_np = waveform.squeeze().numpy()
begin = time.time()
for _ in range(iters):
librosa.resample(waveform_np, sample_rate, resample_rate, res_type=librosa_type)
elapsed = time.time() - begin
return elapsed / iters
#@title Visualizing Data
waveform, sample_rate = torchaudio.load("/content/drive/MyDrive/Work/MCRL/stutter/data/uclass/audio/F_0050_10y9m_1.wav")
print_stats(waveform, sample_rate=16000)
#plot_waveform(waveform, sample_rate)
plot_specgram(waveform, 16000)
play_audio(waveform, 16000)
#@title Libristutter —ALL APPEARANCES— Data Generation, Storage { form-width: "10%" }
# Libristutter audio file --> audio clips(the 4 seconds around all appearances of stutters) --> spectrogram --> storage
# all images saved to "/contents/data/images/" in google drive root
def graph_spectrogram(wav_file):
rate, data = wavfile.read(wav_file)
fig,ax = plt.subplots(1)
fig.subplots_adjust(left=0,right=1,bottom=0,top=1)
ax.axis('off')
pxx, freqs, bins, im = ax.specgram(x=data, Fs=16000, noverlap=128, NFFT=256)
ax.axis('off')
#fig.savefig('sp_xyz.png', dpi=300, frameon='false')
data_location = "/content/drive/MyDrive/Work/MCRL/stutter/data/libristutter/"
parts = ['partC'] #['partA', 'partB', 'partC']
#!rm -r /content/drive/MyDrive/Work/MCRL/stutter/data/libristutter/clips
#!rm -r /content/drive/MyDrive/data/imagesA/
#!rm -r /content/drive/MyDrive/data/imagesB/
#!rm -r /content/drive/MyDrive/data/imagesC/
for part in parts:
speakerIDs = sorted(os.listdir(data_location + part + "/" + "audio/")) # speaker ID numbers array
speakerIDNum = speakerIDs.index('87') #0 # math.ceil(0.8 * (len(speakerIDs)-1)) # this convoluted to start with j test data creation, normally 0
speakerID = speakerIDs[speakerIDNum]
for id in speakerIDs: print(id)
chapters = sorted(os.listdir(data_location + part + "/" + "audio/" + speakerID)) # chapter numbers array
chapterNum = 0 #math.ceil(0.8 * (len(chapters)-1)) # 0
chapter = chapters[chapterNum]
phrases = sorted(os.listdir(data_location + part + "/" + "audio" + "/" + speakerID + "/" + chapter)) # audio file names array (all .flac)
phraseNum = 0#math.ceil(0.8 * (len(phrases)-1)) # 0
phrase = phrases[phraseNum]
annotation_name = phrase[:-5] + ".csv"
annotation_location = data_location + part + "/" + "annotations/" + speakerID + "/" + chapter + "/" + annotation_name
train_location = f"/content/drive/MyDrive/data/{'images' + part[-1]}/train/"
test_location = f"/content/drive/MyDrive/data/{'images' + part[-1]}/test/"
clips_location = "/content/drive/MyDrive/Work/MCRL/stutter/data/libristutter/clips/"
dataTrainPctg = 0.8
partition_spec_loc = train_location # swaps to test_location when 80% of data has been put in train/
lump_loc = "/content/drive/MyDrive/data/libriAll/"
lump_spec_loc = lump_loc + "train/"
while speakerIDNum < len(speakerIDs): # first 80% of speakers is for training
print("\nCREATING TRAINING IMAGES\n")
while chapterNum < len(chapters):
while phraseNum < len(phrases):
if speakerIDNum > len(speakerIDs) * dataTrainPctg and partition_spec_loc != test_location:
partition_spec_loc = test_location
lump_spec_loc = lump_loc + "test/"
print("""\n\n\nDONE WITH CREATING TRAINING IMAGES\nCREATING TESTING IMAGES\n\n\n""")
file_name = phrase
file_location = data_location + part + "/" + "audio/" + speakerID + "/" + chapter + "/" + file_name
annotation_name = phrase[:-5] + ".csv"
annotation_location = data_location + part + "/" + "annotations/" + speakerID + "/" + chapter + "/" + annotation_name
stutterRows = []
with open(annotation_location, newline='') as csvfile: # open annotations for current file
spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|')
data = list(spamreader)
rowCount = len(data)
stutterRowInd = 0
foundStutters = 0
print(f'Loc: {file_location}')
for row in data: # finds first appearance of stutter in the csv annotation just opened and stores that row in stutterRows
row = row[0].split(",")
if len(row) == 4 and row[3] != '0':
stutterRows.append(row)
for cellInd in range(len(stutterRows[foundStutters])):
if cellInd > 0:
stutterRows[foundStutters][cellInd] = float(stutterRows[foundStutters][cellInd])
cellInd += 1
print(f' Row: {str(row[0])}, {str(int(row[3]))}, {str(row[1])}, {str(row[2])}') # STUTTER, TYPE, START, END
foundStutters += 1
stutterRowInd += 1
csvfile.close()
print(f' StutterRows: {stutterRows}')
audio = AudioSegment.from_file(file_location) # create audiosegment object from the full .flac file
if audio.duration_seconds * 1000 >= 4000:
if len(stutterRows) == 0: # if file had no stutters
print(f'\nCLEAN FOUND @: {file_location}\n')
full_length = int(audio.duration_seconds * 1000)
cleanInd = 0
for cleanChunk in range(math.floor(audio.duration_seconds * 1000 / 4000)):
cleanInd += 1
print(f' Creating {cleanInd} clean clip here')
cleanStart = cleanChunk * 4000
cleanEnd = cleanStart + 4000
stutterType = 0
stutterClip = audio[cleanStart:cleanEnd]
print(f' Stutter-Free Clip Start and End: {cleanStart}, {cleanEnd}')
clipName = clips_location + part + "/" + file_name[:-5] + "_" + str(cleanInd) + ".flac"
exportClip = AudioSegment.empty() # only way I know how to do this at the moment, make a new empty audioseg, append the stutter clip to it w/ no fade-in
exportClip = exportClip.append(stutterClip, crossfade = 0)
os.makedirs(os.path.dirname(clipName), exist_ok=True) # in case it doesn't exist, create the dir where image will be stored
exportClip.export(clipName, format="wav")
# spectrogram creation
file_part_name = partition_spec_loc + str(stutterType) + "/" + file_name[:-5] + "_" + str(cleanInd) + ".png" # strip .flac and direct images to content/data/[STUTTER TYPE]/[FILE NAME]
file_lump_name = lump_spec_loc + str(stutterType) + "/" + file_name[:-5] + "_" + str(cleanInd) + ".png"
os.makedirs(os.path.dirname(file_part_name), exist_ok=True) # in case it doesn't exist, create the dir where image will be stored
os.makedirs(os.path.dirname(file_lump_name), exist_ok=True) # in case it doesn't exist, create the dir where image will be stored
graph_spectrogram(clipName) # graph, save, close
plt.savefig(file_part_name)
plt.savefig(file_lump_name)
plt.close()
csvfile.close()
else: # if the file had stutters
rowInd = 0
for stutterRow in stutterRows:
audio = AudioSegment.from_file(file_location) # create audiosegment object from the full .flac file
rowInd += 1
stutterStart = stutterRow[1] * 1000 # convert to milliseconds for pydub AudioSegment module
stutterEnd = stutterRow[2] * 1000
stutterDurr = stutterEnd - stutterStart
timeLeft = 4000 - stutterDurr
halfLeft = timeLeft / 2
stutterType = int(stutterRow[3])
start = 0
end = 4000
#print(f' Stutter Clip init Start and End: {stutterStart}, {stutterEnd}')
#print(f' Half left: {halfLeft}')
if timeLeft >= 0: # if we need to add time to the clip to make it 4 seconds long
# here we know the amount we'd half to add to each side of the clip to make it 4 seconds long(halfLeft)
# and we are checking if we can take of that amount without going outside the bounds of the whole clip
# if we go out of them as in the first two ifs, then that means we are either at the end or the start
# in those cases, take the first 4 seconds or the last 4, respectively
# otherwise take the clip from start-halfLeft to end+halfLeft
if stutterStart - halfLeft < 0: # if the stutter is within the first 4 seconds
start = 0
elif stutterEnd + halfLeft > audio.duration_seconds * 1000: # if the stutter is within the last 4 seconds
start = audio.duration_seconds * 1000 - 4000
else: # if it's after the first 4 seconds and before the last 4
start = stutterStart - halfLeft
end = start + 4000
stutterClip = audio[start:end]
print(f' Stutter clip {rowInd} duration: start, end: ({start}, {end}); len: {stutterClip.duration_seconds * 1000}')
clipName = clips_location + part + "/" + file_name[:-5] + "_" + str(rowInd) + ".flac"
exportClip = AudioSegment.empty() # only way I know how to do this at the moment, make a new empty audioseg, append the stutter clip to it w/ no fade-in
exportClip = exportClip.append(stutterClip, crossfade = 0)
os.makedirs(os.path.dirname(clipName), exist_ok=True) # in case it doesn't exist, create the dir where image will be stored
exportClip.export(clipName, format="wav")
# spectrogram creation
file_part_name = partition_spec_loc + str(stutterType) + "/" + file_name[:-5] + "_" + str(rowInd) + ".png" # strip .flac and direct images to content/data/[STUTTER TYPE]/[FILE NAME]
file_lump_name = lump_spec_loc + str(stutterType) + "/" + file_name[:-5] + "_" + str(rowInd) + ".png"
os.makedirs(os.path.dirname(file_part_name), exist_ok=True) # in case it doesn't exist, create the dir where image will be stored
os.makedirs(os.path.dirname(file_lump_name), exist_ok=True) # in case it doesn't exist, create the dir where image will be stored
graph_spectrogram(clipName) # graph, save, close
plt.savefig(file_part_name)
plt.savefig(file_lump_name)
plt.close()
else:
print(f'\nFile at {file_location} is not at least 4 seconds. SKIPPED\n')
phraseNum += 1
if phraseNum < len(phrases):
phrase = phrases[phraseNum]
chapterNum += 1 # once we've finished all the phrases for a chapter
if chapterNum < len(chapters): # move onto the next chapter for this speaker if it exists
chapter = chapters[chapterNum]
phrases = sorted(os.listdir(data_location + part + "/" + "audio" + "/" + speakerID + "/" + chapter)) # fetch the new phrases
phraseNum = 0
phrase = phrases[phraseNum]
speakerIDNum += 1
if speakerIDNum < len(speakerIDs):
speakerID = speakerIDs[speakerIDNum]
chapterNum = 0
chapters = sorted(os.listdir(data_location + part + "/" + "audio/" + speakerID))
chapter = chapters[chapterNum]
phrases = sorted(os.listdir(data_location + part + "/" + "audio" + "/" + speakerID + "/" + chapter)) # fetch the new phrases
phraseNum = 0
phrase = phrases[phraseNum]
#@title Testing Libristutter Image Creation
def graph_spectrogram(wav_file):
rate, data = wavfile.read(wav_file)
fig,ax = plt.subplots(1)
fig.subplots_adjust(left=0,right=1,bottom=0,top=1)
ax.axis('off')
pxx, freqs, bins, im = ax.specgram(x=data, Fs=16000, noverlap=128, NFFT=256)
ax.axis('off')
#fig.savefig('/content/example.png',, frameon='false')
print(f'0-class Image Before and After Clipping')
graph_spectrogram("/content/drive/MyDrive/Work/MCRL/stutter/data/libristutter/partB/audio/2952/407/2952-407-0021.flac")
graph_spectrogram("/content/drive/MyDrive/Work/MCRL/stutter/data/libristutter/clips/partB/2952-407-0021_1.flac")
#print(f'x-class Image Before and After Clipping')
#graph_spectrogram("/content/drive/MyDrive/Work/MCRL/stutter/data/libristutter/partA/audio/103/1240/103-1240-0000.flac")
#graph_spectrogram("/content/drive/MyDrive/Work/MCRL/stutter/data/libristutter/clips/partA/103-1240-0000_1.flac")
#@title UCLASS Data Generation -- ALL APPEARANCES { form-width: "10%", display-mode: "form" }
# UCLASS audio file --> audio clip(the 4 seconds around the first appearance of a stutter) --> spectrogram --> storage
# all images saved to "/contents/data/Uimages/" in google drive root
# aud_~~ = audio, annot_~~ = annotation, file_~~ = spectrogram
def graph_spectrogram(wav_file):
rate, data = wavfile.read(wav_file)
fig,ax = plt.subplots(1)
fig.subplots_adjust(left=0,right=1,bottom=0,top=1)
ax.axis('off')
pxx, freqs, bins, im = ax.specgram(x=data, Fs=16000, noverlap=128, NFFT=256) # NFFT used to be 512, worked well supposedly
ax.axis('off')
#fig.savefig('sp_xyz.png', dpi=300, frameon='false')
data_location = "/content/drive/MyDrive/Work/MCRL/stutter/data/uclass/"
annotation_location = data_location + "annotations/"
audio_location = data_location + "audio/"
annot_files = sorted(os.listdir(data_location + "annotations/"))
train_location = "/content/drive/MyDrive/data/uimages/train/"
test_location = "/content/drive/MyDrive/data/uimages/test/"
clips_location = "/content/drive/MyDrive/Work/MCRL/stutter/data/uclass/clips/"
!rm -r /content/drive/MyDrive/data/uimages/
!rm -r /content/drive/MyDrive/Work/MCRL/stutter/data/uclass/clips/
part_spec_location = train_location
print("\nCREATING UCLASS VALIDATION IMAGES\n")
file_num = 1
pct_for_train = 0.8
for annot_name in annot_files:
if file_num > len(annot_files) * pct_for_train and part_spec_location != test_location:
part_spec_location = test_location
print("""\n\n\nDONE WITH CREATING TRAINING IMAGES\nCREATING TESTING IMAGES\n\n\n""")
curr_annot_location = annotation_location + annot_name
audio_name = annot_name[:-4] + ".flac"
curr_audio_location = audio_location + audio_name
stutterRows = []
print(f"\nStutter(s) @ file {file_num}'s Loc: {curr_annot_location}")
file_num += 1
with open(curr_annot_location, newline='', encoding='cp1252') as csvfile: # open annotations for current file
spamreader = csv.reader(csvfile, delimiter=',', quotechar='|')
#print(spamreader)
data = list(spamreader)
rowCount = len(data)
stutterRowInd = 0
foundStutters = 0
for row in data: # finds all rows indicated to contain a stutter and stores them in stutterRows
if row[7] != '0': # the 5th box contains boolean indicating a stutter or lack thereof
file_cont_st = True
stutterRows.append(row) # add the row containining the stutter
for cellInd in [2, 3]:
stutterRows[foundStutters][cellInd] = float(stutterRows[foundStutters][cellInd]) # turn the numerical values in the csv boxes from strings into floats
for cellInd in [7]:
stutterRows[foundStutters][cellInd] = int(stutterRows[foundStutters][cellInd])
print(f' Row {stutterRowInd}: {str(stutterRows[foundStutters])}')
foundStutters += 1
stutterRowInd += 1
csvfile.close()
if len(stutterRows) != 0: # if it had stutters, loop through each stutter-containing row
rowInd = 0
prevStutterEnd = stutterRows[0][3] * 1000
cleanGaps = 0
for stutterRow in stutterRows:
audio = AudioSegment.from_file(curr_audio_location) # create audiosegment object from the full .flac file
rowInd += 1
stutterStart = stutterRow[2] * 1000 # convert to milliseconds for pydub AudioSegment module
stutterEnd = stutterRow[3] * 1000
stutterDurr = stutterEnd - stutterStart
timeLeft = 4000 - stutterDurr
halfLeft = timeLeft / 2
stutterType = int(stutterRow[7])
if stutterStart - prevStutterEnd > 4000:
cleanGaps += 1
for chunkInd in range(math.floor((stutterStart - prevStutterEnd)/4000)):
start = stutterStart + chunkInd * 4000
end = start + 4000
stutterClip = audio[start: end]
print(f' Clean UCLASS inter-clip {chunkInd + 1} range: ({start}, {end}); len: {stutterClip.duration_seconds * 1000}')
clip_name = f"{clips_location}/{audio_name[:-4]}_{cleanGaps}clean{chunkInd}.flac" # data/uimages/clips/~~~~~.wav (the 4 second audio clip files)
exportClip = AudioSegment.empty() # only way I know how to do this at the moment, make a new empty audioseg, append the stutter clip to it w/ no fade-in
exportClip = exportClip.append(stutterClip, crossfade = 0)
os.makedirs(os.path.dirname(clip_name), exist_ok=True) # in case it doesn't exist, create the dir where image will be stored
exportClip.export(clip_name, format="wav")
# spectrogram creation
file_result_name = f"{part_spec_location}0/{audio_name[:-4]}_{cleanGaps}clean{rowInd}.png" # strip .wav and direct images to content/data/[STUTTER TYPE]/[FILE NAME]
os.makedirs(os.path.dirname(file_result_name), exist_ok=True) # in case it doesn't exist, create the dir where image will be stored
#print(f'Clip name: {clip_name}')
graph_spectrogram(clip_name) # graph, save, close # used to be file_location
plt.savefig(file_result_name)
plt.close()
if timeLeft >= 0: # if we need to add time to the clip to make it 4 seconds long
# here we know the amount we'd half to add to each side of the clip to make it 4 seconds long(halfLeft)
# and we are checking if we can take of that amount without going outside the bounds of the whole clip
# if we go out of them as in the first two ifs, then that means we are either at the end or the start
# in those cases, take the first 4 seconds or the last 4, respectively
# otherwise take the clip from start-halfLeft to end+halfLeft
if stutterStart - halfLeft < 0: # if the stutter is within the first 4 seconds
start = 0
end = 4000
elif stutterEnd + halfLeft > audio.duration_seconds * 1000: # if the stutter is within the last 4 seconds
start = audio.duration_seconds * 1000 - 4000
end = start + 4000
else: # if it's after the first 4 seconds and before the last 4
start = stutterStart - halfLeft
end = stutterEnd + halfLeft
stutterClip = audio[start:end]
print(f' Stutter clip {rowInd} range: ({start}, {end}); len: {stutterClip.duration_seconds * 1000}')
clip_name = clips_location + "/" + audio_name[:-4] + "_" + str(rowInd) + ".flac" # data/uimages/clips/~~~~~.wav (the 4 second audio clip files)
exportClip = AudioSegment.empty() # only way I know how to do this at the moment, make a new empty audioseg, append the stutter clip to it w/ no fade-in
exportClip = exportClip.append(stutterClip, crossfade = 0)
os.makedirs(os.path.dirname(clip_name), exist_ok=True) # in case it doesn't exist, create the dir where image will be stored
exportClip.export(clip_name, format="wav")
# spectrogram creation
file_result_name = part_spec_location + str(stutterType) + "/" + audio_name[:-4] + "_" + str(rowInd) + ".png" # strip .wav and direct images to content/data/[STUTTER TYPE]/[FILE NAME]
os.makedirs(os.path.dirname(file_result_name), exist_ok=True) # in case it doesn't exist, create the dir where image will be stored
#print(f'Clip name: {clip_name}')
graph_spectrogram(clip_name) # graph, save, close # used to be file_location
plt.savefig(file_result_name)
plt.close()
prevStutterEnd = stutterEnd
#@title Testing UCLASS Image Creation
def graph_spectrogram(wav_file):
rate, data = wavfile.read(wav_file)
fig,ax = plt.subplots(1)
fig.subplots_adjust(left=0,right=1,bottom=0,top=1)
ax.axis('off')
pxx, freqs, bins, im = ax.specgram(x=data, Fs=16000, noverlap=128, NFFT=256) # NFFT used to be 512, worked well supposedly
ax.axis('off')
#fig.savefig('sp_xyz.png', dpi=300, frameon='false')
rate, data = wavfile.read("/content/drive/MyDrive/Work/MCRL/stutter/data/uclass/audio/F_0050_10y9m_1.flac")
fig,ax = plt.subplots(1)
fig.subplots_adjust(left=0,right=1,bottom=0,top=1)
#ax.axis('off')
pxx, freqs, bins, im = ax.specgram(x=data, Fs=16000, noverlap=128, NFFT=256) # NFFT used to be 512, worked well supposedly
rate2, data2 = wavfile.read("/content/drive/MyDrive/Work/MCRL/stutter/data/libristutter/partA/audio/103/1240/103-1240-0000.flac")
fig2,ax2 = plt.subplots(1)
fig2.subplots_adjust(left=0,right=1,bottom=0,top=1)
pxx, freqs, bins, im = ax2.specgram(x=data2, Fs=16000, noverlap=128, NFFT=256)
plt.show()
#ax.axis('off')
#graph_spectrogram("/content/drive/MyDrive/Work/MCRL/stutter/data/uclass/audio/M_0090_10y1m_1.wav")
#graph_spectrogram("/content/drive/MyDrive/Work/MCRL/stutter/data/libristutter/partA/audio/103/1240/103-1240-0000.flac")
"""# Model Begins Here"""
#@title Visualize Data (for debugging) { run: "auto", display-mode: "form" }
def visualize_data(input, title=None):
input = input.numpy().transpose((1, 2, 0))
mean = np.array([0.485, 0.456, 0.406])
std = np.array([0.229, 0.224, 0.225])
input = std * input + mean
input = np.clip(input, 0, 1)
plt.imshow(input)
if title is not None:
plt.title(None) # remove titles
plt.pause(0.001) ## Here we are pausing a bit so that plots are updated
inputs_data, classes = next(iter(loaders_data['train']))
## This is the code for getting a batch of training data
out = torchvision.utils.make_grid(inputs_data)
## Here we are making a grid from batch
#visualize_data(out, title=[class_names[x] for x in classes])
#@title WandB Training Visualizer and Analysis { form-width: "10%", display-mode: "both" }
!pip install wandb -qU
# Log in to your W&B account
import wandb
wandb.login()
#API key: 5b5a1032d2bef3510f30bf3e46923f62ec1b1ac2
#@title Install Libraries { display-mode: "form" }
# Install Libraries
#!pip install pydub -qU
#!pip install wandb -qU
#!wandb login
#!pip install cloud-tpu-client==0.10 torch==1.12.0 https://storage.googleapis.com/tpu-pytorch/wheels/colab/torch_xla-1.12-cp37-cp37m-linux_x86_64.whl
!pip install torchinfo
#@title Import Libraries { run: "auto", display-mode: "form" }
# Import libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import os
import csv
import math
import time
import copy
import gc
plt.ion()
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.hub
from torch.utils.data import Subset
import torch.optim as optim
from torch.optim import lr_scheduler
import torchvision
from torchvision import datasets, models, transforms
from torchvision.models.feature_extraction import get_graph_node_names
from torchvision.models.feature_extraction import create_feature_extractor
import torchaudio
import torchaudio.functional as F
import torchaudio.transforms as T
#from torchsummary import summary
from torchinfo import summary
from torch.autograd import Variable
from sklearn.preprocessing import MinMaxScaler
import scipy.signal as signal
from scipy.io import wavfile
import soundfile as sf
# imports the torch_xla package -- TPU
#import torch_xla
#import torch_xla.core.xla_model as xm
#@title SERN Class and Creation Methods { form-width: "10%" }
# SEResNet Class
# From: https://github.com/StickCui/PyTorch-SE-ResNet/blob/master/model/model.py
class SEResNet(nn.Module):
def __init__(self, block, layers, num_classes=1000):
self.inplanes = 64
super(SEResNet, self).__init__()
self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3,
bias=False)
self.bn1 = nn.BatchNorm2d(64)
self.relu = nn.ReLU(inplace=True)
self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
self.layer1 = self._make_layer(block, 64, layers[0])
self.layer2 = self._make_layer(block, 128, layers[1], stride=2)
self.layer3 = self._make_layer(block, 256, layers[2], stride=2)
self.layer4 = self._make_layer(block, 512, layers[3], stride=2)
self.avgpool = nn.AvgPool2d(7)
self.fc = nn.Linear(512 * block.expansion, num_classes)
for m in self.modules():
if isinstance(m, nn.Conv2d):
n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
m.weight.data.normal_(0, math.sqrt(2. / n))
elif isinstance(m, nn.BatchNorm2d):
m.weight.data.fill_(1)
m.bias.data.zero_()
def _make_layer(self, block, planes, blocks, stride=1):
downsample = None
if stride != 1 or self.inplanes != planes * block.expansion:
downsample = nn.Sequential(
nn.Conv2d(self.inplanes, planes * block.expansion,
kernel_size=1, stride=stride, bias=False),
nn.BatchNorm2d(planes * block.expansion),
)
layers = []
layers.append(block(self.inplanes, planes, stride, downsample))
self.inplanes = planes * block.expansion
for i in range(1, blocks):
layers.append(block(self.inplanes, planes))
return nn.Sequential(*layers)
def forward(self, x):
x = self.conv1(x)
x = self.bn1(x)
x = self.relu(x)
x = self.maxpool(x)
x = self.layer1(x)
x = self.layer2(x)
x = self.layer3(x)
x = self.layer4(x)
x = self.avgpool(x)
x = x.view(x.size(0), -1)
x = self.fc(x)
return x
class Bottleneck(nn.Module): # what is this ....
expansion = 4
def __init__(self, inplanes, planes, stride=1, downsample=None):
super(Bottleneck, self).__init__()
self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False)
self.bn1 = nn.BatchNorm2d(planes)
self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride,
padding=1, bias=False)
self.bn2 = nn.BatchNorm2d(planes)
self.conv3 = nn.Conv2d(planes, planes * 4, kernel_size=1, bias=False)
self.bn3 = nn.BatchNorm2d(planes * 4)
self.relu = nn.ReLU(inplace=True)
# SE
self.global_pool = nn.AdaptiveAvgPool2d(1)
self.conv_down = nn.Conv2d(
planes * 4, planes // 4, kernel_size=1, bias=False)
self.conv_up = nn.Conv2d(
planes // 4, planes * 4, kernel_size=1, bias=False)
self.sig = nn.Sigmoid()
# Downsample
self.downsample = downsample
self.stride = stride
def forward(self, x):
residual = x
out = self.conv1(x)
out = self.bn1(out)
out = self.relu(out)
out = self.conv2(out)
out = self.bn2(out)
out = self.relu(out)
out = self.conv3(out)
out = self.bn3(out)
out1 = self.global_pool(out)
out1 = self.conv_down(out1)
out1 = self.relu(out1)
out1 = self.conv_up(out1)
out1 = self.sig(out1)
if self.downsample is not None:
residual = self.downsample(x)
res = out1 * out + residual
res = self.relu(res)
return res