File size: 25,992 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
{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "name": "Publish_NeMo_Model_On_Hugging_Face_Hub.ipynb",
      "provenance": [],
      "collapsed_sections": []
    },
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    },
    "language_info": {
      "name": "python"
    }
  },
  "cells": [
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "qjQ5KQIkaK2J"
      },
      "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",
        "!apt-get install sox libsndfile1 ffmpeg\n",
        "!pip install wget\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[all]"
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "### Install Hugging Face Hub\n",
        "!python -m pip install huggingface_hub\n",
        "!python -m pip install evaluate"
      ],
      "metadata": {
        "id": "J6d04-VRjC-O"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "# NeMo models on Hugging Face Hub\n",
        "\n",
        "This guide will briefly show how to upload NeMo models to Hugging Face programmatically.\n",
        "\n",
        "This enables community members to share their NeMo models (any model!) with all users of NeMo!\n",
        "\n",
        "**Note**: While in this tutorial we showcase an ASR model, there is no particular restriction to any domain - all NeMo models (.nemo files) of every domain can be uploaded and shared in the same way."
      ],
      "metadata": {
        "id": "aS-Y5O_oGBTc"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "# Login to Hugging Face\n",
        "\n",
        "Use the notebook login, and access your user access token (or create one to upload models to Hugging Face).\n",
        "\n",
        "For more information, visit the User Access Token section - https://huggingface.co/docs/hub/security-tokens"
      ],
      "metadata": {
        "id": "Us3UlvwCiEZi"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "from huggingface_hub import notebook_login\n",
        "\n",
        "notebook_login()"
      ],
      "metadata": {
        "id": "4RTYbCLziEnb"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "!git config --global credential.helper store"
      ],
      "metadata": {
        "id": "dgZbTPcFiaml"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "# Prepare a model to upload to HF\n",
        "\n",
        "In this example, we will download a NeMo ASR model from NGC and then upload it to Hugging Face for simplicity and to showcase the method.\n",
        "\n",
        "**You can swap out this ASR model for any model that you restore via `restore_from()` and follow the same steps to upload your own models !**"
      ],
      "metadata": {
        "id": "s-FiNn1eiFAl"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "import torch\n",
        "import torch.nn as nn\n",
        "\n",
        "from omegaconf import DictConfig, OmegaConf, open_dict"
      ],
      "metadata": {
        "id": "5KnVl-M0ax14"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "import nemo.collections.asr as nemo_asr  # use any domain's models !\n",
        "import nemo.collections.nlp as nemo_nlp  # use any domain's models !\n",
        "import nemo.collections.tts as nemo_tts  # use any domain's models !"
      ],
      "metadata": {
        "id": "ZEDpkIinbwmm"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "# Model Name\n",
        "\n",
        "NeMo adheres to strict requirements when naming a model for upload to NGC / Hugging Face Hub. \n",
        "\n",
        "It is **mandatory** to share the model name across the model card, the NeMo file itself. Otherwise NeMo model from Hugging Face will fail to restore correctly."
      ],
      "metadata": {
        "id": "mLuQo1vnHVcP"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "## Naming Convention\n",
        "\n",
        "NeMo model names can vary based on domain and purpose. While we attempt to conform to standard guidelines when naming our models, we do not expect the same level of strictness for community contributions.\n",
        "\n",
        "Here are some common guidelines we encourage (but do not enforce) users to follow : \n",
        "\n",
        "- `Task name`: Usually a short 2-3 character representation of the task that the model performs.\n",
        "  - `stt` = Speech To Text (ASR)\n",
        "  - `tts` = Text to Speech (TTS)\n",
        "  - `ssl` = (Speech) Self Supervised Learning (SSL)\n",
        "  - `nlp` = Natural Language Processing (NLP)\n",
        "  - `nmt` = Neural Machine Translation (NMT) and many more.\n",
        "\n",
        "- `Language ID`: Usually a 2/3 digit universal language id. For multilingual models, each domain has its own rules, but some common ones are `{lang_1}{lang_2}{...}` or call them `multilingual.`\n",
        "\n",
        "- `Model Identifier`: Since models vary so drastically across domains, there is a lot of flexibility here. We try to adhere to naming conventions in literature as much as possible. For example, you can attach `model architecture` (Conformer/Citrinet), `training loss` (CTC/Transducer), and `model size` (small, large, discrete integer sizes, etc.).\n",
        "\n",
        "- `Optional: Additional Modifiers`: These are additional identifiers such as gender of speaker (TTS), dataset name (ls for Librispeech), etc. It can be set on a case-by-case basis.\n",
        "\n",
        "All these name segments are jointed by `_`.\n",
        "\n",
        "-----\n",
        "\n",
        "As an example of the following model we will try today : \n",
        "\n",
        "`{task name}_{language id}_{model identifier}_[OPTIONAL modifiers]` = `stt_en_conformer_ctc_small`"
      ],
      "metadata": {
        "id": "MRO2f9fhHywJ"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "**Set the MODEL_NAME carefully** !"
      ],
      "metadata": {
        "id": "BjLstKWnPzWV"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "MODEL_NAME = \"stt_en_conformer_ctc_small\""
      ],
      "metadata": {
        "id": "UzHjXDbckU0M"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "-----\n",
        "**Restore a NeMo Model**\n",
        "\n",
        "Here, we restore a model from NGC directly, but you can restore a model from your training runs using `restore_from()` or use a local .nemo file."
      ],
      "metadata": {
        "id": "qibj1RwvKjSQ"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "model = nemo_asr.models.ASRModel.from_pretrained(MODEL_NAME)"
      ],
      "metadata": {
        "id": "MsC3pE65d_z2"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "# Create a Hugging Face Model\n",
        "\n",
        "Now that we have a NeMo model and have logged into Hugging Face with our user API key, we can begin by creating a new repository and uploading our model."
      ],
      "metadata": {
        "id": "y1AkXPFVKfC2"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "-----\n",
        "\n",
        "After the model has been restored, create an HfApi object to interact with the model repository."
      ],
      "metadata": {
        "id": "iv17qFG7KzlL"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "from huggingface_hub import HfApi\n",
        "api = HfApi()\n",
        "username = api.whoami()['name']"
      ],
      "metadata": {
        "id": "aJUXCOTjKy-2"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "try:\n",
        "  api.create_repo(repo_id=MODEL_NAME)\n",
        "  print(\"Successfully created repository !\")\n",
        "except Exception as e:\n",
        "  print(\"Repository is possibly already created. Refer to error here - \\n\\n\", e)"
      ],
      "metadata": {
        "id": "DKRlMeaEkeAH"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "from huggingface_hub import Repository"
      ],
      "metadata": {
        "id": "N2-deSyTlCdS"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "Note two essential names - \n",
        "\n",
        "- `hf_model_name`: A string name that is the composite of your `username` and `MODEL_NAME` as set above. This name is used for multiple purposes, so keep track of it.\n",
        "\n",
        "- `model_filename`: The actual filename of the NeMo model that will be uploaded to Hugging Face. Note that this filename is explicitly set to `{MODEL_NAME}.nemo`. If this model filename is altered, then the model cannot correctly be restored by NeMo when downloaded from Hugging Face Hub, so please be careful."
      ],
      "metadata": {
        "id": "aTa4RqDYLGMI"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "local_dir = f'model-{MODEL_NAME}/'\n",
        "hf_model_name = f'{username}/{MODEL_NAME}'\n",
        "\n",
        "commit_message = \"Upload model\"\n",
        "model_filename = f'{MODEL_NAME}.nemo'\n",
        "\n",
        "with Repository(local_dir=local_dir, clone_from=hf_model_name, repo_type='model').commit(commit_message):\n",
        "  model.save_to(model_filename)"
      ],
      "metadata": {
        "id": "xhTTMNpBskMS"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "print(\"Finished uploading model to :\", hf_model_name)"
      ],
      "metadata": {
        "id": "BhvNp8MYvxLi"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "## Test if the model works \n",
        "\n",
        "Now that we uploaded the model, let's try to use it in NeMo !\n",
        "\n",
        "The only change required between normally calling `from_pretrained(model_name)` is to call **`from_pretrained({username}/{filename})`**"
      ],
      "metadata": {
        "id": "Qrs-MlW9vVbH"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "hf_model_name = f'{username}/{MODEL_NAME}'\n",
        "hf_model = nemo_asr.models.ASRModel.from_pretrained(hf_model_name)"
      ],
      "metadata": {
        "id": "NyuyyRv5snkr"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "print(\"Successfully used HF model -\", hf_model_name)"
      ],
      "metadata": {
        "id": "Yhi922WVv4G_"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "# Model Card\n",
        "\n",
        "Now that we have uploaded the model, we are nearly 50% done!\n",
        "\n",
        "The next step is to update the model card to have some helpful information regarding the uploaded model and its scores compared to other models.\n",
        "\n",
        "You can do this in two ways, manually (by clicking the link below) or programmatically fill in part of the model card by following the instructions below."
      ],
      "metadata": {
        "id": "9gG1ElJywEJT"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "hf_url = f'https://huggingface.co/{username}/{MODEL_NAME}'\n",
        "print(f\"Visit {hf_url} to manually edit your model card\")"
      ],
      "metadata": {
        "id": "aZJRKoxhwBLr"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "-----\n",
        "\n",
        "Here, we are going to setup some variables for our model card.\n",
        "\n",
        "First up are the tags:"
      ],
      "metadata": {
        "id": "ZlA4hNq6w4rH"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "TAGS = [\n",
        "    \"automatic-speech-recognition\",  # Task id, refer to https://github.com/huggingface/datasets/blob/master/src/datasets/utils/resources/tasks.json for allowed values.\n",
        "    \"speech\",  # add as many other tags as required\n",
        "    \"audio\",\n",
        "    \"CTC\",\n",
        "    \"Conformer\",\n",
        "    \"Transformer\",\n",
        "    \"NeMo\",  # required for library identification\n",
        "    \"pytorch\",  # required, for toolkit identification\n",
        "    # \"hf-asr-leaderboard\",  # Should only be used if model is evaluated on benchmark scores for ASR.\n",
        "]"
      ],
      "metadata": {
        "id": "QxKtPynWyUWX"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "-----\n",
        "\n",
        "Next, we list down all the datasets that were used to train the model.\n",
        "\n",
        "By convention, try to search if the dataset already exists on Hugging Face Datasets - it is usually listed at the top and in lower case.\n",
        "\n",
        "If you train on datasets that don't yet exist in Hugging Face Datasets, you can still add them but try to differentiate them by using capitalized names."
      ],
      "metadata": {
        "id": "Fh7rYWEMM0Vz"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "# Replace all spaces with `-`\n",
        "DATASETS = [\n",
        "    \"librispeech_asr\",\n",
        "    \"mozilla-foundation/common_voice_7_0\",\n",
        "    \"vctk\",\n",
        "    \"fisher_corpus\",\n",
        "    \"Switchboard-1\",\n",
        "    \"WSJ-0\",\n",
        "    \"WSJ-1\",\n",
        "    \"National-Singapore-Corpus-Part-1\",\n",
        "    \"National-Singapore-Corpus-Part-6\",\n",
        "    \"VoxPopuli-(EN)\",\n",
        "    \"Europarl-ASR-(EN)\",\n",
        "    \"Multilingual-LibriSpeech-(2000-hours)\",\n",
        "]"
      ],
      "metadata": {
        "id": "qy-5aDAgzuGD"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "-----\n",
        "\n",
        "Now we create an automated template based on a config for the top portion of the readme file."
      ],
      "metadata": {
        "id": "_0w1X_z4NN5-"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "from dataclasses import dataclass, field\n",
        "from typing import List, Optional, Dict, Any\n",
        "\n",
        "@dataclass\n",
        "class NeMoHuggingFaceModelConfig:\n",
        "  language: List[str]\n",
        "  license: str\n",
        "\n",
        "  library_name: str = \"nemo\"\n",
        "  datasets: List[str] = field(default_factory=lambda: DATASETS)\n",
        "  thumbnail: Optional[str] = None\n",
        "  tags: List[str] = field(default_factory=lambda: TAGS)\n",
        "  model_index: Any = field(default_factory=lambda: [dict(name=MODEL_NAME, results=[])])"
      ],
      "metadata": {
        "id": "O88WFyPJwjJD"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "config = NeMoHuggingFaceModelConfig(language=['en'], license=\"cc-by-4.0\")  # choose appropriate license here\n",
        "config = OmegaConf.structured(config)\n",
        "\n",
        "with open_dict(config):\n",
        "  # Update `model_index` to `model-index`\n",
        "  model_index = config.pop('model_index')\n",
        "  config['model-index'] = model_index\n",
        "\n",
        "  # Replace all spaces with `-` in datasets\n",
        "  normalized_datasets = [ds_name.replace(\" \", \"-\") for ds_name in config['datasets']]\n",
        "  config['datasets'] = OmegaConf.create(normalized_datasets)\n",
        "\n",
        "print(OmegaConf.to_yaml(config))"
      ],
      "metadata": {
        "id": "BpInrBdNxxZ3"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "## Markdown Template\n",
        "\n",
        "Now that we have an auto-generated header for our readme, next, we write down some template markdown for the actual contents of the markdown.\n",
        "\n",
        "You can edit the code here directly if you want, or if you prefer the GUI to see the actual changes in real-time, you can finish uploading this model card and then edit the readme file on the Hugging Face webpage itself."
      ],
      "metadata": {
        "id": "0TECX8QrC6FY"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "hf_model_name = f'{username}/{MODEL_NAME}'\n",
        "\n",
        "TEMPLATE = f\"\"\"\n",
        "## Model Overview\n",
        "\n",
        "<DESCRIBE IN ONE LINE THE MODEL AND ITS USE>\n",
        "\n",
        "## NVIDIA NeMo: Training\n",
        "\n",
        "To train, fine-tune or play with the model you will need to install [NVIDIA NeMo](https://github.com/NVIDIA/NeMo). We recommend you install it after you've installed latest Pytorch version.\n",
        "```\n",
        "pip install nemo_toolkit['all']\n",
        "``` \n",
        "\n",
        "## How to Use this Model\n",
        "\n",
        "The model is available for use in the NeMo toolkit [3], and can be used as a pre-trained checkpoint for inference or for fine-tuning on another dataset.\n",
        "\n",
        "### Automatically instantiate the model\n",
        "\n",
        "```python\n",
        "import nemo.collections.asr as nemo_asr\n",
        "asr_model = nemo_asr.models.ASRModel.from_pretrained(\"{hf_model_name}\")\n",
        "```\n",
        "\n",
        "### Transcribing using Python\n",
        "First, let's get a sample\n",
        "```\n",
        "wget https://dldata-public.s3.us-east-2.amazonaws.com/2086-149220-0033.wav\n",
        "```\n",
        "Then simply do:\n",
        "```\n",
        "asr_model.transcribe(['2086-149220-0033.wav'])\n",
        "```\n",
        "\n",
        "### Transcribing many audio files\n",
        "\n",
        "```shell\n",
        "python [NEMO_GIT_FOLDER]/examples/asr/transcribe_speech.py \\\n",
        " pretrained_name=\"{hf_model_name}\" \\\n",
        " audio_dir=\"<DIRECTORY CONTAINING AUDIO FILES>\"\n",
        "```\n",
        "\n",
        "### Input\n",
        "\n",
        "This model accepts 16000 KHz Mono-channel Audio (wav files) as input.\n",
        "\n",
        "### Output\n",
        "\n",
        "This model provides transcribed speech as a string for a given audio sample.\n",
        "\n",
        "## Model Architecture\n",
        "\n",
        "<ADD SOME INFORMATION ABOUT THE ARCHITECTURE>\n",
        "\n",
        "## Training\n",
        "\n",
        "<ADD INFORMATION ABOUT HOW THE MODEL WAS TRAINED - HOW MANY EPOCHS, AMOUNT OF COMPUTE ETC>\n",
        "\n",
        "### Datasets\n",
        "\n",
        "<LIST THE NAME AND SPLITS OF DATASETS USED TO TRAIN THIS MODEL (ALONG WITH LANGUAGE AND ANY ADDITIONAL INFORMATION)>\n",
        "\n",
        "## Performance\n",
        "\n",
        "<LIST THE SCORES OF THE MODEL - \n",
        "      OR\n",
        "USE THE Hugging Face Evaluate LiBRARY TO UPLOAD METRICS>\n",
        "\n",
        "## Limitations\n",
        "\n",
        "<DECLARE ANY POTENTIAL LIMITATIONS OF THE MODEL>\n",
        "\n",
        "Eg: \n",
        "Since this model was trained on publically available speech datasets, the performance of this model might degrade for speech which includes technical terms, or vernacular that the model has not been trained on. The model might also perform worse for accented speech.\n",
        "\n",
        "\n",
        "## References\n",
        "\n",
        "<ADD ANY REFERENCES HERE AS NEEDED>\n",
        "\n",
        "[1] [NVIDIA NeMo Toolkit](https://github.com/NVIDIA/NeMo)\n",
        "\n",
        "\"\"\""
      ],
      "metadata": {
        "id": "SSmm7_OiC9Ex"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "-----\n",
        "\n",
        "Below, we will upload this model card in a temporary file called **`\"readme_template.md\"`**. This is done to prevent overwriting of the \"final\" model card that the user may have manually edited.\n",
        "\n",
        "Once this step is finished, **please copy the contents of this file, create a README.md file and paste the contents into it**."
      ],
      "metadata": {
        "id": "KPa53S_5NzNp"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "local_dir = f'model-{MODEL_NAME}/'\n",
        "hf_model_name = f'{username}/{MODEL_NAME}'\n",
        "\n",
        "commit_message = \"Upload config\"\n",
        "filename = 'readme_template.md'\n",
        "\n",
        "with Repository(local_dir=local_dir, clone_from=hf_model_name, repo_type='model').commit(commit_message):\n",
        "  with open(filename, 'w') as f:\n",
        "    f.write(\"---\\n\")\n",
        "    f.write(OmegaConf.to_yaml(config))\n",
        "    f.write(\"\\n---\\n\\n\")\n",
        "    f.write(TEMPLATE)\n",
        "  "
      ],
      "metadata": {
        "id": "0vk5KK4gzpSU"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "-----\n",
        "\n",
        "Please visit the URL below to copy the contents of the `readme_template.md` file into your `README.md` file."
      ],
      "metadata": {
        "id": "dfXoihCQmWDa"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "hf_url = f'https://huggingface.co/{username}/{MODEL_NAME}'\n",
        "print(f\"Visit {hf_url} to edit your model card from the generated template file `{filename}`\")"
      ],
      "metadata": {
        "id": "but-5LuLTHFd"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "## Evaluation Results\n",
        "\n",
        "Now that we have both the model checkpoint and the readme uploaded to the Hub, we can optionally add some evaluation results to the card as well!\n",
        "\n",
        "While this next section is optional, it is highly encouraged to do!"
      ],
      "metadata": {
        "id": "5vPEnlE62dGU"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "import evaluate\n",
        "# evaluate.list_evaluation_modules(module_type='metric', with_details=True)"
      ],
      "metadata": {
        "id": "rkXMtapA0YzH"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "# Uncomment in order to see what values you can supply to the `evaluate` library to push to the Hub.\n",
        "# help(evaluate.push_to_hub)"
      ],
      "metadata": {
        "id": "50rzG9Qb3yLR"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "hf_model_name = f'{username}/{MODEL_NAME}'\n",
        "metric_value = 8.1  # value obtained from https://catalog.ngc.nvidia.com/orgs/nvidia/teams/nemo/models/stt_en_conformer_ctc_small \n",
        "\n",
        "evaluate.push_to_hub(\n",
        "    model_id=hf_model_name,\n",
        "    task_type=\"automatic-speech-recognition\",\n",
        "    dataset_type=\"librispeech_asr\",\n",
        "    dataset_name=\"Librispeech (clean)\",\n",
        "    metric_type=\"wer\",\n",
        "    metric_name=\"WER\",\n",
        "    dataset_split=\"test\",  # corresponds to test-clean set\n",
        "    dataset_config=\"other\",  # corresponds to test-clean set\n",
        "    dataset_args=dict(language=\"en\"),  # metadata for dataset\n",
        "    # the actual score obtained by the model\n",
        "    metric_value=metric_value,\n",
        ")"
      ],
      "metadata": {
        "id": "5A4g3SGf4d0V"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "-----\n",
        "\n",
        "Done! Now we have a model checkpoint, a model card as well as evaluation results all set up for the NeMo model on Hugging Face!\n",
        "\n",
        "To add more metrics, you can copy-paste the above cell and repeat the procedure for as many metrics as needed!"
      ],
      "metadata": {
        "id": "f3YYa7liO_m3"
      }
    }
  ]
}