File size: 28,958 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
{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "accelerator": "GPU",
    "colab": {
      "name": "CTC_Segmentation_Tutorial_update.ipynb",
      "private_outputs": true,
      "provenance": [],
      "collapsed_sections": [],
      "toc_visible": true
    },
    "kernelspec": {
      "display_name": "Python 3 (ipykernel)",
      "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.9.7"
    }
  },
  "cells": [
    {
      "cell_type": "code",
      "metadata": {
        "id": "d4KCUoxSpdoZ"
      },
      "source": [
        "BRANCH = 'r1.17.0'\n",
        "\n",
        "\"\"\"\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",
        "\"\"\""
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "JDk9zxC6pdod"
      },
      "source": [
        "import os\n",
        "# either provide a path to local NeMo repository with NeMo already installed or git clone\n",
        "\n",
        "# option #1: local path to NeMo repo with NeMo already installed\n",
        "NEMO_DIR_PATH = \"NeMo\"\n",
        "\n",
        "# option #2: download NeMo repo\n",
        "if 'google.colab' in str(get_ipython()) or not os.path.exists(NEMO_DIR_PATH):\n",
        "  ! git clone -b $BRANCH https://github.com/NVIDIA/NeMo\n",
        "  % cd NeMo\n",
        "  ! python -m pip install git+https://github.com/NVIDIA/NeMo.git@$BRANCH#egg=nemo_toolkit[all]"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "CH7yR7cSwPKr"
      },
      "source": [
        "import json\n",
        "import os\n",
        "import wget\n",
        "\n",
        "from IPython.display import Audio\n",
        "import numpy as np\n",
        "import scipy.io.wavfile as wav\n",
        "\n",
        "! pip install pandas\n",
        "! pip install plotly\n",
        "from plotly import graph_objects as go"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "xXRARM8XtK_g"
      },
      "source": [
        "# 1. Introduction\n",
        "End-to-end Automatic Speech Recognition (ASR) systems surpassed traditional systems in performance but require large amounts of labeled data for training. \n",
        "\n",
        "This tutorial will show how to use a pre-trained with Connectionist Temporal Classification (CTC) ASR model, such as [QuartzNet Model](https://arxiv.org/abs/1910.10261) or [Citrinet](https://arxiv.org/abs/2104.01721) to split long audio files and the corresponding transcripts into shorter fragments that are suitable for an ASR model training. \n",
        "\n",
        "We're going to use [ctc-segmentation](https://github.com/lumaku/ctc-segmentation) Python package based on the algorithm described in [CTC-Segmentation of Large Corpora for German End-to-end Speech Recognition](https://arxiv.org/pdf/2007.09127.pdf)."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "8FAZKakrIyGI"
      },
      "source": [
        "requirements = f'https://raw.githubusercontent.com/NVIDIA/NeMo/{BRANCH}/tools/ctc_segmentation/requirements.txt'\n",
        "wget.download(requirements)\n",
        "! pip install -r requirements.txt\n",
        "! apt-get install -y ffmpeg"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "S1DZk-inQGTI"
      },
      "source": [
        "`TOOLS_DIR` contains scripts that we are going to need during the next steps, all necessary scripts could be found [here](https://github.com/NVIDIA/NeMo/tree/main/tools/ctc_segmentation/scripts)."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "1C9DdMfvRFM-"
      },
      "source": [
        "if 'google.colab' in str(get_ipython()):\n",
        "  NEMO_DIR_PATH = \"/content/NeMo\"\n",
        "elif not os.path.exists(NEMO_DIR_PATH):\n",
        "  NEMO_DIR_PATH = \"NeMo\"\n",
        "    \n",
        "TOOLS_DIR = f'{NEMO_DIR_PATH}/tools/ctc_segmentation/scripts'\n",
        "print(TOOLS_DIR)\n",
        "! ls -l $TOOLS_DIR"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "XUEncnqTIzF6"
      },
      "source": [
        "# 2. Data Download\n",
        "First, let's download audio and text data (data source: [https://librivox.org/](https://librivox.org/) and [http://www.gutenberg.org](http://www.gutenberg.org)."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "bkeKX2I_tIgV"
      },
      "source": [
        "## create data directory and download an audio file\n",
        "WORK_DIR = 'WORK_DIR'\n",
        "DATA_DIR = WORK_DIR + '/DATA'\n",
        "os.makedirs(DATA_DIR, exist_ok=True)\n",
        "\n",
        "print('downloading audio samples...')\n",
        "wget.download(\"https://multilangaudiosamples.s3.us-east-2.amazonaws.com/audio_samples.zip\", DATA_DIR)\n",
        "! unzip -o $DATA_DIR/audio_samples.zip -d $DATA_DIR\n",
        "! rm $DATA_DIR/audio_samples.zip\n",
        "\n",
        "DATA_DIR = os.path.join(DATA_DIR, \"audio_samples\")"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "2JAv7ePmpdok"
      },
      "source": [
        "We downloaded audio and text samples in `English` and `Spanish`:"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "Y6VYVk9mpdol"
      },
      "source": [
        "! ls $DATA_DIR"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "-_XE9MkKuAA7"
      },
      "source": [
        "Data folder for each language contains both audio and text files. Note, the text file and the audio file share the same base name. For example, an audio file `example.wav` should have a corresponding text file called `example.txt`."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "IGhijb-Bpdol"
      },
      "source": [
        "! ls $DATA_DIR/es/audio/ $DATA_DIR/es/text/"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "FWqlbSryw_WL"
      },
      "source": [
        "# 3. Segmentation of a single file (Spanish sample)\n",
        "\n",
        "Let's listen to our Spanish audio sample:"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "ulkPrqwipdom"
      },
      "source": [
        "base_name_es = \"el19demarzoyel2demayo_03_perezgaldos\"\n",
        "Audio(f\"{DATA_DIR}/es/audio/{base_name_es}.wav\")"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "RzlLsmMXpdom"
      },
      "source": [
        "Let's take a look at the ground truth text:"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "9Qfp10Xnpdom"
      },
      "source": [
        "text = f\"{DATA_DIR}/es/text/{base_name_es}.txt\"\n",
        "! cat $text"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "RMT5lkPYzZHK"
      },
      "source": [
        "As one probably noticed, the audio file contains a prologue and an epilogue that are missing in the corresponding text. The segmentation algorithm could handle extra audio fragments at the end and the beginning of the audio, but prolonged untranscribed audio segments in the middle of the file could deteriorate segmentation results. That is why, it is recommended to normalize text, so that transcripts contain spoken equivalents of abbreviations and numbers.\n",
        "\n",
        "## 3.1. Prepare Text and Audio\n",
        "\n",
        "We're going to use `prepare_data.py` script to prepare both text and audio data for segmentation.\n",
        "\n",
        "### Text preprocessing:\n",
        "* the text will be roughly split into sentences and stored under '$OUTPUT_DIR/processed/*.txt' where each sentence is going to start with a new line (we're going to find alignments for these sentences in the next steps)\n",
        "* to change the lengths of the final sentences/fragments, specify additional punctuation marks to split the text into fragments, use `--additional_split_symbols` argument. Use `|` as a separator between symbols, for example: `--additional_split_symbols=;|:`\n",
        "* `max_length` argument - max number of words in a segment for alignment (used only if there are no punctuation marks present in the original text. Long non-speech segments are better for segments split and are more likely to co-occur with punctuation marks. Random text split could deteriorate the quality of the alignment.\n",
        "* out-of-vocabulary words will be removed based on pre-trained ASR model vocabulary, and the text will be changed to lowercase \n",
        "* sentences for alignment with the original punctuation and capitalization will be stored under  `$OUTPUT_DIR/processed/*_with_punct.txt`\n",
        "* numbers will be converted from written to their spoken form with `num2words` package. For English, it's recommended to use NeMo normalization tool use `--use_nemo_normalization` argument (not supported if running this segmentation tutorial in Colab, see the text normalization tutorial: [`tutorials/text_processing/Text_Normalization.ipynb`](https://colab.research.google.com/github/NVIDIA/NeMo/blob/stable/tutorials/text_processing/Text_Normalization.ipynb) for more details). Even `num2words` normalization is usually enough for proper segmentation. However, it does not take audio into account. NeMo supports audio-based normalization for English, German and Russian languages that can be applied to the segmented data as a post-processing step. Audio-based normalization produces multiple normalization options. For example, `901` could be normalized as `nine zero one` or `nine hundred and one`. The audio-based normalization chooses the best match among the possible normalization options and the transcript based on the character error rate. Note, the audio-based normalization of long audio samples is not supported due to multiple normalization options. See [NeMo/nemo_text_processing/text_normalization/normalize_with_audio.py](https://github.com/NVIDIA/NeMo/blob/stable/nemo_text_processing/text_normalization/normalize_with_audio.py) for more details.\n",
        "\n",
        "### Audio preprocessing:\n",
        "* non '.wav' audio files will be converted to `.wav` format\n",
        "* audio files will be resampled to 16kHz (sampling rate used during training NeMo ASR models)\n",
        "* stereo tracks will be converted to mono\n",
        "* In some cases, if an audio contains a very long untranscribed prologue, increasing `--cut_prefix` value might help improve segmentation quality.\n",
        "\n",
        "\n",
        "The `prepare_data.py` will preprocess all `.txt` files found in the `--in_text=$DATA_DIR` and all audio files located at `--audio_dir=$DATA_DIR`.\n",
        "\n",
        "We are going to use [Spanish Citrinet-512 model](https://catalog.ngc.nvidia.com/orgs/nvidia/teams/nemo/models/stt_es_citrinet_512)."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "u4zjeVVv-UXR"
      },
      "source": [
        "MODEL = \"stt_es_citrinet_512\" \n",
        "OUTPUT_DIR = WORK_DIR + \"/es_output\"\n",
        "\n",
        "! rm -rf $OUTPUT_DIR\n",
        "\n",
        "! python $TOOLS_DIR/prepare_data.py \\\n",
        "--in_text=$DATA_DIR/es/text \\\n",
        "--output_dir=$OUTPUT_DIR/processed/ \\\n",
        "--language='en' \\\n",
        "--model=$MODEL \\\n",
        "--audio_dir=$DATA_DIR/es/audio"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "kmDTCuTLH7pm"
      },
      "source": [
        "The following four files should be generated and stored at the `$OUTPUT_DIR/processed` folder:\n",
        "\n",
        "* el19demarzoyel2demayo_03_perezgaldos.txt (lower cased and normalized text with punctuation removed, each line represents an utterance for alignment)\n",
        "* el19demarzoyel2demayo_03_perezgaldos.wav (.wav mono file, 16kHz)\n",
        "* el19demarzoyel2demayo_03_perezgaldos_with_punct.txt  (raw utterances for alignment with punctuation and case preserved)\n",
        "* el19demarzoyel2demayo_03_perezgaldos_with_punct_normalized.txt (normalized utterances for alignment utterance for alignment with punctuation and case preserved)"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "6R7OKAsYH9p0"
      },
      "source": [
        "! ls $OUTPUT_DIR/processed"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "bIvKBwRcH_9W"
      },
      "source": [
        "The `.txt` file without punctuation contains preprocessed text phrases that we're going to align within the audio file. Here, we split the text into sentences. Each line should contain a text snippet for alignment."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "74GLpMgoICmk"
      },
      "source": [
        "! head $OUTPUT_DIR/processed/el19demarzoyel2demayo_03_perezgaldos.txt"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "QrvZAjeoR9U1"
      },
      "source": [
        "## 3.2. Run CTC-Segmentation\n",
        "\n",
        "In this step, we're going to use the [`ctc-segmentation`](https://github.com/lumaku/ctc-segmentation) to find the start and end time stamps for the segments we created during the previous step.\n",
        "\n",
        "\n",
        "As described in the [CTC-Segmentation of Large Corpora for German End-to-end Speech Recognition](https://arxiv.org/pdf/2007.09127.pdf), the algorithm is relying on a CTC-based ASR model to extract utterance segments with exact time-wise alignments. "
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "xyKtaqAd-Tvk"
      },
      "source": [
        "WINDOW = 8000\n",
        "\n",
        "! python $TOOLS_DIR/run_ctc_segmentation.py \\\n",
        "--output_dir=$OUTPUT_DIR \\\n",
        "--data=$OUTPUT_DIR/processed \\\n",
        "--model=$MODEL \\\n",
        "--window_len=$WINDOW "
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "wY27__e3HmhH"
      },
      "source": [
        "`WINDOW` parameter might need to be adjusted depending on the length of the utterance one wants to align, the default value should work in most cases. By default, if the alignment is not found for the initial `WINDOW` size, the window size will be doubled a few times to re-try backtracing. \n",
        "\n",
        "Let's take a look at the generated alignments."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "ktBAsfJRVCwI"
      },
      "source": [
        "alignment_file = f\"{WINDOW}_{base_name_es}_segments.txt\"\n",
        "! head -n 3 $OUTPUT_DIR/segments/$alignment_file"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "xCwEFefHZz1C"
      },
      "source": [
        "The expected output for our audio sample looks like this:\n",
        "\n",
        "```\n",
        "<PATH_TO>/processed/el19demarzoyel2demayo_03_perezgaldos.wav\n",
        "11.518331881862931 25.916246734191596 -1.2629864680237006 | entraron en la habitaci贸n donde est谩bamos y al punto que d mauro vio a su sobrina dirigiose a ella con los brazos abiertos y al estrecharla en ellos exclam贸 endulzando la voz 隆in茅s de mi alma inocente hija de mi prima juana | Entraron en la habitaci贸n donde est谩bamos, y al punto que D.  Mauro vio a su sobrina dirigiose a ella con los brazos abiertos, y al estrecharla en ellos, exclam贸 endulzando la voz: -隆In茅s de mi alma, inocente hija de mi prima Juana! | Entraron en la habitaci贸n donde est谩bamos, y al punto que D.  Mauro vio a su sobrina dirigiose a ella con los brazos abiertos, y al estrecharla en ellos, exclam贸 endulzando la voz: - In茅s de mi alma, inocente hija de mi prima Juana!\n",
        "25.756269902499053 28.155922377887165 -0.0003830735786323203 | al fin al fin te veo | Al fin, al fin te veo. | Al fin, al fin te veo.\n",
        "...\n",
        "```\n",
        "\n",
        "**Details of the file content**:\n",
        "- the first line of the file contains the path to the original audio file\n",
        "- all subsequent lines contain:\n",
        "  * the first number is the start of the segment (in seconds)\n",
        "  * the second one is the end of the segment (in seconds)\n",
        "  * the third value - alignment confidence score (in log space)\n",
        "  * text fragments corresponding to the timestamps\n",
        "  * original text without pre-processing\n",
        "  * normalized text\n",
        "\n",
        "Finally, we're going to split the original audio file into segments based on the found alignments. We're going to save only segments with alignment score above the threshold value (default threshold=-2:\n",
        "* high scored clips (segments with the segmentation score above the threshold value)\n",
        "* low scored clips (segments with the segmentation score below the threshold)\n",
        "* deleted segments (segments that were excluded during the alignment. For example, in our sample audio file, the prologue and epilogue that don't have the corresponding transcript were excluded. Oftentimes, deleted files also contain such things as clapping, music, or hard breathing. \n",
        "\n",
        "The alignment score values depend on the pre-trained model quality and the dataset.\n",
        "\n",
        "Also note, that the `OFFSET` parameter is something one might want to experiment with since timestamps have a delay (offset) depending on the model.\n"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "6YM64RPlitPL"
      },
      "source": [
        "OFFSET = 0\n",
        "THRESHOLD = -2\n",
        "\n",
        "! python $TOOLS_DIR/cut_audio.py \\\n",
        "--output_dir=$OUTPUT_DIR \\\n",
        "--alignment=$OUTPUT_DIR/segments/ \\\n",
        "--threshold=$THRESHOLD \\\n",
        "--offset=$OFFSET"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "QoyS0T8AZxcx"
      },
      "source": [
        "## 3.3. Transcribe segmented audio\n",
        "\n",
        "The transcripts will be saved in a new manifest file in `pred_text` field."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "1UaSIflBZwaV"
      },
      "source": [
        "wget.download(f'https://raw.githubusercontent.com/NVIDIA/NeMo/{BRANCH}/examples/asr/transcribe_speech.py')\n",
        "\n",
        "! python transcribe_speech.py \\\n",
        "pretrained_name=$MODEL \\\n",
        "dataset_manifest=$OUTPUT_DIR/manifests/manifest.json \\\n",
        "output_filename=$OUTPUT_DIR/manifests/manifest_transcribed.json"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "F-nPT8z_IVD-"
      },
      "source": [
        "def plot_signal(signal, sample_rate):\n",
        "    \"\"\" Plot the signal in time domain \"\"\"\n",
        "    fig_signal = go.Figure(\n",
        "        go.Scatter(x=np.arange(signal.shape[0])/sample_rate,\n",
        "                   y=signal, line={'color': 'green'},\n",
        "                   name='Waveform',\n",
        "                   hovertemplate='Time: %{x:.2f} s<br>Amplitude: %{y:.2f}<br><extra></extra>'),\n",
        "        layout={\n",
        "            'height': 200,\n",
        "            'xaxis': {'title': 'Time, s'},\n",
        "            'yaxis': {'title': 'Amplitude'},\n",
        "            'title': 'Audio Signal',\n",
        "            'margin': dict(l=0, r=0, t=40, b=0, pad=0),\n",
        "        }\n",
        "    )\n",
        "    fig_signal.show()\n",
        "    \n",
        "def display_samples(manifest):\n",
        "    \"\"\" Display audio and reference text.\"\"\"\n",
        "    with open(manifest, 'r') as f:\n",
        "        for line in f:\n",
        "            sample = json.loads(line)\n",
        "            sample_rate, signal = wav.read(sample['audio_filepath'])\n",
        "            plot_signal(signal, sample_rate)\n",
        "            display(Audio(sample['audio_filepath']))\n",
        "            display('Reference text:       ' + sample['text_no_preprocessing'])\n",
        "            if 'pred_text' in sample:\n",
        "                display('ASR transcript: ' + sample['pred_text'])\n",
        "            print(f\"Score: {sample['score']}\")\n",
        "            print('\\n' + '-' * 110)"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "S69UFA30ZvxV"
      },
      "source": [
        "Let's examine the high scored segments we obtained.\n",
        "\n",
        "The `Reference text` in the next cell represents the original text without pre-processing, while `ASR transcript` is an ASR model prediction with greedy decoding. Also notice, that `ASR transcript` in some cases contains errors that could decrease the alignment score, but usually it doesn鈥檛 hurt the quality of the aligned segments.\n",
        "\n",
        "Displaying audio in Jupyter Notebook could be slow, it's recommended to use [Speech Data Explorer](https://docs.nvidia.com/deeplearning/nemo/user-guide/docs/en/stable/tools/speech_data_explorer.html) to analyze speech data."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "Q45uBtsHIaAD"
      },
      "source": [
        "# let's examine only a few first samples\n",
        "! head -n 2 $OUTPUT_DIR/manifests/manifest_transcribed.json > $OUTPUT_DIR/manifests/samples.json\n",
        "\n",
        "display_samples(f\"{OUTPUT_DIR}/manifests/samples.json\")"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "yivXpD25T4Ir"
      },
      "source": [
        "# 4. Processing of multiple files (English samples)\n",
        "\n",
        "Up until now, we were processing only one file at a time, but to create a large dataset processing of multiple files simultaneously could help speed up things considerably. \n",
        "\n",
        "Our English data folder contains 2 audio files and corresponding text files:"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "KRc9yMjPXPgj"
      },
      "source": [
        "! ls $DATA_DIR/en/audio $DATA_DIR/en/text"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "3ftilXu-5tzT"
      },
      "source": [
        "We are going to use `run_segmentation.sh` to perform all the above steps starting from the text and audio preprocessing to segmentation and manifest creation in a single step:"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "2I4w34Hepdor"
      },
      "source": [
        "`run_segmentation.sh` script takes `DATA_DIR` argument and assumes that it contains folders `text` and `audio`.\n",
        "An example of the `DATA_DIR` folder structure:\n",
        "\n",
        "\n",
        "--DATA_DIR\n",
        "\n",
        "     |----audio\n",
        "            |---1.mp3\n",
        "            |---2.mp3\n",
        "            \n",
        "     |-----text\n",
        "            |---1.txt\n",
        "            |---2.txt"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "nYXNvBDsHMEu"
      },
      "source": [
        "`run_segmentation.sh` could use multiple `WINDOW` sizes for segmentation, and then adds segments that were similarly aligned with various window sizes to `verified_segments` folder. This could be useful to reduce the amount of manual work while checking the alignment quality."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "hRFAl0gO92bp"
      },
      "source": [
        "MODEL = \"QuartzNet15x5Base-En\" # \"stt_en_citrinet_512_gamma_0_25\" \n",
        "OUTPUT_DIR_2 = WORK_DIR + \"/en_output\"\n",
        "\n",
        "! rm -rf $OUTPUT_DIR_2\n",
        "\n",
        "! bash $TOOLS_DIR/../run_segmentation.sh \\\n",
        "--MODEL_NAME_OR_PATH=$MODEL \\\n",
        "--DATA_DIR=$DATA_DIR/en \\\n",
        "--OUTPUT_DIR=$OUTPUT_DIR_2 \\\n",
        "--SCRIPTS_DIR=$TOOLS_DIR \\\n",
        "--MIN_SCORE=$THRESHOLD  \\\n",
        "--USE_NEMO_NORMALIZATION=False"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "zzJTwKq2Kl9U"
      },
      "source": [
        "Manifest file with segments with alignment score above the threshold values are saved in `en/output/manifests/manifest.json`.\n",
        "\n",
        "Next, we are going to run `run_filter.sh`. The script does the following:\n",
        "* adds ASR transcripts to the manifest\n",
        "* calculates and saves metrics such as Word Error Rate (WER), Character Error Rate (CER), CER at the tails of the audio file, word difference between reference and transcript, mean absolute values at the tails of the audio.\n",
        "* filters out samples that do not satisfy threshold values and saves selected segments in `manifest_transcribed_metrics_filtered.json`.\n",
        "\n",
        "Note, it's better to analyze the manifest with metrics in Speech Data Explorer to decide on what thresholds should be used for final sample selection."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "xsm89hYlpdor"
      },
      "source": [
        "! bash $TOOLS_DIR/../run_filter.sh \\\n",
        "--SCRIPTS_DIR=$TOOLS_DIR \\\n",
        "--MODEL_NAME_OR_PATH=stt_en_conformer_ctc_large \\\n",
        "--MANIFEST=$OUTPUT_DIR_2/manifests/manifest.json \\\n",
        "--INPUT_AUDIO_DIR=$DATA_DIR/en/audio/"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "nacE_iQ2_85L"
      },
      "source": [
        "# let's examine only a few first samples\n",
        "! head -n 2 $OUTPUT_DIR_2/manifests/manifest_transcribed_metrics_filtered.json > $OUTPUT_DIR_2/manifests/samples.json\n",
        "\n",
        "display_samples(f\"{OUTPUT_DIR_2}/manifests/samples.json\")"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "lcvT3P2lQ_GS"
      },
      "source": [
        "# Next Steps\n",
        "\n",
        "- Check out [NeMo Speech Data Explorer tool](https://github.com/NVIDIA/NeMo/tree/main/tools/speech_data_explorer#speech-data-explorer) to interactively evaluate the aligned segments.\n",
        "- Try Audio-based normalization tool."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "GYylwvTX2VSF"
      },
      "source": [
        "# References\n",
        "K眉rzinger, Ludwig, et al. [\"CTC-Segmentation of Large Corpora for German End-to-End Speech Recognition.\"](https://arxiv.org/abs/2007.09127) International Conference on Speech and Computer. Springer, Cham, 2020."
      ]
    }
  ]
}