File size: 55,117 Bytes
7934b29
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
{
    "cells": [
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {
                "colab": {
                    "base_uri": "https://localhost:8080/",
                    "height": 1000
                },
                "colab_type": "code",
                "id": "cvXwyS263AMk",
                "outputId": "57646cdd-58c1-4ddb-8805-9178cb0a2048"
            },
            "outputs": [],
            "source": [
                "\"\"\"\n",
                "You can run either this notebook locally (if you have all the dependencies and a GPU) or on Google Colab.\n",
                "\n",
                "Instructions for setting up Colab are as follows:\n",
                "1. Open a new Python 3 notebook.\n",
                "2. Import this notebook from GitHub (File -> Upload Notebook -> \"GITHUB\" tab -> copy/paste GitHub URL)\n",
                "3. Connect to an instance with a GPU (Runtime -> Change runtime type -> select \"GPU\" for hardware accelerator)\n",
                "4. Run this cell to set up dependencies.\n",
                "\"\"\"\n",
                "# If you're using Google Colab and not running locally, run this cell.\n",
                "\n",
                "## Install dependencies\n",
                "!pip install wget\n",
                "!apt-get install sox libsndfile1 ffmpeg\n",
                "!pip install text-unidecode\n",
                "\n",
                "# ## Install NeMo\n",
                "BRANCH = 'r1.17.0'\n",
                "!python -m pip install git+https://github.com/NVIDIA/NeMo.git@$BRANCH#egg=nemo_toolkit[asr]\n",
                "\n",
                "## Install TorchAudio\n",
                "!pip install torchaudio>=0.13.0 -f https://download.pytorch.org/whl/torch_stable.html\n",
                "\n",
                "## Grab the config we'll use in this example\n",
                "!mkdir configs"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {
                "colab_type": "text",
                "id": "Kqg4Rwki4jBX"
            },
            "source": [
                "# Introduction\n",
                "\n",
                "Data augmentation is a useful method to improve the performance of models which is applicable across multiple domains. Certain augmentations can also substantially improve robustness of models to noisy samples. \n",
                "\n",
                "In this notebook, we describe how to construct an augmentation pipeline inside [Neural Modules (NeMo)](https://github.com/NVIDIA/NeMo), enable augmented training of a [MatchboxNet model](https://arxiv.org/abs/2004.08531 ) ( based on QuartzNet, from the paper [\"QuartzNet: Deep Automatic Speech Recognition with 1D Time-Channel Separable Convolutions\"](https://arxiv.org/abs/1910.10261)) and finally how to construct custom augmentations to add to NeMo.\n",
                "\n",
                "The notebook will follow the steps below:\n",
                "\n",
                " - Dataset preparation: Preparing a noise dataset using an example file.\n",
                "\n",
                " - Construct a data augmentation pipeline.\n",
                " \n",
                " - Construct a custom augmentation and register it for use in NeMo."
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {
                "colab_type": "text",
                "id": "5XieMEo84pJ-"
            },
            "source": [
                "## Note\n",
                "Data augmentation is valuable for many datasets, but it comes at the cost of increased training time if samples are augmented during training time. Certain augmentations are particularly costly, in terms of how much time they take to process a single sample. A few examples of slow augmentations available in NeMo are : \n",
                "\n",
                " - Speed Perturbation\n",
                " - Time Stretch Perturbation (Sample level)\n",
                " - Noise Perturbation\n",
                " - Impulse Perturbation\n",
                " - Time Stretch Augmentation (Batch level, Neural Module)\n",
                " \n",
                "For such augmentations, it is advisable to pre-process the dataset offline for a one time preprocessing cost and then train the dataset on this augmented training set."
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {
                "colab_type": "text",
                "id": "Tgc_ZHDl4sMy"
            },
            "source": [
                "## Taking a Look at Our Data (AN4)\n",
                "\n",
                "The AN4 dataset, also known as the Alphanumeric dataset, was collected and published by Carnegie Mellon University. It consists of recordings of people spelling out addresses, names, telephone numbers, etc., one letter or number at a time, as well as their corresponding transcripts. We choose to use AN4 for this tutorial because it is relatively small, with 948 training and 130 test utterances, and so it trains quickly.\n",
                "\n",
                "Before we get started, let's download and prepare the dataset. The utterances are available as `.sph` files, so we will need to convert them to `.wav` for later processing. Please make sure you have [Sox](http://sox.sourceforge.net/) installed for this step (instructions to setup your environment are available at the beginning of this notebook)."
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {
                "colab": {},
                "colab_type": "code",
                "id": "DtLm_XuQ3pmk"
            },
            "outputs": [],
            "source": [
                "# This is where the an4/ directory will be placed.\n",
                "# Change this if you don't want the data to be extracted in the current directory.\n",
                "data_dir = '.'"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {
                "colab": {
                    "base_uri": "https://localhost:8080/",
                    "height": 102
                },
                "colab_type": "code",
                "id": "HjfLhUtH4wNc",
                "outputId": "f0a9cd46-6709-49dd-9103-1e0ef61de745"
            },
            "outputs": [],
            "source": [
                "import glob\n",
                "import os\n",
                "import subprocess\n",
                "import tarfile\n",
                "import wget\n",
                "\n",
                "# Download the dataset. This will take a few moments...\n",
                "print(\"******\")\n",
                "if not os.path.exists(data_dir + '/an4_sphere.tar.gz'):\n",
                "    an4_url = 'https://dldata-public.s3.us-east-2.amazonaws.com/an4_sphere.tar.gz'  # for the original source, please visit http://www.speech.cs.cmu.edu/databases/an4/an4_sphere.tar.gz \n",
                "    an4_path = wget.download(an4_url, data_dir)\n",
                "    print(f\"Dataset downloaded at: {an4_path}\")\n",
                "else:\n",
                "    print(\"Tarfile already exists.\")\n",
                "    an4_path = data_dir + '/an4_sphere.tar.gz'\n",
                "\n",
                "if not os.path.exists(data_dir + '/an4/'):\n",
                "    # Untar and convert .sph to .wav (using sox)\n",
                "    tar = tarfile.open(an4_path)\n",
                "    tar.extractall(path=data_dir)\n",
                "\n",
                "    print(\"Converting .sph to .wav...\")\n",
                "    sph_list = glob.glob(data_dir + '/an4/**/*.sph', recursive=True)\n",
                "    for sph_path in sph_list:\n",
                "        wav_path = sph_path[:-4] + '.wav'\n",
                "        cmd = [\"sox\", sph_path, wav_path]\n",
                "        subprocess.run(cmd)\n",
                "print(\"Finished conversion.\\n******\")\n"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {
                "colab_type": "text",
                "id": "HqJmf4WB5P1x"
            },
            "source": [
                "You should now have a folder called `an4` that contains `etc/an4_train.transcription`, `etc/an4_test.transcription`, audio files in `wav/an4_clstk` and `wav/an4test_clstk`, along with some other files we will not need.\n",
                "\n",
                "We now build a few manifest files which will be used later:"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {
                "colab": {
                    "base_uri": "https://localhost:8080/",
                    "height": 85
                },
                "colab_type": "code",
                "id": "AmR6CH025C8E",
                "outputId": "0cd776ea-078f-4ab8-8a79-eed3e1c05839"
            },
            "outputs": [],
            "source": [
                "# --- Building Manifest Files --- #\n",
                "import json\n",
                "import librosa\n",
                "\n",
                "# Function to build a manifest\n",
                "def build_manifest(transcripts_path, manifest_path, wav_path):\n",
                "    with open(transcripts_path, 'r') as fin:\n",
                "        with open(manifest_path, 'w') as fout:\n",
                "            for line in fin:\n",
                "                # Lines look like this:\n",
                "                # <s> transcript </s> (fileID)\n",
                "                transcript = line[: line.find('(')-1].lower()\n",
                "                transcript = transcript.replace('<s>', '').replace('</s>', '')\n",
                "                transcript = transcript.strip()\n",
                "\n",
                "                file_id = line[line.find('(')+1 : -2]  # e.g. \"cen4-fash-b\"\n",
                "                audio_path = os.path.join(\n",
                "                    data_dir, wav_path,\n",
                "                    file_id[file_id.find('-')+1 : file_id.rfind('-')],\n",
                "                    file_id + '.wav')\n",
                "\n",
                "                duration = librosa.core.get_duration(filename=audio_path)\n",
                "\n",
                "                # Write the metadata to the manifest\n",
                "                metadata = {\n",
                "                    \"audio_filepath\": audio_path,\n",
                "                    \"duration\": duration,\n",
                "                    \"text\": transcript\n",
                "                }\n",
                "                json.dump(metadata, fout)\n",
                "                fout.write('\\n')\n",
                "                \n",
                "# Building Manifests\n",
                "print(\"******\")\n",
                "train_transcripts = data_dir + '/an4/etc/an4_train.transcription'\n",
                "train_manifest = data_dir + '/an4/train_manifest.json'\n",
                "build_manifest(train_transcripts, train_manifest, 'an4/wav/an4_clstk')\n",
                "print(\"Training manifest created.\")\n",
                "\n",
                "test_transcripts = data_dir + '/an4/etc/an4_test.transcription'\n",
                "test_manifest = data_dir + '/an4/test_manifest.json'\n",
                "build_manifest(test_transcripts, test_manifest, 'an4/wav/an4test_clstk')\n",
                "print(\"Test manifest created.\")\n",
                "print(\"******\")"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {
                "colab_type": "text",
                "id": "EQsXzh7x5zIQ"
            },
            "source": [
                "## Prepare the path to manifest files"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {
                "colab": {},
                "colab_type": "code",
                "id": "vmOa0IRC5eW4"
            },
            "outputs": [],
            "source": [
                "dataset_basedir = os.path.join(data_dir, 'an4')\n",
                "\n",
                "train_dataset = os.path.join(dataset_basedir, 'train_manifest.json')\n",
                "test_dataset = os.path.join(dataset_basedir, 'test_manifest.json')"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {
                "colab_type": "text",
                "id": "pz9LC3yZ6J1Q"
            },
            "source": [
                "## Read a few rows of the manifest file \n",
                "\n",
                "Manifest files are the data structure used by NeMo to declare a few important details about the data :\n",
                "\n",
                "1) `audio_filepath`: Refers to the path to the raw audio file <br>\n",
                "2) `text`: The text transcript of this sample <br>\n",
                "3) `duration`: The length of the audio file, in seconds."
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {
                "colab": {},
                "colab_type": "code",
                "id": "3OzZQiX751iz"
            },
            "outputs": [],
            "source": [
                "!head -n 5 {train_dataset}"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {
                "colab_type": "text",
                "id": "pD9bprV66Oai"
            },
            "source": [
                "# Data Augmentation Pipeline\n",
                "\n",
                "Constructing a data augmentation pipeline in NeMo is as simple as composing a nested dictionary that describes two things :\n",
                "\n",
                "1) The probability of that augmentation occurring - using the `prob` keyword <br>\n",
                "2) The keyword arguments required by that augmentation class\n",
                "\n",
                "Below, we show a few samples of these augmentations. Note, in order to distinguish between the original sample and the perturbed sample, we exaggerate the perturbation strength significantly."
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {
                "colab": {},
                "colab_type": "code",
                "id": "l5bc7gYO6MHG"
            },
            "outputs": [],
            "source": [
                "import torch\n",
                "import IPython.display as ipd"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {
                "colab_type": "text",
                "id": "L8Bd8s3e6TeK"
            },
            "source": [
                "## Audio file preparation "
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {
                "colab": {},
                "colab_type": "code",
                "id": "g7f9riZz6Qnj"
            },
            "outputs": [],
            "source": [
                "# Import the data augmentation component from ASR collection\n",
                "from nemo.collections.asr.parts.preprocessing import perturb, segment"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {
                "colab": {},
                "colab_type": "code",
                "id": "wK8uwpt16d6I"
            },
            "outputs": [],
            "source": [
                "# Lets see the available perturbations\n",
                "perturb.perturbation_types"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {
                "colab_type": "text",
                "id": "IP1VpkOA6nE-"
            },
            "source": [
                "### Obtain a baseline audio file"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {
                "colab": {},
                "colab_type": "code",
                "id": "sj4DNMmZ6ktm"
            },
            "outputs": [],
            "source": [
                "filepath = librosa.util.example(key='vibeace', hq=True)\n",
                "sample, sr = librosa.core.load(filepath)\n",
                "\n",
                "ipd.Audio(sample, rate=sr)"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {
                "colab_type": "text",
                "id": "M9mZNm296tNf"
            },
            "source": [
                "### Convert to WAV format"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {
                "colab": {},
                "colab_type": "code",
                "id": "QDjlgLc-6vtq"
            },
            "outputs": [],
            "source": [
                "import soundfile as sf\n",
                "\n",
                "# lets convert this ogg file into a wave to be compatible with NeMo\n",
                "if not os.path.exists('./media'):\n",
                "    os.makedirs('./media/')\n",
                "    \n",
                "filename = 'Kevin_MacLeod_-_Vibe_Ace.wav'\n",
                "filepath = os.path.join('media', filename)\n",
                "\n",
                "sf.write(filepath, sample, samplerate=sr)"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {
                "colab": {},
                "colab_type": "code",
                "id": "FEkV-ikT6xgB"
            },
            "outputs": [],
            "source": [
                "sample, sr = librosa.core.load(filepath)\n",
                "ipd.Audio(sample, rate=sr)"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {
                "colab": {},
                "colab_type": "code",
                "id": "gmuwEwIQ6zK3"
            },
            "outputs": [],
            "source": [
                "# NeMo has its own support class for loading wav files\n",
                "def load_audio() -> segment.AudioSegment:\n",
                "    filename = 'Kevin_MacLeod_-_Vibe_Ace.wav'\n",
                "    filepath = os.path.join('media', filename)\n",
                "    sample_segment = segment.AudioSegment.from_file(filepath, target_sr=sr)\n",
                "    return sample_segment\n",
                "\n",
                "sample_segment = load_audio()\n",
                "ipd.Audio(sample_segment.samples, rate=sr)"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {
                "colab_type": "text",
                "id": "hTnf1g1y63wZ"
            },
            "source": [
                "## White Noise Perturbation\n",
                "\n",
                "White Noise perturbation is performed by the following steps : <br>\n",
                "1) Randomly sample the amplitude of the noise from a uniformly distributed range (defined in dB) <br>\n",
                "2) Sample gaussian noise (mean = 0, std = 1) with same length as audio signal <br>\n",
                "3) Scale this gaussian noise by the amplitude (in dB scale) <br>\n",
                "4) Add this noise vector to the original sample\n",
                "\n",
                "Notably, the original signal should not have a \"hissing sound\" constantly present in the perturbed version."
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {
                "colab": {},
                "colab_type": "code",
                "id": "2jaPQyUY65ij"
            },
            "outputs": [],
            "source": [
                "white_noise = perturb.WhiteNoisePerturbation(min_level=-50, max_level=-30)\n",
                "\n",
                "# Perturb the audio file\n",
                "sample_segment = load_audio()\n",
                "white_noise.perturb(sample_segment)\n",
                "\n",
                "ipd.Audio(sample_segment.samples, rate=sr)"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {
                "colab_type": "text",
                "id": "2dfwesJU7DhN"
            },
            "source": [
                "## Shift Perturbation\n",
                "\n",
                "Shift perturbation is performed by the following steps : <br>\n",
                "1) Randomly sample the shift factor of the signal from a uniformly distributed range (defined in milliseconds) <br>\n",
                "2) Depending on the sign of the shift, we shift the original signal to the left or the right. <br>\n",
                "3) The boundary locations are filled with zeros after the shift of the signal <br>\n",
                "\n",
                "Notably, the perturbed signal below skips the first 25 to 50 seconds of the original audio below, and the remainder of the time is simply silence. "
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {
                "colab": {},
                "colab_type": "code",
                "id": "2ONq8dBI7BZf"
            },
            "outputs": [],
            "source": [
                "shift = perturb.ShiftPerturbation(min_shift_ms=25000.0, max_shift_ms=50000.0)\n",
                "\n",
                "# Perturb the audio file \n",
                "sample_segment = load_audio()\n",
                "shift.perturb(sample_segment)\n",
                "\n",
                "ipd.Audio(sample_segment.samples, rate=sr)"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {
                "colab_type": "text",
                "id": "kywA3h4T7G_S"
            },
            "source": [
                "## Data Dependent Perturbations\n",
                "\n",
                "Some perturbations require an external data source in order to perturb the original sample. Noise Perturbation is a perfect example of one such augmentation that requires an external noise source dataset in order to perturb the original data."
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {
                "colab_type": "text",
                "id": "eYm2DgGQ7KPe"
            },
            "source": [
                "### Preparing a manifest of \"noise\" samples"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {
                "colab": {},
                "colab_type": "code",
                "id": "RXZ1o85E7FLT"
            },
            "outputs": [],
            "source": [
                "# Lets prepare a manifest file using the baseline file itself, cut into 1 second segments\n",
                "\n",
                "def write_manifest(filepath, data_dir='./media/', manifest_name='noise_manifest', duration_max=None, duration_stride=1.0, filter_long=False, duration_limit=10.0):\n",
                "    if duration_max is None:\n",
                "        duration_max = 1e9\n",
                "                \n",
                "    with open(os.path.join(data_dir, manifest_name + '.json'), 'w') as fout:\n",
                "        \n",
                "        try:\n",
                "            x, _sr = librosa.load(filepath)\n",
                "            duration = librosa.get_duration(x, sr=_sr)\n",
                "\n",
                "        except Exception:\n",
                "            print(f\"\\n>>>>>>>>> WARNING: Librosa failed to load file {filepath}. Skipping this file !\\n\")\n",
                "            return\n",
                "\n",
                "        if filter_long and duration > duration_limit:\n",
                "            print(f\"Skipping sound sample {filepath}, exceeds duration limit of {duration_limit}\")\n",
                "            return\n",
                "\n",
                "        offsets = []\n",
                "        durations = []\n",
                "\n",
                "        if duration > duration_max:\n",
                "            current_offset = 0.0\n",
                "\n",
                "            while current_offset < duration:\n",
                "                difference = duration - current_offset\n",
                "                segment_duration = min(duration_max, difference)\n",
                "\n",
                "                offsets.append(current_offset)\n",
                "                durations.append(segment_duration)\n",
                "\n",
                "                current_offset += duration_stride\n",
                "\n",
                "        else:\n",
                "            offsets.append(0.0)\n",
                "            durations.append(duration)\n",
                "\n",
                "\n",
                "        for duration, offset in zip(durations, offsets):\n",
                "            metadata = {\n",
                "                'audio_filepath': filepath,\n",
                "                'duration': duration,\n",
                "                'label': 'noise',\n",
                "                'text': '_',  # for compatibility with ASRAudioText collection\n",
                "                'offset': offset,\n",
                "            }\n",
                "\n",
                "            json.dump(metadata, fout)\n",
                "            fout.write('\\n')\n",
                "            fout.flush()\n",
                "\n",
                "        print(f\"Wrote {len(durations)} segments for filename {filename}\")\n",
                "            \n",
                "    print(\"Finished preparing manifest !\")"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {
                "colab": {},
                "colab_type": "code",
                "id": "wLTT8jlP7NdU"
            },
            "outputs": [],
            "source": [
                "filename = 'Kevin_MacLeod_-_Vibe_Ace.wav'\n",
                "filepath = os.path.join('media', filename)\n",
                "\n",
                "# Write a \"noise\" manifest file\n",
                "write_manifest(filepath, manifest_name='noise_1s', duration_max=1.0, duration_stride=1.0)"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {
                "colab": {},
                "colab_type": "code",
                "id": "izbdrSmd7PY5"
            },
            "outputs": [],
            "source": [
                "# Lets read this noise manifest file\n",
                "noise_manifest_path = os.path.join('media', 'noise_1s.json')\n",
                "\n",
                "!head -n 5 {noise_manifest_path}"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {
                "colab": {},
                "colab_type": "code",
                "id": "82yq0TOV7Q_4"
            },
            "outputs": [],
            "source": [
                "# Lets create a helper method to load the first file in the train dataset of AN4\n",
                "# Load the first sample in the manifest\n",
                "def load_gsc_sample() -> segment.AudioSegment:\n",
                "    with open(train_dataset, 'r') as f:\n",
                "        line = f.readline()\n",
                "        \n",
                "    line = json.loads(line)\n",
                "    gsc_filepath = line['audio_filepath']\n",
                "    sample_segment = segment.AudioSegment.from_file(gsc_filepath)\n",
                "    return sample_segment\n",
                "\n",
                "gsc_sample_segment = load_gsc_sample()\n",
                "ipd.Audio(gsc_sample_segment.samples, rate=16000)"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {
                "colab_type": "text",
                "id": "zV9ypBqz7V9a"
            },
            "source": [
                "## Noise Augmentation\n",
                "\n",
                "Noise perturbation is performed by the following steps : <br>\n",
                "1) Randomly sample the amplitude scale of the noise sample from a uniformly distributed range (defined in dB) <br>\n",
                "2) Randomly choose an audio clip from the set of noise audio samples available <br>\n",
                "3) Compute the gain (in dB) required for the noise clip as compared to the original sample and scale the noise by this factor <br>\n",
                "4) If the noise snippet is of shorter duration than the original audio, then randomly select an index in time from the original sample, where the noise snippet will be added <br>\n",
                "5) If instead the noise snippet is longer than the duration of the original audio, then randomly subsegment the noise snippet and add the full snippet to the original audio <br>\n",
                "\n",
                "Notably, the noise perturbed sample should sound as if there are two sounds playing at the same time (overlapping audio) as compared to the original signal. The magnitude of the noise will be dependent on step (3) and the location where the noise is added will depend on steps (4) and (5)."
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {
                "colab": {},
                "colab_type": "code",
                "id": "cjSXci1v7Tlg"
            },
            "outputs": [],
            "source": [
                "import random\n",
                "rng = 42 #note you can use integer to be as random seed to reproduce result \n",
                "noise = perturb.NoisePerturbation(manifest_path=noise_manifest_path,\n",
                "                                  min_snr_db=-10, max_snr_db=-10,\n",
                "                                  max_gain_db=300.0, rng=rng)\n",
                "\n",
                "# Perturb the audio file \n",
                "sample_segment = load_gsc_sample()\n",
                "noise.perturb(sample_segment)\n",
                "\n",
                "ipd.Audio(sample_segment.samples, rate=16000)"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {},
            "source": [
                "## RIR and Noise Perturbation\n",
                "RIR augmentation with additive foreground and background noise.\n",
                "In this implementation audio data is augmented by first convolving the audio with a Room Impulse Response\n",
                "and then adding foreground noise and background noise at various SNRs. RIR, foreground and background noises\n",
                "should either be supplied with a manifest file or as tarred audio files (faster)."
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {},
            "source": [
                "### Prepare rir data and manifest"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {},
            "outputs": [],
            "source": [
                "# This is where the rir data will be downloaded.\n",
                "# Change this if you don't want the data to be extracted in the current directory.\n",
                "rir_data_path = '.'\n",
                "!python ../../scripts/dataset_processing/get_openslr_rir_data.py --data_root {rir_data_path}\n",
                "rir_manifest_path = os.path.join(rir_data_path, 'processed', 'rir.json')\n",
                "!head -n 3 {rir_manifest_path}"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {},
            "source": [
                "### Create RIR instance"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {},
            "outputs": [],
            "source": [
                "rir = perturb.RirAndNoisePerturbation(rir_manifest_path=rir_manifest_path, \n",
                "                                      rir_prob=1,\n",
                "                                      noise_manifest_paths=[noise_manifest_path], # use noise_manifest_path from previous step\n",
                "                                      bg_noise_manifest_paths=[noise_manifest_path],\n",
                "                                      min_snr_db=[20], # foreground noise snr\n",
                "                                      max_snr_db=[20],\n",
                "                                      bg_min_snr_db=[20], # background noise snr\n",
                "                                      bg_max_snr_db=[20],\n",
                "                                      noise_tar_filepaths=[None], # `[None]` to indicates that noise audio files are not tar.\n",
                "                                      bg_noise_tar_filepaths=[None])"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {},
            "source": [
                "### Perturb the audio"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {},
            "outputs": [],
            "source": [
                "sample_segment = load_gsc_sample()\n",
                "rir.perturb(sample_segment)\n",
                "ipd.Audio(sample_segment.samples, rate=16000)"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {
                "colab_type": "text",
                "id": "kJjUkGJu7ern"
            },
            "source": [
                "## Speed Perturbation\n",
                "\n",
                "Speed perturbation changes the speed of the speech, but does not preserve pitch of the sound. Try a few random augmentations to see how the pitch changes with change in duration of the audio file.\n",
                "\n",
                "**Note**: This is a very slow augmentation and is not advised to perform online augmentation for large datasets as it can dramatically increase training time."
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {
                "colab": {},
                "colab_type": "code",
                "id": "Ic-ziInU7ZKC"
            },
            "outputs": [],
            "source": [
                "resample_type = 'kaiser_best'  # Can be ['kaiser_best', 'kaiser_fast', 'fft', 'scipy']\n",
                "speed = perturb.SpeedPerturbation(sr, resample_type, min_speed_rate=0.5, max_speed_rate=2.0, num_rates=-1)\n",
                "\n",
                "# Perturb the audio file \n",
                "sample_segment = load_gsc_sample()\n",
                "speed.perturb(sample_segment)\n",
                "\n",
                "ipd.Audio(sample_segment.samples, rate=16000)"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {
                "colab_type": "text",
                "id": "bhHX3dyh7jPq"
            },
            "source": [
                "## Time Stretch Perturbation\n",
                "\n",
                "Time Stretch perturbation changes the speed of the speech, and also preserve pitch of the sound. \n",
                "Try a few random augmentations to see how the pitch remains close to the same with change in duration of the audio file."
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {
                "colab_type": "text",
                "id": "8_kNSfcK7lfP"
            },
            "source": [
                "### Note about speed optimizations\n",
                "\n",
                "Time stretch is a costly augmentation, and can easily cause training time to increase drastically. It is suggested that one installs the `numba` library using conda to use a more optimized augmentation kernel.\n",
                "\n",
                "```python\n",
                "conda install numba\n",
                "```"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {
                "colab": {},
                "colab_type": "code",
                "id": "Dpeb0QUZ7g3l"
            },
            "outputs": [],
            "source": [
                "time_stretch = perturb.TimeStretchPerturbation(min_speed_rate=0.5, max_speed_rate=2.0, num_rates=3)\n",
                "\n",
                "# Perturb the audio file \n",
                "sample_segment = load_gsc_sample()\n",
                "time_stretch.perturb(sample_segment)\n",
                "\n",
                "ipd.Audio(sample_segment.samples, rate=16000)"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {
                "colab_type": "text",
                "id": "vhH1-Ga87rCX"
            },
            "source": [
                "# Augmentation Pipeline\n",
                "\n",
                "The augmentation pipeline can be constructed in multiple ways, either explicitly by instantiating the objects of these perturbations or implicitly by providing the arguments to these augmentations as a nested dictionary.\n",
                "\n",
                "We will show both approaches in the following sections"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {
                "colab_type": "text",
                "id": "RC8_NOD97tlW"
            },
            "source": [
                "## Explicit definition"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {
                "colab_type": "text",
                "id": "UwWE7swo72WP"
            },
            "source": [
                "### Instantiate the perturbations"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {
                "colab": {},
                "colab_type": "code",
                "id": "GdLYn0hx7pRU"
            },
            "outputs": [],
            "source": [
                "perturbations = [\n",
                "    perturb.WhiteNoisePerturbation(min_level=-90, max_level=-46),\n",
                "    perturb.GainPerturbation(min_gain_dbfs=0, max_gain_dbfs=50),\n",
                "    perturb.NoisePerturbation(manifest_path=noise_manifest_path,\n",
                "                              min_snr_db=0, max_snr_db=50, max_gain_db=300.0)\n",
                "]"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {
                "colab_type": "text",
                "id": "CDSSbZ8w7zzR"
            },
            "source": [
                "### Select chance of perturbations being applied"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {
                "colab": {},
                "colab_type": "code",
                "id": "NmoxfLSL7xPJ"
            },
            "outputs": [],
            "source": [
                "probas = [1.0, 1.0, 0.5]"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {
                "colab_type": "text",
                "id": "wl0tnrMq79Jh"
            },
            "source": [
                "### Prepare the audio augmentation object"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {
                "colab": {},
                "colab_type": "code",
                "id": "nO6T4U4f767o"
            },
            "outputs": [],
            "source": [
                "augmentations = list(zip(probas, perturbations))\n",
                "\n",
                "audio_augmentations = perturb.AudioAugmentor(augmentations)\n",
                "audio_augmentations._pipeline"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {
                "colab_type": "text",
                "id": "9cgI9yUx8Cyv"
            },
            "source": [
                "## Implicit definition\n",
                "\n",
                "Implicit definitions are preferred since they can be prepared in the actual configuration object."
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {
                "colab": {},
                "colab_type": "code",
                "id": "tiqrKFTM7_mH"
            },
            "outputs": [],
            "source": [
                "perturb.perturbation_types  # Available perturbations"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {
                "colab_type": "text",
                "id": "dbeXwLdw8VEc"
            },
            "source": [
                "### Prepare the nested dictionary"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {
                "colab": {},
                "colab_type": "code",
                "id": "mbE0qEA98TRI"
            },
            "outputs": [],
            "source": [
                "audio_augmentations = dict(\n",
                "    white_noise = dict(\n",
                "        prob=1.0,\n",
                "        min_level=-90,\n",
                "        max_level=-46\n",
                "    ),\n",
                "    gain = dict(\n",
                "        prob=1.0,\n",
                "        min_gain_dbfs=0,\n",
                "        max_gain_dbfs=50\n",
                "    ),\n",
                "    noise = dict(\n",
                "        prob=0.5,\n",
                "        manifest_path=noise_manifest_path,\n",
                "        min_snr_db=0,\n",
                "        max_snr_db=50,\n",
                "        max_gain_db=300.0\n",
                "    )\n",
                ")\n",
                "\n",
                "audio_augmentations"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {
                "colab_type": "text",
                "id": "tcsoCe9-8ZM9"
            },
            "source": [
                "### Supply `augmentor` as an argument to the `model.train_ds` config\n",
                "\n",
                "Most of the common datasets used by ASR models support the keyword `augmentor` - which can include a nested dictionary defining the implicit definition of an augmentation pipeline.\n",
                "\n",
                "Note, all ASR models support implicit declaration of augmentations. This includes - \n",
                "\n",
                "1) Speech To Label Models <br>\n",
                "2) Speech To Text Models <br>\n",
                "3) Speech To Text Models with BPE/WPE Support<br>"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {
                "colab_type": "text",
                "id": "0WOJC0fdBL5J"
            },
            "source": [
                "# Training - Application of augmentations\n",
                "\n",
                "We will be describing the data loaders for a MatchboxNet model from the paper \"[MatchboxNet: 1D Time-Channel Separable Convolutional Neural Network Architecture for Speech Commands Recognition](https://arxiv.org/abs/2004.08531)\". The benefit of MatchboxNet over JASPER models is that they use Separable Convolutions, which greatly reduce the number of parameters required to get good model accuracy.\n",
                "\n",
                "<ins>Care must be taken not to apply augmentations to the test set!</ins>\n"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {
                "colab": {},
                "colab_type": "code",
                "id": "7iDWiIrzBzUA"
            },
            "outputs": [],
            "source": [
                "from omegaconf import OmegaConf"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {
                "colab": {},
                "colab_type": "code",
                "id": "yv3KWNjcAUnQ"
            },
            "outputs": [],
            "source": [
                "# We will download the MatchboxNet configuration file for either v1 or v2 dataset here\n",
                "DATASET_VER = 1\n",
                "\n",
                "if DATASET_VER == 1:\n",
                "  MODEL_CONFIG = \"matchboxnet_3x1x64_v1.yaml\"\n",
                "else:\n",
                "  MODEL_CONFIG = \"matchboxnet_3x1x64_v2.yaml\"\n",
                "\n",
                "if not os.path.exists(f\"configs/{MODEL_CONFIG}\"):\n",
                "  !wget -P configs/ \"https://raw.githubusercontent.com/NVIDIA/NeMo/$BRANCH/examples/asr/conf/matchboxnet/{MODEL_CONFIG}\""
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {
                "colab": {},
                "colab_type": "code",
                "id": "vOcv0ri3BkmA"
            },
            "outputs": [],
            "source": [
                "# This line will load the entire config of the MatchboxNet model\n",
                "config_path = f\"configs/{MODEL_CONFIG}\"\n",
                "config = OmegaConf.load(config_path)"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {
                "colab_type": "text",
                "id": "mLsyceMSCIHV"
            },
            "source": [
                "### Augmentation in train set only\n",
                "\n",
                "Note how the train dataset config supports the `augmentor` implicit definition, however the test config does not.\n",
                "\n",
                "This is essential to avoid mistakenly performing Test Time Augmentation."
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {
                "colab": {},
                "colab_type": "code",
                "id": "VgUVm7lGB8Cz"
            },
            "outputs": [],
            "source": [
                "# Has `augmentor`\n",
                "print(OmegaConf.to_yaml(config.model.train_ds))"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {
                "colab": {},
                "colab_type": "code",
                "id": "gURwQ2eyCE7o"
            },
            "outputs": [],
            "source": [
                "# Does not have `augmentor`\n",
                "print(OmegaConf.to_yaml(config.model.test_ds))"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {
                "colab_type": "text",
                "id": "_UV74AVlCo_m"
            },
            "source": [
                "# Custom Perturbations\n",
                "\n",
                "We can define and use custom perturbations as required simply by extending the `Perturbation` class. \n",
                "\n",
                "Let's look at how we can build a custom Noise Perturbation that we can use to evaluate the effect of noise at inference time, in order to measure the model's robustness to noise\n",
                "\n",
                "In evaluation mode, we want to set an explicit value for the `snr_db` parameter instead of uniformly sample it from a range. This allows us to control the signal to noise ratio without relying on randomness from the training implementation of `NoisePerturbation`.\n",
                "\n",
                "Further, we force a random seed in order to produce reproduceable results on the evaluation set.\n",
                "\n",
                "With this combination, we can easily evaluate each sample in the test set `S` times (`S` being the number of random seeds), and can evaluate each of these samples at `D` levels of Signal to Noise Ratio (in dB). "
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {
                "colab": {},
                "colab_type": "code",
                "id": "Q9YBmBiZCbAX"
            },
            "outputs": [],
            "source": [
                "# We use a NeMo utility to parse the manifest file for us\n",
                "from nemo.collections.common.parts.preprocessing import collections, parsers\n",
                "\n",
                "class NoisePerturbationEval(perturb.Perturbation):\n",
                "    def __init__(\n",
                "        self, manifest_path=None, snr_db=40, max_gain_db=300.0, rng=None,\n",
                "    ):\n",
                "        self._manifest = collections.ASRAudioText(manifest_path, parser=parsers.make_parser([]))\n",
                "        self._snr_db = snr_db\n",
                "        self._max_gain_db = max_gain_db\n",
                "        random.seed(rng) if rng else None\n",
                "    \n",
                "    # This is mostly obtained from the original NoisePerturbation class itself\n",
                "    def perturb(self, data):\n",
                "        snr_db = self._snr_db\n",
                "        noise_record = random.sample(self._manifest.data, 1)[0]\n",
                "        noise = AudioSegment.from_file(noise_record.audio_file, target_sr=data.sample_rate)\n",
                "        noise_gain_db = min(data.rms_db - noise.rms_db - snr_db, self._max_gain_db)\n",
                "\n",
                "        # calculate noise segment to use\n",
                "        start_time = 0.0\n",
                "        if noise.duration > (start_time + data.duration):\n",
                "            noise.subsegment(start_time=start_time, end_time=start_time + data.duration)\n",
                "\n",
                "        # adjust gain for snr purposes and superimpose\n",
                "        noise.gain_db(noise_gain_db)\n",
                "\n",
                "        if noise._samples.shape[0] < data._samples.shape[0]:\n",
                "            noise_idx = data._samples.shape[0] // 2  # midpoint of audio\n",
                "            while (noise_idx + noise._samples.shape[0]) > data._samples.shape[0]:\n",
                "                noise_idx = noise_idx // 2  # half the initial starting point\n",
                "\n",
                "            data._samples[noise_idx: noise_idx + noise._samples.shape[0]] += noise._samples\n",
                "\n",
                "        else:\n",
                "            data._samples += noise._samples\n"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {
                "colab_type": "text",
                "id": "qR8qiwSkC1eE"
            },
            "source": [
                "## Registering augmentations\n",
                "\n",
                "We can use either approach to submit this test time augmentation to the Data Loaders.\n",
                "\n",
                "In order to obtain the convenience of the implicit method, we must register this augmentation into NeMo's directory of available augmentations. This can be done as follows -"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {
                "colab": {},
                "colab_type": "code",
                "id": "40Z4Fm88CxWA"
            },
            "outputs": [],
            "source": [
                "perturb.register_perturbation(name='noise_eval', perturbation=NoisePerturbationEval)"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {
                "colab": {},
                "colab_type": "code",
                "id": "jVVbRxb-C4hB"
            },
            "outputs": [],
            "source": [
                "# Lets check the registry of allowed perturbations !\n",
                "perturb.perturbation_types"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {
                "colab_type": "text",
                "id": "2fiHz6CdC-B1"
            },
            "source": [
                "## Overriding pre-existing augmentations\n",
                "\n",
                "**Note**: It is not allowed to overwrite already registered perturbations using the `perturb.register_perturbation` method. It will raise a `ValueError` in order to prevent overwriting the pre-existing perturbation types"
            ]
        }
    ],
    "metadata": {
        "accelerator": "GPU",
        "colab": {
            "collapsed_sections": [],
            "name": "Online_Noise_Augmentation.ipynb",
            "provenance": [],
            "toc_visible": true
        },
        "kernelspec": {
            "display_name": "Python 3",
            "language": "python",
            "name": "python3"
        },
        "language_info": {
            "codemirror_mode": {
                "name": "ipython",
                "version": 3
            },
            "file_extension": ".py",
            "mimetype": "text/x-python",
            "name": "python",
            "nbconvert_exporter": "python",
            "pygments_lexer": "ipython3",
            "version": "3.7.7"
        },
        "pycharm": {
            "stem_cell": {
                "cell_type": "raw",
                "metadata": {
                    "collapsed": false
                },
                "source": []
            }
        }
    },
    "nbformat": 4,
    "nbformat_minor": 4
}