File size: 21,859 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
{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "name": "Offline_ASR.ipynb",
      "provenance": [],
      "collapsed_sections": [],
      "toc_visible": true
    },
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    },
    "accelerator": "GPU"
  },
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "_wIWPxBVc3_O"
      },
      "source": [
        "# NeMo offline ASR\n",
        "\n",
        "This notebook demonstrates how to  \n",
        "\n",
        "* transcribe an audio file (offline ASR) with greedy decoder\n",
        "* extract timestamps information from the model to split audio into separate words\n",
        "* use beam search decoder with N-gram language model re-scoring\n",
        "\n",
        "You may find more info on how to train and use language models for ASR models here:\n",
        "https://docs.nvidia.com/deeplearning/nemo/user-guide/docs/en/main/asr/asr_language_modeling.html\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "gzcsqceVdtj3"
      },
      "source": [
        "## Installation\n",
        "NeMo can be installed via simple pip command. \n",
        "\n",
        "Optional CTC beam search decoder might require restart of Colab runtime after installation."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "I9eIxAyKHREB"
      },
      "source": [
        "BRANCH = 'r1.17.0'\n",
        "try:\n",
        "    # Import NeMo Speech Recognition collection\n",
        "    import nemo.collections.asr as nemo_asr\n",
        "except ModuleNotFoundError:\n",
        "    !python -m pip install git+https://github.com/NVIDIA/NeMo.git@$BRANCH#egg=nemo_toolkit[all]\n",
        "\n",
        "# check if we have optional Plotly for visualization\n",
        "try:\n",
        "    from plotly import graph_objects as go\n",
        "except ModuleNotFoundError:\n",
        "    !pip install plotly\n",
        "    from plotly import graph_objects as go\n",
        "\n",
        "# check if we have optional ipywidgets for tqdm/notebook\n",
        "try:\n",
        "    import ipywidgets\n",
        "except ModuleNotFoundError:\n",
        "    !pip install ipywidgets\n",
        "\n",
        "# check if CTC beam decoders are installed\n",
        "try:\n",
        "    import ctc_decoders\n",
        "except ModuleNotFoundError:\n",
        "    # install beam search decoder\n",
        "    !apt-get update && apt-get install -y swig\n",
        "    !git clone https://github.com/NVIDIA/NeMo -b \"$BRANCH\"\n",
        "    !cd NeMo && bash scripts/asr_language_modeling/ngram_lm/install_beamsearch_decoders.sh\n",
        "    print('Restarting Colab runtime to successfully import built module.')\n",
        "    print('Please re-run the notebook.')\n",
        "    import os\n",
        "    os.kill(os.getpid(), 9)"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "-X2OyAxreGfl"
      },
      "source": [
        "import numpy as np\n",
        "# Import audio processing library\n",
        "import librosa\n",
        "# We'll use this to listen to audio\n",
        "from IPython.display import Audio, display"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "zodyzdyTVXas"
      },
      "source": [
        "## Instantiate pre-trained NeMo model\n",
        "``from_pretrained(...)`` API downloads and initializes model directly from the cloud. \n",
        "\n",
        "Alternatively, ``restore_from(...)`` allows loading a model from a disk.\n",
        "\n",
        "To display available pre-trained models from the cloud, please use ``list_available_models()`` method."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "f_J9cuU1H6Bn"
      },
      "source": [
        "nemo_asr.models.EncDecCTCModel.list_available_models()"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "x2LMVI9qqtEV"
      },
      "source": [
        "Let's load a base English QuartzNet15x5 model."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "ZhWmR7lbvwSm"
      },
      "source": [
        "asr_model = nemo_asr.models.EncDecCTCModel.from_pretrained(model_name='QuartzNet15x5Base-En', strict=False)"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "HESTZmIzzCEj"
      },
      "source": [
        "## Get test audio clip"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "QPWn89l-zLXo"
      },
      "source": [
        "Let's download and analyze a test audio signal."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "02gDfK7czSVV"
      },
      "source": [
        "# Download audio sample which we'll try\n",
        "# This is a sample from LibriSpeech dev clean subset - the model hasn't seen it before\n",
        "AUDIO_FILENAME = '1919-142785-0028.wav'\n",
        "!wget https://dldata-public.s3.us-east-2.amazonaws.com/1919-142785-0028.wav\n",
        "\n",
        "# load audio signal with librosa\n",
        "signal, sample_rate = librosa.load(AUDIO_FILENAME, sr=None)\n",
        "\n",
        "# display audio player for the signal\n",
        "display(Audio(data=signal, rate=sample_rate))\n",
        "\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': 300,\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",
        "# calculate amplitude spectrum\n",
        "time_stride=0.01\n",
        "hop_length = int(sample_rate*time_stride)\n",
        "n_fft = 512\n",
        "# linear scale spectrogram\n",
        "s = librosa.stft(y=signal,\n",
        "                 n_fft=n_fft,\n",
        "                 hop_length=hop_length)\n",
        "s_db = librosa.power_to_db(np.abs(s)**2, ref=np.max, top_db=100)\n",
        "\n",
        "# plot the signal in frequency domain\n",
        "fig_spectrum = go.Figure(\n",
        "    go.Heatmap(z=s_db,\n",
        "               colorscale=[\n",
        "                   [0, 'rgb(30,62,62)'],\n",
        "                   [0.5, 'rgb(30,128,128)'],\n",
        "                   [1, 'rgb(30,255,30)'],\n",
        "               ],\n",
        "               colorbar=dict(\n",
        "                   ticksuffix=' dB'\n",
        "               ),\n",
        "               dx=time_stride, dy=sample_rate/n_fft/1000,\n",
        "               name='Spectrogram',\n",
        "               hovertemplate='Time: %{x:.2f} s<br>Frequency: %{y:.2f} kHz<br>Magnitude: %{z:.2f} dB<extra></extra>'),\n",
        "    layout={\n",
        "        'height': 300,\n",
        "        'xaxis': {'title': 'Time, s'},\n",
        "        'yaxis': {'title': 'Frequency, kHz'},\n",
        "        'title': 'Spectrogram',\n",
        "        'margin': dict(l=0, r=0, t=40, b=0, pad=0),\n",
        "    }\n",
        ")\n",
        "fig_spectrum.show()"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "jQSj-IhEhrtI"
      },
      "source": [
        "## Offline inference\n",
        "If we have an entire audio clip available, then we can do offline inference with a pre-trained model to transcribe it.\n",
        "\n",
        "The easiest way to do it is to call ASR model's ``transcribe(...)`` method  that allows transcribing multiple files in a batch."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "s0ERrXIzKpwu"
      },
      "source": [
        "# Convert our audio sample to text\n",
        "files = [AUDIO_FILENAME]\n",
        "transcript = asr_model.transcribe(paths2audio_files=files)[0]\n",
        "print(f'Transcript: \"{transcript}\"')"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "_UOoj-WfQoL_"
      },
      "source": [
        "## Extract timestamps and split words\n",
        "``transcribe()`` generates a text applying a CTC greedy decoder to raw probabilities distribution over alphabet's characters from ASR model. We can get those raw probabilities with ``logprobs=True`` argument."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "-0Sk0C9-LmAR"
      },
      "source": [
        "# softmax implementation in NumPy\n",
        "def softmax(logits):\n",
        "    e = np.exp(logits - np.max(logits))\n",
        "    return e / e.sum(axis=-1).reshape([logits.shape[0], 1])\n",
        "\n",
        "# let's do inference once again but without decoder\n",
        "logits = asr_model.transcribe(files, logprobs=True)[0]\n",
        "probs = softmax(logits)\n",
        "\n",
        "# 20ms is duration of a timestep at output of the model\n",
        "time_stride = 0.02\n",
        "\n",
        "# get model's alphabet\n",
        "labels = list(asr_model.decoder.vocabulary) + ['blank']\n",
        "labels[0] = 'space'\n",
        "\n",
        "# plot probability distribution over characters for each timestep\n",
        "fig_probs = go.Figure(\n",
        "    go.Heatmap(z=probs.transpose(),\n",
        "               colorscale=[\n",
        "                   [0, 'rgb(30,62,62)'],\n",
        "                   [1, 'rgb(30,255,30)'],\n",
        "               ],\n",
        "               y=labels,\n",
        "               dx=time_stride,\n",
        "               name='Probs',\n",
        "               hovertemplate='Time: %{x:.2f} s<br>Character: %{y}<br>Probability: %{z:.2f}<extra></extra>'),\n",
        "    layout={\n",
        "        'height': 300,\n",
        "        'xaxis': {'title': 'Time, s'},\n",
        "        'yaxis': {'title': 'Characters'},\n",
        "        'title': 'Character Probabilities',\n",
        "        'margin': dict(l=0, r=0, t=40, b=0, pad=0),\n",
        "    }\n",
        ")\n",
        "fig_probs.show()"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "YiNMZBodIaSP"
      },
      "source": [
        "It is easy to identify timesteps for space character."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "32aaW3HEJ89l"
      },
      "source": [
        "# get timestamps for space symbols\n",
        "spaces = []\n",
        "\n",
        "state = ''\n",
        "idx_state = 0\n",
        "\n",
        "if np.argmax(probs[0]) == 0:\n",
        "    state = 'space'\n",
        "\n",
        "for idx in range(1, probs.shape[0]):\n",
        "    current_char_idx = np.argmax(probs[idx])\n",
        "    if state == 'space' and current_char_idx != 0 and current_char_idx != 28:\n",
        "        spaces.append([idx_state, idx-1])\n",
        "        state = ''\n",
        "    if state == '':\n",
        "        if current_char_idx == 0:\n",
        "            state = 'space'\n",
        "            idx_state = idx\n",
        "\n",
        "if state == 'space':\n",
        "    spaces.append([idx_state, len(pred)-1])"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "rqg4oxpsL8cW"
      },
      "source": [
        "Then we can split original audio signal into separate words. It is worth to mention that all timestamps have a delay (or an offset) depending on the model. We need to take it into account for alignment."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "a-LSg9dSL_O1"
      },
      "source": [
        "# calibration offset for timestamps: 180 ms\n",
        "offset = -0.18\n",
        "\n",
        "# split the transcript into words\n",
        "words = transcript.split()\n",
        "\n",
        "# cut words\n",
        "pos_prev = 0\n",
        "for j, spot in enumerate(spaces):\n",
        "    display(words[j])\n",
        "    pos_end = offset + (spot[0]+spot[1])/2*time_stride\n",
        "    display(Audio(signal[int(pos_prev*sample_rate):int(pos_end*sample_rate)],\n",
        "                 rate=sample_rate))\n",
        "    pos_prev = pos_end\n",
        "\n",
        "display(words[j+1])\n",
        "display(Audio(signal[int(pos_prev*sample_rate):],\n",
        "        rate=sample_rate))"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Q8Jvwe4Ahncx"
      },
      "source": [
        "## Offline inference with beam search decoder and N-gram language model re-scoring\n",
        "\n",
        "It is possible to use an external [KenLM](https://kheafield.com/code/kenlm/)-based N-gram language model to rescore multiple transcription candidates. \n",
        "\n",
        "Let's download and preprocess LibriSpeech 3-gram language model."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "EIh8wTVs5uH7"
      },
      "source": [
        "import gzip\n",
        "import os, shutil, wget\n",
        "\n",
        "lm_gzip_path = '3-gram.pruned.1e-7.arpa.gz'\n",
        "if not os.path.exists(lm_gzip_path):\n",
        "    print('Downloading pruned 3-gram model.')\n",
        "    lm_url = 'http://www.openslr.org/resources/11/3-gram.pruned.1e-7.arpa.gz'\n",
        "    lm_gzip_path = wget.download(lm_url)\n",
        "    print('Downloaded the 3-gram language model.')\n",
        "else:\n",
        "    print('Pruned .arpa.gz already exists.')\n",
        "\n",
        "uppercase_lm_path = '3-gram.pruned.1e-7.arpa'\n",
        "if not os.path.exists(uppercase_lm_path):\n",
        "    with gzip.open(lm_gzip_path, 'rb') as f_zipped:\n",
        "        with open(uppercase_lm_path, 'wb') as f_unzipped:\n",
        "            shutil.copyfileobj(f_zipped, f_unzipped)\n",
        "    print('Unzipped the 3-gram language model.')\n",
        "else:\n",
        "    print('Unzipped .arpa already exists.')\n",
        "\n",
        "lm_path = 'lowercase_3-gram.pruned.1e-7.arpa'\n",
        "if not os.path.exists(lm_path):\n",
        "    with open(uppercase_lm_path, 'r') as f_upper:\n",
        "        with open(lm_path, 'w') as f_lower:\n",
        "            for line in f_upper:\n",
        "                f_lower.write(line.lower())\n",
        "print('Converted language model file to lowercase.')"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "fLDbUkzzUAqW"
      },
      "source": [
        "Let's instantiate ``BeamSearchDecoderWithLM`` module."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "_qgKa9L954bJ"
      },
      "source": [
        "beam_search_lm = nemo_asr.modules.BeamSearchDecoderWithLM(\n",
        "    vocab=list(asr_model.decoder.vocabulary),\n",
        "    beam_width=16,\n",
        "    alpha=2, beta=1.5,\n",
        "    lm_path=lm_path,\n",
        "    num_cpus=max(os.cpu_count(), 1),\n",
        "    input_tensor=False)"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "NSH8EvL7USac"
      },
      "source": [
        "Now we can check all transcription candidates along with their scores."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "nV1CAy0Dit-g"
      },
      "source": [
        "beam_search_lm.forward(log_probs = np.expand_dims(probs, axis=0), log_probs_length=None)"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "# Greedy Decoding Time Stamps\n",
        "\n",
        "While the above approach works well for character based CTC models, it requires careful tuning of offset parameter as well as computation of the word time stamp offsets.\n",
        "\n",
        "We therefore provide a simple way to obtain greedy decoding word time stamps directly using the familiar \"model.transcribe()\" method, which works quite well for character and subword models.\n",
        "\n",
        "**Note**: We find that larger models that have converged to strong scores on the dataset usually have better word alignments. If evaluated on a completely out of domain audio sample, it might produce very poor time stamps."
      ],
      "metadata": {
        "id": "LPtMzLE4T7T-"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "from omegaconf import OmegaConf, open_dict"
      ],
      "metadata": {
        "id": "z_0pO-TaUIHU"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "For the purposes of this demonstration, we will use Conformer CTC Large, a 120 M parameter model trained on thousands of hours of English speech."
      ],
      "metadata": {
        "id": "i0Epb8D-rW3-"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "asr_model_subword = nemo_asr.models.ASRModel.from_pretrained(\"stt_en_conformer_ctc_large\")"
      ],
      "metadata": {
        "id": "Ky7OpuikbBTb"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "## CTC Decoding Strategy\n",
        "\n",
        "NeMo CTC models have an internal decoding strategy that can be updated after training. In our case, we will enable the greedy decoding step to compute word time stamps, as well as preserve the log probability predictions."
      ],
      "metadata": {
        "id": "vwN6wddTrhno"
      }
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "ubpcxp6z3ZF-"
      },
      "source": [
        "decoding_cfg = asr_model_subword.cfg.decoding\n",
        "print(OmegaConf.to_yaml(decoding_cfg))"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "decoding_cfg.preserve_alignments = True\n",
        "decoding_cfg.compute_timestamps = True\n",
        "asr_model_subword.change_decoding_strategy(decoding_cfg)"
      ],
      "metadata": {
        "id": "pKUsMlUbUAxv"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "Next, we simply transcribe the audio file, and pass the flag `return_hypotheses=True`. This will return a list of `Hypothesis` objects instead of the predicted text."
      ],
      "metadata": {
        "id": "EdX0Drncr8Yl"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "hypothesis = asr_model_subword.transcribe([AUDIO_FILENAME], return_hypotheses=True)[0]"
      ],
      "metadata": {
        "id": "SUkfIyYzUbaB"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "print(\"Greedy prediction :\", hypothesis.text)"
      ],
      "metadata": {
        "id": "duaxOSPXUmQ0"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "## Hypothesis - Time Stamps\n",
        "\n",
        "Since we previously set the flag for `decoding_cfg.compute_timestamps`, the hypothesis now contains a dictionary in it, accessed via `hypothesis.timestep`. This dictionary contains multiple useful lists, detailing the time step at which some token was predicted, the character / subword / word time stamps."
      ],
      "metadata": {
        "id": "_5hfsiDGsM19"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "timestamp_dict = hypothesis.timestep\n",
        "print(\"Hypothesis contains following timestep information :\", list(timestamp_dict.keys()))"
      ],
      "metadata": {
        "id": "vh7K_9D1UrQp"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "# 40ms is duration of a timestep at output of the Conformer\n",
        "time_stride = 4 * asr_model_subword.cfg.preprocessor.window_stride\n",
        "\n",
        "##################################################################\n",
        "\n",
        "word_timestamps = timestamp_dict['word']\n",
        "\n",
        "for stamp in word_timestamps:\n",
        "    start = stamp['start_offset'] * time_stride\n",
        "    end = stamp['end_offset'] * time_stride\n",
        "    word = stamp['char'] if 'char' in stamp else stamp['word']\n",
        "\n",
        "    print(f\"Time : {start:0.2f} - {end:0.2f} - {word}\")\n",
        "    display(Audio(signal[int(start * sample_rate) : int(end * sample_rate)], rate=sample_rate))"
      ],
      "metadata": {
        "id": "fogttpCTVTEZ"
      },
      "execution_count": null,
      "outputs": []
    }
  ]
}