malmarz commited on
Commit
d09a13e
1 Parent(s): 0ff3ea9

Training in progress, step 1000

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitignore +1 -0
  2. .ipynb_checkpoints/fine-tune-whisper-non-streaming-checkpoint.ipynb +1225 -0
  3. .ipynb_checkpoints/mgb2_speech-checkpoint.py +169 -0
  4. .ipynb_checkpoints/run_mgb2-checkpoint.sh +38 -0
  5. .ipynb_checkpoints/run_speech_recognition_seq2seq_mixed_mgb2-checkpoint.py +748 -0
  6. .ipynb_checkpoints/run_speech_recognition_seq2seq_mixed_mgb2-cv1-checkpoint.py +802 -0
  7. README.md +104 -0
  8. added_tokens.json +109 -0
  9. all_results.json +12 -0
  10. bigram_count.txt +3875 -0
  11. check_bnb_install.py +20 -0
  12. check_bnb_install.py.1 +20 -0
  13. config.json +41 -0
  14. ds_config.json +48 -0
  15. eval_results.json +8 -0
  16. evaluate_models.py +73 -0
  17. fine-tune-whisper-non-streaming.ipynb +1322 -0
  18. fine-tune-whisper-non-streaming.ipynb.1 +1207 -0
  19. merges.txt +0 -0
  20. mgb2_speech.py +169 -0
  21. normalizer.json +1742 -0
  22. preprocess_dataset.py +89 -0
  23. preprocessor_config.json +0 -0
  24. pytorch_model.bin +3 -0
  25. requirements.txt +14 -0
  26. requirements_colab.txt +11 -0
  27. run.sh +38 -0
  28. run_eval_cv_11.sh +10 -0
  29. run_eval_fleurs.sh +10 -0
  30. run_eval_whisper_streaming.py +166 -0
  31. run_mgb2.sh +38 -0
  32. run_mgb2_deepspeed.sh +38 -0
  33. run_speech_recognition_seq2seq.py +607 -0
  34. run_speech_recognition_seq2seq_mixed_mgb2-cv1.py +802 -0
  35. run_speech_recognition_seq2seq_mixed_mgb2.py +748 -0
  36. run_speech_recognition_seq2seq_streaming.py +608 -0
  37. runs/Dec16_20-24-38_129-146-160-68/1671222292.263272/events.out.tfevents.1671222292.129-146-160-68.394631.1 +3 -0
  38. runs/Dec16_20-24-38_129-146-160-68/events.out.tfevents.1671222292.129-146-160-68.394631.0 +3 -0
  39. runs/Dec16_20-26-39_129-146-160-68/1671222412.8615997/events.out.tfevents.1671222412.129-146-160-68.394809.1 +3 -0
  40. runs/Dec16_20-26-39_129-146-160-68/events.out.tfevents.1671222412.129-146-160-68.394809.0 +3 -0
  41. runs/Dec16_21-21-11_129-146-160-68/1671226550.1156573/events.out.tfevents.1671226550.129-146-160-68.395790.1 +3 -0
  42. runs/Dec16_21-21-11_129-146-160-68/events.out.tfevents.1671226550.129-146-160-68.395790.0 +3 -0
  43. runs/Dec16_21-57-02_129-146-160-68/1671227839.103308/events.out.tfevents.1671227839.129-146-160-68.396724.1 +3 -0
  44. runs/Dec16_21-57-02_129-146-160-68/events.out.tfevents.1671227839.129-146-160-68.396724.0 +3 -0
  45. setup_env.sh +10 -0
  46. setup_jupyter.sh +4 -0
  47. setup_libs.sh +13 -0
  48. setup_libs_colab.sh +12 -0
  49. special_tokens_map.json +133 -0
  50. split_mgb2_test.py +20 -0
.gitignore ADDED
@@ -0,0 +1 @@
 
 
1
+ checkpoint-*/
.ipynb_checkpoints/fine-tune-whisper-non-streaming-checkpoint.ipynb ADDED
@@ -0,0 +1,1225 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "id": "75b58048-7d14-4fc6-8085-1fc08c81b4a6",
6
+ "metadata": {
7
+ "id": "75b58048-7d14-4fc6-8085-1fc08c81b4a6"
8
+ },
9
+ "source": [
10
+ "# Fine-Tune Whisper For Multilingual ASR with 🤗 Transformers"
11
+ ]
12
+ },
13
+ {
14
+ "cell_type": "markdown",
15
+ "id": "fbfa8ad5-4cdc-4512-9058-836cbbf65e1a",
16
+ "metadata": {
17
+ "id": "fbfa8ad5-4cdc-4512-9058-836cbbf65e1a"
18
+ },
19
+ "source": [
20
+ "In this Colab, we present a step-by-step guide on how to fine-tune Whisper \n",
21
+ "for any multilingual ASR dataset using Hugging Face 🤗 Transformers. This is a \n",
22
+ "more \"hands-on\" version of the accompanying [blog post](https://huggingface.co/blog/fine-tune-whisper). \n",
23
+ "For a more in-depth explanation of Whisper, the Common Voice dataset and the theory behind fine-tuning, the reader is advised to refer to the blog post."
24
+ ]
25
+ },
26
+ {
27
+ "cell_type": "markdown",
28
+ "id": "afe0d503-ae4e-4aa7-9af4-dbcba52db41e",
29
+ "metadata": {
30
+ "id": "afe0d503-ae4e-4aa7-9af4-dbcba52db41e"
31
+ },
32
+ "source": [
33
+ "## Introduction"
34
+ ]
35
+ },
36
+ {
37
+ "cell_type": "markdown",
38
+ "id": "9ae91ed4-9c3e-4ade-938e-f4c2dcfbfdc0",
39
+ "metadata": {
40
+ "id": "9ae91ed4-9c3e-4ade-938e-f4c2dcfbfdc0"
41
+ },
42
+ "source": [
43
+ "Whisper is a pre-trained model for automatic speech recognition (ASR) \n",
44
+ "published in [September 2022](https://openai.com/blog/whisper/) by the authors \n",
45
+ "Alec Radford et al. from OpenAI. Unlike many of its predecessors, such as \n",
46
+ "[Wav2Vec 2.0](https://arxiv.org/abs/2006.11477), which are pre-trained \n",
47
+ "on un-labelled audio data, Whisper is pre-trained on a vast quantity of \n",
48
+ "**labelled** audio-transcription data, 680,000 hours to be precise. \n",
49
+ "This is an order of magnitude more data than the un-labelled audio data used \n",
50
+ "to train Wav2Vec 2.0 (60,000 hours). What is more, 117,000 hours of this \n",
51
+ "pre-training data is multilingual ASR data. This results in checkpoints \n",
52
+ "that can be applied to over 96 languages, many of which are considered \n",
53
+ "_low-resource_.\n",
54
+ "\n",
55
+ "When scaled to 680,000 hours of labelled pre-training data, Whisper models \n",
56
+ "demonstrate a strong ability to generalise to many datasets and domains.\n",
57
+ "The pre-trained checkpoints achieve competitive results to state-of-the-art \n",
58
+ "ASR systems, with near 3% word error rate (WER) on the test-clean subset of \n",
59
+ "LibriSpeech ASR and a new state-of-the-art on TED-LIUM with 4.7% WER (_c.f._ \n",
60
+ "Table 8 of the [Whisper paper](https://cdn.openai.com/papers/whisper.pdf)).\n",
61
+ "The extensive multilingual ASR knowledge acquired by Whisper during pre-training \n",
62
+ "can be leveraged for other low-resource languages; through fine-tuning, the \n",
63
+ "pre-trained checkpoints can be adapted for specific datasets and languages \n",
64
+ "to further improve upon these results. We'll show just how Whisper can be fine-tuned \n",
65
+ "for low-resource languages in this Colab."
66
+ ]
67
+ },
68
+ {
69
+ "cell_type": "markdown",
70
+ "id": "e59b91d6-be24-4b5e-bb38-4977ea143a72",
71
+ "metadata": {
72
+ "id": "e59b91d6-be24-4b5e-bb38-4977ea143a72"
73
+ },
74
+ "source": [
75
+ "<figure>\n",
76
+ "<img src=\"https://raw.githubusercontent.com/sanchit-gandhi/notebooks/main/whisper_architecture.svg\" alt=\"Trulli\" style=\"width:100%\">\n",
77
+ "<figcaption align = \"center\"><b>Figure 1:</b> Whisper model. The architecture \n",
78
+ "follows the standard Transformer-based encoder-decoder model. A \n",
79
+ "log-Mel spectrogram is input to the encoder. The last encoder \n",
80
+ "hidden states are input to the decoder via cross-attention mechanisms. The \n",
81
+ "decoder autoregressively predicts text tokens, jointly conditional on the \n",
82
+ "encoder hidden states and previously predicted tokens. Figure source: \n",
83
+ "<a href=\"https://openai.com/blog/whisper/\">OpenAI Whisper Blog</a>.</figcaption>\n",
84
+ "</figure>"
85
+ ]
86
+ },
87
+ {
88
+ "cell_type": "markdown",
89
+ "id": "21b6316e-8a55-4549-a154-66d3da2ab74a",
90
+ "metadata": {
91
+ "id": "21b6316e-8a55-4549-a154-66d3da2ab74a"
92
+ },
93
+ "source": [
94
+ "The Whisper checkpoints come in five configurations of varying model sizes.\n",
95
+ "The smallest four are trained on either English-only or multilingual data.\n",
96
+ "The largest checkpoint is multilingual only. All nine of the pre-trained checkpoints \n",
97
+ "are available on the [Hugging Face Hub](https://huggingface.co/models?search=openai/whisper). The \n",
98
+ "checkpoints are summarised in the following table with links to the models on the Hub:\n",
99
+ "\n",
100
+ "| Size | Layers | Width | Heads | Parameters | English-only | Multilingual |\n",
101
+ "|--------|--------|-------|-------|------------|------------------------------------------------------|---------------------------------------------------|\n",
102
+ "| tiny | 4 | 384 | 6 | 39 M | [✓](https://huggingface.co/openai/whisper-tiny.en) | [✓](https://huggingface.co/openai/whisper-tiny.) |\n",
103
+ "| base | 6 | 512 | 8 | 74 M | [✓](https://huggingface.co/openai/whisper-base.en) | [✓](https://huggingface.co/openai/whisper-base) |\n",
104
+ "| small | 12 | 768 | 12 | 244 M | [✓](https://huggingface.co/openai/whisper-small.en) | [✓](https://huggingface.co/openai/whisper-small) |\n",
105
+ "| medium | 24 | 1024 | 16 | 769 M | [✓](https://huggingface.co/openai/whisper-medium.en) | [✓](https://huggingface.co/openai/whisper-medium) |\n",
106
+ "| large | 32 | 1280 | 20 | 1550 M | x | [✓](https://huggingface.co/openai/whisper-large) |\n",
107
+ "\n",
108
+ "For demonstration purposes, we'll fine-tune the multilingual version of the \n",
109
+ "[`\"small\"`](https://huggingface.co/openai/whisper-small) checkpoint with 244M params (~= 1GB). \n",
110
+ "As for our data, we'll train and evaluate our system on a low-resource language \n",
111
+ "taken from the [Common Voice](https://huggingface.co/datasets/mozilla-foundation/common_voice_11_0)\n",
112
+ "dataset. We'll show that with as little as 8 hours of fine-tuning data, we can achieve \n",
113
+ "strong performance in this language."
114
+ ]
115
+ },
116
+ {
117
+ "cell_type": "markdown",
118
+ "id": "3a680dfc-cbba-4f6c-8a1f-e1a5ff3f123a",
119
+ "metadata": {
120
+ "id": "3a680dfc-cbba-4f6c-8a1f-e1a5ff3f123a"
121
+ },
122
+ "source": [
123
+ "------------------------------------------------------------------------\n",
124
+ "\n",
125
+ "\\\\({}^1\\\\) The name Whisper follows from the acronym “WSPSR”, which stands for “Web-scale Supervised Pre-training for Speech Recognition”."
126
+ ]
127
+ },
128
+ {
129
+ "cell_type": "markdown",
130
+ "id": "b219c9dd-39b6-4a95-b2a1-3f547a1e7bc0",
131
+ "metadata": {
132
+ "id": "b219c9dd-39b6-4a95-b2a1-3f547a1e7bc0"
133
+ },
134
+ "source": [
135
+ "## Load Dataset"
136
+ ]
137
+ },
138
+ {
139
+ "attachments": {},
140
+ "cell_type": "markdown",
141
+ "id": "674429c5-0ab4-4adf-975b-621bb69eca38",
142
+ "metadata": {
143
+ "id": "674429c5-0ab4-4adf-975b-621bb69eca38"
144
+ },
145
+ "source": [
146
+ "Using 🤗 Datasets, downloading and preparing data is extremely simple. \n",
147
+ "We can download and prepare the Common Voice splits in just one line of code. \n",
148
+ "\n",
149
+ "First, ensure you have accepted the terms of use on the Hugging Face Hub: [mozilla-foundation/common_voice_11_0](https://huggingface.co/datasets/mozilla-foundation/common_voice_11_0). Once you have accepted the terms, you will have full access to the dataset and be able to download the data locally.\n",
150
+ "\n",
151
+ "Since Arabic is very low-resource, we'll combine the `train` and `validation` \n",
152
+ "splits to give approximately 8 hours of training data. We'll use the 4 hours \n",
153
+ "of `test` data as our held-out test set:"
154
+ ]
155
+ },
156
+ {
157
+ "cell_type": "code",
158
+ "execution_count": null,
159
+ "id": "5de15d70",
160
+ "metadata": {},
161
+ "outputs": [],
162
+ "source": [
163
+ "model_name = \"openai/whisper-small\""
164
+ ]
165
+ },
166
+ {
167
+ "cell_type": "code",
168
+ "execution_count": null,
169
+ "id": "a2787582-554f-44ce-9f38-4180a5ed6b44",
170
+ "metadata": {
171
+ "id": "a2787582-554f-44ce-9f38-4180a5ed6b44"
172
+ },
173
+ "outputs": [],
174
+ "source": [
175
+ "from datasets import load_dataset, DatasetDict\n",
176
+ "\n",
177
+ "common_voice = DatasetDict()\n",
178
+ "\n",
179
+ "common_voice[\"train\"] = load_dataset(\"mozilla-foundation/common_voice_11_0\", \"ar\", split=\"train+validation\", use_auth_token=True)\n",
180
+ "common_voice[\"test\"] = load_dataset(\"mozilla-foundation/common_voice_11_0\", \"ar\", split=\"test\", use_auth_token=True)\n",
181
+ "\n",
182
+ "print(common_voice)"
183
+ ]
184
+ },
185
+ {
186
+ "cell_type": "markdown",
187
+ "id": "d5c7c3d6-7197-41e7-a088-49b753c1681f",
188
+ "metadata": {
189
+ "id": "d5c7c3d6-7197-41e7-a088-49b753c1681f"
190
+ },
191
+ "source": [
192
+ "Most ASR datasets only provide input audio samples (`audio`) and the \n",
193
+ "corresponding transcribed text (`sentence`). Common Voice contains additional \n",
194
+ "metadata information, such as `accent` and `locale`, which we can disregard for ASR.\n",
195
+ "Keeping the notebook as general as possible, we only consider the input audio and\n",
196
+ "transcribed text for fine-tuning, discarding the additional metadata information:"
197
+ ]
198
+ },
199
+ {
200
+ "cell_type": "code",
201
+ "execution_count": null,
202
+ "id": "20ba635d-518c-47ac-97ee-3cad25f1e0ce",
203
+ "metadata": {
204
+ "id": "20ba635d-518c-47ac-97ee-3cad25f1e0ce"
205
+ },
206
+ "outputs": [],
207
+ "source": [
208
+ "common_voice = common_voice.remove_columns([\"accent\", \"age\", \"client_id\", \"down_votes\", \"gender\", \"locale\", \"path\", \"segment\", \"up_votes\"])\n",
209
+ "\n",
210
+ "print(common_voice)"
211
+ ]
212
+ },
213
+ {
214
+ "cell_type": "markdown",
215
+ "id": "2d63b2d2-f68a-4d74-b7f1-5127f6d16605",
216
+ "metadata": {
217
+ "id": "2d63b2d2-f68a-4d74-b7f1-5127f6d16605"
218
+ },
219
+ "source": [
220
+ "## Prepare Feature Extractor, Tokenizer and Data"
221
+ ]
222
+ },
223
+ {
224
+ "cell_type": "markdown",
225
+ "id": "601c3099-1026-439e-93e2-5635b3ba5a73",
226
+ "metadata": {
227
+ "id": "601c3099-1026-439e-93e2-5635b3ba5a73"
228
+ },
229
+ "source": [
230
+ "The ASR pipeline can be de-composed into three stages: \n",
231
+ "1) A feature extractor which pre-processes the raw audio-inputs\n",
232
+ "2) The model which performs the sequence-to-sequence mapping \n",
233
+ "3) A tokenizer which post-processes the model outputs to text format\n",
234
+ "\n",
235
+ "In 🤗 Transformers, the Whisper model has an associated feature extractor and tokenizer, \n",
236
+ "called [WhisperFeatureExtractor](https://huggingface.co/docs/transformers/main/model_doc/whisper#transformers.WhisperFeatureExtractor)\n",
237
+ "and [WhisperTokenizer](https://huggingface.co/docs/transformers/main/model_doc/whisper#transformers.WhisperTokenizer) \n",
238
+ "respectively.\n",
239
+ "\n",
240
+ "We'll go through details for setting-up the feature extractor and tokenizer one-by-one!"
241
+ ]
242
+ },
243
+ {
244
+ "cell_type": "markdown",
245
+ "id": "560332eb-3558-41a1-b500-e83a9f695f84",
246
+ "metadata": {
247
+ "id": "560332eb-3558-41a1-b500-e83a9f695f84"
248
+ },
249
+ "source": [
250
+ "### Load WhisperFeatureExtractor"
251
+ ]
252
+ },
253
+ {
254
+ "cell_type": "markdown",
255
+ "id": "32ec8068-0bd7-412d-b662-0edb9d1e7365",
256
+ "metadata": {
257
+ "id": "32ec8068-0bd7-412d-b662-0edb9d1e7365"
258
+ },
259
+ "source": [
260
+ "The Whisper feature extractor performs two operations:\n",
261
+ "1. Pads / truncates the audio inputs to 30s: any audio inputs shorter than 30s are padded to 30s with silence (zeros), and those longer that 30s are truncated to 30s\n",
262
+ "2. Converts the audio inputs to _log-Mel spectrogram_ input features, a visual representation of the audio and the form of the input expected by the Whisper model"
263
+ ]
264
+ },
265
+ {
266
+ "cell_type": "markdown",
267
+ "id": "589d9ec1-d12b-4b64-93f7-04c63997da19",
268
+ "metadata": {
269
+ "id": "589d9ec1-d12b-4b64-93f7-04c63997da19"
270
+ },
271
+ "source": [
272
+ "<figure>\n",
273
+ "<img src=\"https://raw.githubusercontent.com/sanchit-gandhi/notebooks/main/spectrogram.jpg\" alt=\"Trulli\" style=\"width:100%\">\n",
274
+ "<figcaption align = \"center\"><b>Figure 2:</b> Conversion of sampled audio array to log-Mel spectrogram.\n",
275
+ "Left: sampled 1-dimensional audio signal. Right: corresponding log-Mel spectrogram. Figure source:\n",
276
+ "<a href=\"https://ai.googleblog.com/2019/04/specaugment-new-data-augmentation.html\">Google SpecAugment Blog</a>.\n",
277
+ "</figcaption>"
278
+ ]
279
+ },
280
+ {
281
+ "cell_type": "markdown",
282
+ "id": "b2ef54d5-b946-4c1d-9fdc-adc5d01b46aa",
283
+ "metadata": {
284
+ "id": "b2ef54d5-b946-4c1d-9fdc-adc5d01b46aa"
285
+ },
286
+ "source": [
287
+ "We'll load the feature extractor from the pre-trained checkpoint with the default values:"
288
+ ]
289
+ },
290
+ {
291
+ "cell_type": "code",
292
+ "execution_count": null,
293
+ "id": "bc77d7bb-f9e2-47f5-b663-30f7a4321ce5",
294
+ "metadata": {
295
+ "id": "bc77d7bb-f9e2-47f5-b663-30f7a4321ce5"
296
+ },
297
+ "outputs": [],
298
+ "source": [
299
+ "from transformers import WhisperFeatureExtractor\n",
300
+ "\n",
301
+ "feature_extractor = WhisperFeatureExtractor.from_pretrained(model_name)"
302
+ ]
303
+ },
304
+ {
305
+ "cell_type": "markdown",
306
+ "id": "93748af7-b917-4ecf-a0c8-7d89077ff9cb",
307
+ "metadata": {
308
+ "id": "93748af7-b917-4ecf-a0c8-7d89077ff9cb"
309
+ },
310
+ "source": [
311
+ "### Load WhisperTokenizer"
312
+ ]
313
+ },
314
+ {
315
+ "attachments": {},
316
+ "cell_type": "markdown",
317
+ "id": "2bc82609-a9fb-447a-a2af-99597c864029",
318
+ "metadata": {
319
+ "id": "2bc82609-a9fb-447a-a2af-99597c864029"
320
+ },
321
+ "source": [
322
+ "The Whisper model outputs a sequence of _token ids_. The tokenizer maps each of these token ids to their corresponding text string. For Arabic, we can load the pre-trained tokenizer and use it for fine-tuning without any further modifications. We simply have to \n",
323
+ "specify the target language and the task. These arguments inform the \n",
324
+ "tokenizer to prefix the language and task tokens to the start of encoded \n",
325
+ "label sequences:"
326
+ ]
327
+ },
328
+ {
329
+ "cell_type": "code",
330
+ "execution_count": null,
331
+ "id": "c7b07f9b-ae0e-4f89-98f0-0c50d432eab6",
332
+ "metadata": {
333
+ "id": "c7b07f9b-ae0e-4f89-98f0-0c50d432eab6",
334
+ "outputId": "5c004b44-86e7-4e00-88be-39e0af5eed69"
335
+ },
336
+ "outputs": [
337
+ {
338
+ "data": {
339
+ "application/vnd.jupyter.widget-view+json": {
340
+ "model_id": "90d056e20b3e4f14ae0199a1a4ab1bb0",
341
+ "version_major": 2,
342
+ "version_minor": 0
343
+ },
344
+ "text/plain": [
345
+ "Downloading: 0%| | 0.00/829 [00:00<?, ?B/s]"
346
+ ]
347
+ },
348
+ "metadata": {},
349
+ "output_type": "display_data"
350
+ },
351
+ {
352
+ "data": {
353
+ "application/vnd.jupyter.widget-view+json": {
354
+ "model_id": "d82a88daec0e4f14add691b7b903064c",
355
+ "version_major": 2,
356
+ "version_minor": 0
357
+ },
358
+ "text/plain": [
359
+ "Downloading: 0%| | 0.00/1.04M [00:00<?, ?B/s]"
360
+ ]
361
+ },
362
+ "metadata": {},
363
+ "output_type": "display_data"
364
+ },
365
+ {
366
+ "data": {
367
+ "application/vnd.jupyter.widget-view+json": {
368
+ "model_id": "350acdb0f40e454099fa901e66de55f0",
369
+ "version_major": 2,
370
+ "version_minor": 0
371
+ },
372
+ "text/plain": [
373
+ "Downloading: 0%| | 0.00/494k [00:00<?, ?B/s]"
374
+ ]
375
+ },
376
+ "metadata": {},
377
+ "output_type": "display_data"
378
+ },
379
+ {
380
+ "data": {
381
+ "application/vnd.jupyter.widget-view+json": {
382
+ "model_id": "2e6a82a462cc411d90fa1bea4ee60790",
383
+ "version_major": 2,
384
+ "version_minor": 0
385
+ },
386
+ "text/plain": [
387
+ "Downloading: 0%| | 0.00/52.7k [00:00<?, ?B/s]"
388
+ ]
389
+ },
390
+ "metadata": {},
391
+ "output_type": "display_data"
392
+ },
393
+ {
394
+ "data": {
395
+ "application/vnd.jupyter.widget-view+json": {
396
+ "model_id": "c74bfee0198b4817832ea86e8e88d96c",
397
+ "version_major": 2,
398
+ "version_minor": 0
399
+ },
400
+ "text/plain": [
401
+ "Downloading: 0%| | 0.00/2.11k [00:00<?, ?B/s]"
402
+ ]
403
+ },
404
+ "metadata": {},
405
+ "output_type": "display_data"
406
+ },
407
+ {
408
+ "data": {
409
+ "application/vnd.jupyter.widget-view+json": {
410
+ "model_id": "04fb2d81eff646068e10475a08ae42f4",
411
+ "version_major": 2,
412
+ "version_minor": 0
413
+ },
414
+ "text/plain": [
415
+ "Downloading: 0%| | 0.00/2.06k [00:00<?, ?B/s]"
416
+ ]
417
+ },
418
+ "metadata": {},
419
+ "output_type": "display_data"
420
+ }
421
+ ],
422
+ "source": [
423
+ "from transformers import WhisperTokenizer\n",
424
+ "\n",
425
+ "tokenizer = WhisperTokenizer.from_pretrained(\"openai/whisper-small\", language=\"Arabic\", task=\"transcribe\")"
426
+ ]
427
+ },
428
+ {
429
+ "cell_type": "markdown",
430
+ "id": "d2ef23f3-f4a8-483a-a2dc-080a7496cb1b",
431
+ "metadata": {
432
+ "id": "d2ef23f3-f4a8-483a-a2dc-080a7496cb1b"
433
+ },
434
+ "source": [
435
+ "### Combine To Create A WhisperProcessor"
436
+ ]
437
+ },
438
+ {
439
+ "cell_type": "markdown",
440
+ "id": "5ff67654-5a29-4bb8-a69d-0228946c6f8d",
441
+ "metadata": {
442
+ "id": "5ff67654-5a29-4bb8-a69d-0228946c6f8d"
443
+ },
444
+ "source": [
445
+ "To simplify using the feature extractor and tokenizer, we can _wrap_ \n",
446
+ "both into a single `WhisperProcessor` class. This processor object \n",
447
+ "inherits from the `WhisperFeatureExtractor` and `WhisperProcessor`, \n",
448
+ "and can be used on the audio inputs and model predictions as required. \n",
449
+ "In doing so, we only need to keep track of two objects during training: \n",
450
+ "the `processor` and the `model`:"
451
+ ]
452
+ },
453
+ {
454
+ "cell_type": "code",
455
+ "execution_count": null,
456
+ "id": "77d9f0c5-8607-4642-a8ac-c3ab2e223ea6",
457
+ "metadata": {
458
+ "id": "77d9f0c5-8607-4642-a8ac-c3ab2e223ea6"
459
+ },
460
+ "outputs": [],
461
+ "source": [
462
+ "from transformers import WhisperProcessor\n",
463
+ "\n",
464
+ "processor = WhisperProcessor.from_pretrained(model_name, language=\"Arabic\", task=\"transcribe\")"
465
+ ]
466
+ },
467
+ {
468
+ "cell_type": "markdown",
469
+ "id": "381acd09-0b0f-4d04-9eb3-f028ac0e5f2c",
470
+ "metadata": {
471
+ "id": "381acd09-0b0f-4d04-9eb3-f028ac0e5f2c"
472
+ },
473
+ "source": [
474
+ "### Prepare Data"
475
+ ]
476
+ },
477
+ {
478
+ "cell_type": "markdown",
479
+ "id": "9649bf01-2e8a-45e5-8fca-441c13637b8f",
480
+ "metadata": {
481
+ "id": "9649bf01-2e8a-45e5-8fca-441c13637b8f"
482
+ },
483
+ "source": [
484
+ "Let's print the first example of the Common Voice dataset to see \n",
485
+ "what form the data is in:"
486
+ ]
487
+ },
488
+ {
489
+ "cell_type": "code",
490
+ "execution_count": null,
491
+ "id": "6e6b0ec5-0c94-4e2c-ae24-c791be1b2255",
492
+ "metadata": {
493
+ "id": "6e6b0ec5-0c94-4e2c-ae24-c791be1b2255"
494
+ },
495
+ "outputs": [],
496
+ "source": [
497
+ "print(common_voice[\"train\"][0])"
498
+ ]
499
+ },
500
+ {
501
+ "cell_type": "markdown",
502
+ "id": "5a679f05-063d-41b3-9b58-4fc9c6ccf4fd",
503
+ "metadata": {
504
+ "id": "5a679f05-063d-41b3-9b58-4fc9c6ccf4fd"
505
+ },
506
+ "source": [
507
+ "Since \n",
508
+ "our input audio is sampled at 48kHz, we need to _downsample_ it to \n",
509
+ "16kHz prior to passing it to the Whisper feature extractor, 16kHz being the sampling rate expected by the Whisper model. \n",
510
+ "\n",
511
+ "We'll set the audio inputs to the correct sampling rate using dataset's \n",
512
+ "[`cast_column`](https://huggingface.co/docs/datasets/package_reference/main_classes.html?highlight=cast_column#datasets.DatasetDict.cast_column)\n",
513
+ "method. This operation does not change the audio in-place, \n",
514
+ "but rather signals to `datasets` to resample audio samples _on the fly_ the \n",
515
+ "first time that they are loaded:"
516
+ ]
517
+ },
518
+ {
519
+ "cell_type": "code",
520
+ "execution_count": null,
521
+ "id": "f12e2e57-156f-417b-8cfb-69221cc198e8",
522
+ "metadata": {
523
+ "id": "f12e2e57-156f-417b-8cfb-69221cc198e8"
524
+ },
525
+ "outputs": [],
526
+ "source": [
527
+ "from datasets import Audio\n",
528
+ "\n",
529
+ "common_voice = common_voice.cast_column(\"audio\", Audio(sampling_rate=16000))"
530
+ ]
531
+ },
532
+ {
533
+ "cell_type": "markdown",
534
+ "id": "00382a3e-abec-4cdd-a54c-d1aaa3ea4707",
535
+ "metadata": {
536
+ "id": "00382a3e-abec-4cdd-a54c-d1aaa3ea4707"
537
+ },
538
+ "source": [
539
+ "Re-loading the first audio sample in the Common Voice dataset will resample \n",
540
+ "it to the desired sampling rate:"
541
+ ]
542
+ },
543
+ {
544
+ "cell_type": "code",
545
+ "execution_count": null,
546
+ "id": "87122d71-289a-466a-afcf-fa354b18946b",
547
+ "metadata": {
548
+ "id": "87122d71-289a-466a-afcf-fa354b18946b"
549
+ },
550
+ "outputs": [],
551
+ "source": [
552
+ "print(common_voice[\"train\"][0])"
553
+ ]
554
+ },
555
+ {
556
+ "cell_type": "markdown",
557
+ "id": "3df7378a-a4c0-45d7-8d07-defbd1062ab6",
558
+ "metadata": {},
559
+ "source": [
560
+ "We'll define our pre-processing strategy. We advise that you **do not** lower-case the transcriptions or remove punctuation unless mixing different datasets. This will enable you to fine-tune Whisper models that can predict punctuation and casing. Later, you will see how we can evaluate the predictions without punctuation or casing, so that the models benefit from the WER improvement obtained by normalising the transcriptions while still predicting fully formatted transcriptions."
561
+ ]
562
+ },
563
+ {
564
+ "cell_type": "code",
565
+ "execution_count": null,
566
+ "id": "d041650e-1c48-4439-87b3-5b6f4a514107",
567
+ "metadata": {},
568
+ "outputs": [],
569
+ "source": [
570
+ "from transformers.models.whisper.english_normalizer import BasicTextNormalizer\n",
571
+ "\n",
572
+ "do_lower_case = False\n",
573
+ "do_remove_punctuation = False\n",
574
+ "\n",
575
+ "normalizer = BasicTextNormalizer()"
576
+ ]
577
+ },
578
+ {
579
+ "cell_type": "markdown",
580
+ "id": "89e12c2e-2f14-479b-987b-f0c75c881095",
581
+ "metadata": {},
582
+ "source": [
583
+ "Now we can write a function to prepare our data ready for the model:\n",
584
+ "1. We load and resample the audio data by calling `batch[\"audio\"]`. As explained above, 🤗 Datasets performs any necessary resampling operations on the fly.\n",
585
+ "2. We use the feature extractor to compute the log-Mel spectrogram input features from our 1-dimensional audio array.\n",
586
+ "3. We perform any optional pre-processing (lower-case or remove punctuation).\n",
587
+ "4. We encode the transcriptions to label ids through the use of the tokenizer."
588
+ ]
589
+ },
590
+ {
591
+ "cell_type": "code",
592
+ "execution_count": null,
593
+ "id": "c085911c-a10a-41ef-8874-306e0503e9bb",
594
+ "metadata": {},
595
+ "outputs": [],
596
+ "source": [
597
+ "def prepare_dataset(batch):\n",
598
+ " # load and (possibly) resample audio data to 16kHz\n",
599
+ " audio = batch[\"audio\"]\n",
600
+ "\n",
601
+ " # compute log-Mel input features from input audio array \n",
602
+ " batch[\"input_features\"] = processor.feature_extractor(audio[\"array\"], sampling_rate=audio[\"sampling_rate\"]).input_features[0]\n",
603
+ " # compute input length of audio sample in seconds\n",
604
+ " batch[\"input_length\"] = len(audio[\"array\"]) / audio[\"sampling_rate\"]\n",
605
+ " \n",
606
+ " # optional pre-processing steps\n",
607
+ " transcription = batch[\"sentence\"]\n",
608
+ " if do_lower_case:\n",
609
+ " transcription = transcription.lower()\n",
610
+ " if do_remove_punctuation:\n",
611
+ " transcription = normalizer(transcription).strip()\n",
612
+ " \n",
613
+ " # encode target text to label ids\n",
614
+ " batch[\"labels\"] = processor.tokenizer(transcription).input_ids\n",
615
+ " return batch"
616
+ ]
617
+ },
618
+ {
619
+ "cell_type": "markdown",
620
+ "id": "8c960965-9fb6-466f-9dbd-c9d43e71d9d0",
621
+ "metadata": {
622
+ "id": "70b319fb-2439-4ef6-a70d-a47bf41c4a13"
623
+ },
624
+ "source": [
625
+ "We can apply the data preparation function to all of our training examples using dataset's `.map` method. The argument `num_proc` specifies how many CPU cores to use. Setting `num_proc` > 1 will enable multiprocessing. If the `.map` method hangs with multiprocessing, set `num_proc=1` and process the dataset sequentially."
626
+ ]
627
+ },
628
+ {
629
+ "cell_type": "code",
630
+ "execution_count": null,
631
+ "id": "7b73ab39-ffaf-4b9e-86e5-782963c6134b",
632
+ "metadata": {
633
+ "id": "7b73ab39-ffaf-4b9e-86e5-782963c6134b"
634
+ },
635
+ "outputs": [],
636
+ "source": [
637
+ "common_voice = common_voice.map(prepare_dataset, remove_columns=common_voice.column_names[\"train\"], num_proc=2)"
638
+ ]
639
+ },
640
+ {
641
+ "cell_type": "markdown",
642
+ "id": "54ce0fdb-7218-4a4d-b175-383980fec0df",
643
+ "metadata": {},
644
+ "source": [
645
+ "Finally, we filter any training data with audio samples longer than 30s. These samples would otherwise be truncated by the Whisper feature-extractor which could affect the stability of training. We define a function that returns `True` for samples that are less than 30s, and `False` for those that are longer:"
646
+ ]
647
+ },
648
+ {
649
+ "cell_type": "code",
650
+ "execution_count": null,
651
+ "id": "01cb25ef-4bb0-4325-9461-f59198acadf6",
652
+ "metadata": {},
653
+ "outputs": [],
654
+ "source": [
655
+ "max_input_length = 30.0\n",
656
+ "\n",
657
+ "def is_audio_in_length_range(length):\n",
658
+ " return length < max_input_length"
659
+ ]
660
+ },
661
+ {
662
+ "cell_type": "markdown",
663
+ "id": "30e676a8-7ca8-4850-8c5d-5b2b00d13fba",
664
+ "metadata": {},
665
+ "source": [
666
+ "We apply our filter function to all samples of our training dataset through 🤗 Datasets' `.filter` method:"
667
+ ]
668
+ },
669
+ {
670
+ "cell_type": "code",
671
+ "execution_count": null,
672
+ "id": "333f7f6e-6053-4d3b-8924-c733c79b82ac",
673
+ "metadata": {},
674
+ "outputs": [],
675
+ "source": [
676
+ "common_voice[\"train\"] = common_voice[\"train\"].filter(\n",
677
+ " is_audio_in_length_range,\n",
678
+ " input_columns=[\"input_length\"],\n",
679
+ ")"
680
+ ]
681
+ },
682
+ {
683
+ "cell_type": "markdown",
684
+ "id": "263a5a58-0239-4a25-b0df-c625fc9c5810",
685
+ "metadata": {
686
+ "id": "263a5a58-0239-4a25-b0df-c625fc9c5810"
687
+ },
688
+ "source": [
689
+ "## Training and Evaluation"
690
+ ]
691
+ },
692
+ {
693
+ "attachments": {},
694
+ "cell_type": "markdown",
695
+ "id": "a693e768-c5a6-453f-89a1-b601dcf7daf7",
696
+ "metadata": {
697
+ "id": "a693e768-c5a6-453f-89a1-b601dcf7daf7"
698
+ },
699
+ "source": [
700
+ "Now that we've prepared our data, we're ready to dive into the training pipeline. \n",
701
+ "The [🤗 Trainer](https://huggingface.co/transformers/master/main_classes/trainer.html?highlight=trainer)\n",
702
+ "will do much of the heavy lifting for us. All we have to do is:\n",
703
+ "\n",
704
+ "- Define a data collator: the data collator takes our pre-processed data and prepares PyTorch tensors ready for the model.\n",
705
+ "\n",
706
+ "- Evaluation metrics: during evaluation, we want to evaluate the model using the [word error rate (WER)](https://huggingface.co/metrics/wer) metric. We need to define a `compute_metrics` function that handles this computation.\n",
707
+ "\n",
708
+ "- Load a pre-trained checkpoint: we need to load a pre-trained checkpoint and configure it correctly for training.\n",
709
+ "\n",
710
+ "- Define the training configuration: this will be used by the 🤗 Trainer to define the training schedule.\n",
711
+ "\n",
712
+ "Once we've fine-tuned the model, we will evaluate it on the test data to verify that we have correctly trained it \n",
713
+ "to transcribe speech in Arabic."
714
+ ]
715
+ },
716
+ {
717
+ "cell_type": "markdown",
718
+ "id": "8d230e6d-624c-400a-bbf5-fa660881df25",
719
+ "metadata": {
720
+ "id": "8d230e6d-624c-400a-bbf5-fa660881df25"
721
+ },
722
+ "source": [
723
+ "### Define a Data Collator"
724
+ ]
725
+ },
726
+ {
727
+ "cell_type": "markdown",
728
+ "id": "04def221-0637-4a69-b242-d3f0c1d0ee78",
729
+ "metadata": {
730
+ "id": "04def221-0637-4a69-b242-d3f0c1d0ee78"
731
+ },
732
+ "source": [
733
+ "The data collator for a sequence-to-sequence speech model is unique in the sense that it \n",
734
+ "treats the `input_features` and `labels` independently: the `input_features` must be \n",
735
+ "handled by the feature extractor and the `labels` by the tokenizer.\n",
736
+ "\n",
737
+ "The `input_features` are already padded to 30s and converted to a log-Mel spectrogram \n",
738
+ "of fixed dimension by action of the feature extractor, so all we have to do is convert the `input_features`\n",
739
+ "to batched PyTorch tensors. We do this using the feature extractor's `.pad` method with `return_tensors=pt`.\n",
740
+ "\n",
741
+ "The `labels` on the other hand are un-padded. We first pad the sequences\n",
742
+ "to the maximum length in the batch using the tokenizer's `.pad` method. The padding tokens \n",
743
+ "are then replaced by `-100` so that these tokens are **not** taken into account when \n",
744
+ "computing the loss. We then cut the BOS token from the start of the label sequence as we \n",
745
+ "append it later during training.\n",
746
+ "\n",
747
+ "We can leverage the `WhisperProcessor` we defined earlier to perform both the \n",
748
+ "feature extractor and the tokenizer operations:"
749
+ ]
750
+ },
751
+ {
752
+ "cell_type": "code",
753
+ "execution_count": null,
754
+ "id": "8326221e-ec13-4731-bb4e-51e5fc1486c5",
755
+ "metadata": {
756
+ "id": "8326221e-ec13-4731-bb4e-51e5fc1486c5"
757
+ },
758
+ "outputs": [],
759
+ "source": [
760
+ "import torch\n",
761
+ "\n",
762
+ "from dataclasses import dataclass\n",
763
+ "from typing import Any, Dict, List, Union\n",
764
+ "\n",
765
+ "@dataclass\n",
766
+ "class DataCollatorSpeechSeq2SeqWithPadding:\n",
767
+ " processor: Any\n",
768
+ "\n",
769
+ " def __call__(self, features: List[Dict[str, Union[List[int], torch.Tensor]]]) -> Dict[str, torch.Tensor]:\n",
770
+ " # split inputs and labels since they have to be of different lengths and need different padding methods\n",
771
+ " # first treat the audio inputs by simply returning torch tensors\n",
772
+ " input_features = [{\"input_features\": feature[\"input_features\"]} for feature in features]\n",
773
+ " batch = self.processor.feature_extractor.pad(input_features, return_tensors=\"pt\")\n",
774
+ "\n",
775
+ " # get the tokenized label sequences\n",
776
+ " label_features = [{\"input_ids\": feature[\"labels\"]} for feature in features]\n",
777
+ " # pad the labels to max length\n",
778
+ " labels_batch = self.processor.tokenizer.pad(label_features, return_tensors=\"pt\")\n",
779
+ "\n",
780
+ " # replace padding with -100 to ignore loss correctly\n",
781
+ " labels = labels_batch[\"input_ids\"].masked_fill(labels_batch.attention_mask.ne(1), -100)\n",
782
+ "\n",
783
+ " # if bos token is appended in previous tokenization step,\n",
784
+ " # cut bos token here as it's append later anyways\n",
785
+ " if (labels[:, 0] == self.processor.tokenizer.bos_token_id).all().cpu().item():\n",
786
+ " labels = labels[:, 1:]\n",
787
+ "\n",
788
+ " batch[\"labels\"] = labels\n",
789
+ "\n",
790
+ " return batch"
791
+ ]
792
+ },
793
+ {
794
+ "cell_type": "markdown",
795
+ "id": "3cae7dbf-8a50-456e-a3a8-7fd005390f86",
796
+ "metadata": {
797
+ "id": "3cae7dbf-8a50-456e-a3a8-7fd005390f86"
798
+ },
799
+ "source": [
800
+ "Let's initialise the data collator we've just defined:"
801
+ ]
802
+ },
803
+ {
804
+ "cell_type": "code",
805
+ "execution_count": null,
806
+ "id": "fc834702-c0d3-4a96-b101-7b87be32bf42",
807
+ "metadata": {
808
+ "id": "fc834702-c0d3-4a96-b101-7b87be32bf42"
809
+ },
810
+ "outputs": [],
811
+ "source": [
812
+ "data_collator = DataCollatorSpeechSeq2SeqWithPadding(processor=processor)"
813
+ ]
814
+ },
815
+ {
816
+ "cell_type": "markdown",
817
+ "id": "d62bb2ab-750a-45e7-82e9-61d6f4805698",
818
+ "metadata": {
819
+ "id": "d62bb2ab-750a-45e7-82e9-61d6f4805698"
820
+ },
821
+ "source": [
822
+ "### Evaluation Metrics"
823
+ ]
824
+ },
825
+ {
826
+ "cell_type": "markdown",
827
+ "id": "66fee1a7-a44c-461e-b047-c3917221572e",
828
+ "metadata": {
829
+ "id": "66fee1a7-a44c-461e-b047-c3917221572e"
830
+ },
831
+ "source": [
832
+ "We'll use the word error rate (WER) metric, the 'de-facto' metric for assessing \n",
833
+ "ASR systems. For more information, refer to the WER [docs](https://huggingface.co/metrics/wer). We'll load the WER metric from 🤗 Evaluate:"
834
+ ]
835
+ },
836
+ {
837
+ "cell_type": "code",
838
+ "execution_count": null,
839
+ "id": "b22b4011-f31f-4b57-b684-c52332f92890",
840
+ "metadata": {
841
+ "id": "b22b4011-f31f-4b57-b684-c52332f92890"
842
+ },
843
+ "outputs": [],
844
+ "source": [
845
+ "import evaluate\n",
846
+ "\n",
847
+ "metric = evaluate.load(\"wer\")"
848
+ ]
849
+ },
850
+ {
851
+ "cell_type": "markdown",
852
+ "id": "4f32cab6-31f0-4cb9-af4c-40ba0f5fc508",
853
+ "metadata": {
854
+ "id": "4f32cab6-31f0-4cb9-af4c-40ba0f5fc508"
855
+ },
856
+ "source": [
857
+ "We then simply have to define a function that takes our model \n",
858
+ "predictions and returns the WER metric. This function, called\n",
859
+ "`compute_metrics`, first replaces `-100` with the `pad_token_id`\n",
860
+ "in the `label_ids` (undoing the step we applied in the \n",
861
+ "data collator to ignore padded tokens correctly in the loss).\n",
862
+ "It then decodes the predicted and label ids to strings. Finally,\n",
863
+ "it computes the WER between the predictions and reference labels. \n",
864
+ "Here, we have the option of evaluating with the 'normalised' transcriptions \n",
865
+ "and predictions. We recommend you set this to `True` to benefit from the WER \n",
866
+ "improvement obtained by normalising the transcriptions."
867
+ ]
868
+ },
869
+ {
870
+ "cell_type": "code",
871
+ "execution_count": null,
872
+ "id": "23959a70-22d0-4ffe-9fa1-72b61e75bb52",
873
+ "metadata": {
874
+ "id": "23959a70-22d0-4ffe-9fa1-72b61e75bb52"
875
+ },
876
+ "outputs": [],
877
+ "source": [
878
+ "# evaluate with the 'normalised' WER\n",
879
+ "do_normalize_eval = True\n",
880
+ "\n",
881
+ "def compute_metrics(pred):\n",
882
+ " pred_ids = pred.predictions\n",
883
+ " label_ids = pred.label_ids\n",
884
+ "\n",
885
+ " # replace -100 with the pad_token_id\n",
886
+ " label_ids[label_ids == -100] = processor.tokenizer.pad_token_id\n",
887
+ "\n",
888
+ " # we do not want to group tokens when computing the metrics\n",
889
+ " pred_str = processor.tokenizer.batch_decode(pred_ids, skip_special_tokens=True)\n",
890
+ " label_str = processor.tokenizer.batch_decode(label_ids, skip_special_tokens=True)\n",
891
+ "\n",
892
+ " if do_normalize_eval:\n",
893
+ " pred_str = [normalizer(pred) for pred in pred_str]\n",
894
+ " label_str = [normalizer(label) for label in label_str]\n",
895
+ "\n",
896
+ " wer = 100 * metric.compute(predictions=pred_str, references=label_str)\n",
897
+ "\n",
898
+ " return {\"wer\": wer}"
899
+ ]
900
+ },
901
+ {
902
+ "cell_type": "markdown",
903
+ "id": "daf2a825-6d9f-4a23-b145-c37c0039075b",
904
+ "metadata": {
905
+ "id": "daf2a825-6d9f-4a23-b145-c37c0039075b"
906
+ },
907
+ "source": [
908
+ "### Load a Pre-Trained Checkpoint"
909
+ ]
910
+ },
911
+ {
912
+ "cell_type": "markdown",
913
+ "id": "437a97fa-4864-476b-8abc-f28b8166cfa5",
914
+ "metadata": {
915
+ "id": "437a97fa-4864-476b-8abc-f28b8166cfa5"
916
+ },
917
+ "source": [
918
+ "Now let's load the pre-trained Whisper `small` checkpoint. Again, this \n",
919
+ "is trivial through use of 🤗 Transformers!"
920
+ ]
921
+ },
922
+ {
923
+ "cell_type": "code",
924
+ "execution_count": null,
925
+ "id": "5a10cc4b-07ec-4ebd-ac1d-7c601023594f",
926
+ "metadata": {
927
+ "id": "5a10cc4b-07ec-4ebd-ac1d-7c601023594f"
928
+ },
929
+ "outputs": [],
930
+ "source": [
931
+ "from transformers import WhisperForConditionalGeneration\n",
932
+ "\n",
933
+ "model = WhisperForConditionalGeneration.from_pretrained(model_name)"
934
+ ]
935
+ },
936
+ {
937
+ "cell_type": "markdown",
938
+ "id": "a15ead5f-2277-4a39-937b-585c2497b2df",
939
+ "metadata": {
940
+ "id": "a15ead5f-2277-4a39-937b-585c2497b2df"
941
+ },
942
+ "source": [
943
+ "Override generation arguments - no tokens are forced as decoder outputs (see [`forced_decoder_ids`](https://huggingface.co/docs/transformers/main_classes/text_generation#transformers.generation_utils.GenerationMixin.generate.forced_decoder_ids)), no tokens are suppressed during generation (see [`suppress_tokens`](https://huggingface.co/docs/transformers/main_classes/text_generation#transformers.generation_utils.GenerationMixin.generate.suppress_tokens)). Set `use_cache` to False since we're using gradient checkpointing, and the two are incompatible:"
944
+ ]
945
+ },
946
+ {
947
+ "cell_type": "code",
948
+ "execution_count": null,
949
+ "id": "62038ba3-88ed-4fce-84db-338f50dcd04f",
950
+ "metadata": {
951
+ "id": "62038ba3-88ed-4fce-84db-338f50dcd04f"
952
+ },
953
+ "outputs": [],
954
+ "source": [
955
+ "model.config.forced_decoder_ids = None\n",
956
+ "model.config.suppress_tokens = []\n",
957
+ "model.config.use_cache = False"
958
+ ]
959
+ },
960
+ {
961
+ "cell_type": "markdown",
962
+ "id": "2178dea4-80ca-47b6-b6ea-ba1915c90c06",
963
+ "metadata": {
964
+ "id": "2178dea4-80ca-47b6-b6ea-ba1915c90c06"
965
+ },
966
+ "source": [
967
+ "### Define the Training Configuration"
968
+ ]
969
+ },
970
+ {
971
+ "cell_type": "markdown",
972
+ "id": "c21af1e9-0188-4134-ac82-defc7bdcc436",
973
+ "metadata": {
974
+ "id": "c21af1e9-0188-4134-ac82-defc7bdcc436"
975
+ },
976
+ "source": [
977
+ "In the final step, we define all the parameters related to training. For more detail on the training arguments, refer to the Seq2SeqTrainingArguments [docs](https://huggingface.co/docs/transformers/main_classes/trainer#transformers.Seq2SeqTrainingArguments)."
978
+ ]
979
+ },
980
+ {
981
+ "cell_type": "code",
982
+ "execution_count": null,
983
+ "id": "0ae3e9af-97b7-4aa0-ae85-20b23b5bcb3a",
984
+ "metadata": {
985
+ "id": "0ae3e9af-97b7-4aa0-ae85-20b23b5bcb3a"
986
+ },
987
+ "outputs": [],
988
+ "source": [
989
+ "from transformers import Seq2SeqTrainingArguments\n",
990
+ "\n",
991
+ "training_args = Seq2SeqTrainingArguments(\n",
992
+ " output_dir=\"./\",\n",
993
+ " per_device_train_batch_size=64,\n",
994
+ " gradient_accumulation_steps=1, # increase by 2x for every 2x decrease in batch size\n",
995
+ " learning_rate=1e-5,\n",
996
+ " warmup_steps=500,\n",
997
+ " max_steps=5000,\n",
998
+ " gradient_checkpointing=True,\n",
999
+ " fp16=True,\n",
1000
+ " evaluation_strategy=\"steps\",\n",
1001
+ " per_device_eval_batch_size=8,\n",
1002
+ " predict_with_generate=True,\n",
1003
+ " generation_max_length=225,\n",
1004
+ " save_steps=1000,\n",
1005
+ " eval_steps=1000,\n",
1006
+ " logging_steps=25,\n",
1007
+ " report_to=[\"tensorboard\"],\n",
1008
+ " load_best_model_at_end=True,\n",
1009
+ " metric_for_best_model=\"wer\",\n",
1010
+ " greater_is_better=False,\n",
1011
+ " push_to_hub=True,\n",
1012
+ ")"
1013
+ ]
1014
+ },
1015
+ {
1016
+ "cell_type": "markdown",
1017
+ "id": "b3a944d8-3112-4552-82a0-be25988b3857",
1018
+ "metadata": {
1019
+ "id": "b3a944d8-3112-4552-82a0-be25988b3857"
1020
+ },
1021
+ "source": [
1022
+ "**Note**: if one does not want to upload the model checkpoints to the Hub, \n",
1023
+ "set `push_to_hub=False`."
1024
+ ]
1025
+ },
1026
+ {
1027
+ "cell_type": "markdown",
1028
+ "id": "bac29114-d226-4f54-97cf-8718c9f94e1e",
1029
+ "metadata": {
1030
+ "id": "bac29114-d226-4f54-97cf-8718c9f94e1e"
1031
+ },
1032
+ "source": [
1033
+ "We can forward the training arguments to the 🤗 Trainer along with our model,\n",
1034
+ "dataset, data collator and `compute_metrics` function:"
1035
+ ]
1036
+ },
1037
+ {
1038
+ "cell_type": "code",
1039
+ "execution_count": null,
1040
+ "id": "d546d7fe-0543-479a-b708-2ebabec19493",
1041
+ "metadata": {
1042
+ "id": "d546d7fe-0543-479a-b708-2ebabec19493"
1043
+ },
1044
+ "outputs": [],
1045
+ "source": [
1046
+ "from transformers import Seq2SeqTrainer\n",
1047
+ "\n",
1048
+ "trainer = Seq2SeqTrainer(\n",
1049
+ " args=training_args,\n",
1050
+ " model=model,\n",
1051
+ " train_dataset=common_voice[\"train\"],\n",
1052
+ " eval_dataset=common_voice[\"test\"],\n",
1053
+ " data_collator=data_collator,\n",
1054
+ " compute_metrics=compute_metrics,\n",
1055
+ " tokenizer=processor.feature_extractor,\n",
1056
+ ")"
1057
+ ]
1058
+ },
1059
+ {
1060
+ "cell_type": "markdown",
1061
+ "id": "uOrRhDGtN5S4",
1062
+ "metadata": {
1063
+ "id": "uOrRhDGtN5S4"
1064
+ },
1065
+ "source": [
1066
+ "We'll save the processor object once before starting training. Since the processor is not trainable, it won't change over the course of training:"
1067
+ ]
1068
+ },
1069
+ {
1070
+ "cell_type": "code",
1071
+ "execution_count": null,
1072
+ "id": "-2zQwMfEOBJq",
1073
+ "metadata": {
1074
+ "id": "-2zQwMfEOBJq"
1075
+ },
1076
+ "outputs": [],
1077
+ "source": [
1078
+ "processor.save_pretrained(training_args.output_dir)"
1079
+ ]
1080
+ },
1081
+ {
1082
+ "cell_type": "markdown",
1083
+ "id": "7f404cf9-4345-468c-8196-4bd101d9bd51",
1084
+ "metadata": {
1085
+ "id": "7f404cf9-4345-468c-8196-4bd101d9bd51"
1086
+ },
1087
+ "source": [
1088
+ "### Training"
1089
+ ]
1090
+ },
1091
+ {
1092
+ "cell_type": "markdown",
1093
+ "id": "5e8b8d56-5a70-4f68-bd2e-f0752d0bd112",
1094
+ "metadata": {
1095
+ "id": "5e8b8d56-5a70-4f68-bd2e-f0752d0bd112"
1096
+ },
1097
+ "source": [
1098
+ "Training will take approximately 5-10 hours depending on your GPU. The peak GPU memory for the given training configuration is approximately 36GB. \n",
1099
+ "Depending on your GPU, it is possible that you will encounter a CUDA `\"out-of-memory\"` error when you launch training. \n",
1100
+ "In this case, you can reduce the `per_device_train_batch_size` incrementally by factors of 2 \n",
1101
+ "and employ [`gradient_accumulation_steps`](https://huggingface.co/docs/transformers/main_classes/trainer#transformers.Seq2SeqTrainingArguments.gradient_accumulation_steps)\n",
1102
+ "to compensate.\n",
1103
+ "\n",
1104
+ "To launch training, simply execute:"
1105
+ ]
1106
+ },
1107
+ {
1108
+ "cell_type": "code",
1109
+ "execution_count": null,
1110
+ "id": "ee8b7b8e-1c9a-4d77-9137-1778a629e6de",
1111
+ "metadata": {
1112
+ "id": "ee8b7b8e-1c9a-4d77-9137-1778a629e6de"
1113
+ },
1114
+ "outputs": [],
1115
+ "source": [
1116
+ "trainer.train()"
1117
+ ]
1118
+ },
1119
+ {
1120
+ "cell_type": "markdown",
1121
+ "id": "810ced54-7187-4a06-b2fe-ba6dcca94dc3",
1122
+ "metadata": {
1123
+ "id": "810ced54-7187-4a06-b2fe-ba6dcca94dc3"
1124
+ },
1125
+ "source": [
1126
+ "We can label our checkpoint with the `whisper-event` tag on push by setting the appropriate key-word arguments (kwargs):"
1127
+ ]
1128
+ },
1129
+ {
1130
+ "cell_type": "code",
1131
+ "execution_count": null,
1132
+ "id": "c704f91e-241b-48c9-b8e0-f0da396a9663",
1133
+ "metadata": {
1134
+ "id": "c704f91e-241b-48c9-b8e0-f0da396a9663"
1135
+ },
1136
+ "outputs": [],
1137
+ "source": [
1138
+ "kwargs = {\n",
1139
+ " \"dataset_tags\": \"mozilla-foundation/common_voice_11_0\",\n",
1140
+ " \"dataset\": \"Common Voice 11.0\", # a 'pretty' name for the training dataset\n",
1141
+ " \"language\": \"ar\",\n",
1142
+ " \"model_name\": \"Whisper Small ar - Zaid Alyafeai\", # a 'pretty' name for your model\n",
1143
+ " \"finetuned_from\": model_name,\n",
1144
+ " \"tasks\": \"automatic-speech-recognition\",\n",
1145
+ " \"tags\": \"whisper-event\",\n",
1146
+ "}"
1147
+ ]
1148
+ },
1149
+ {
1150
+ "cell_type": "markdown",
1151
+ "id": "090d676a-f944-4297-a938-a40eda0b2b68",
1152
+ "metadata": {
1153
+ "id": "090d676a-f944-4297-a938-a40eda0b2b68"
1154
+ },
1155
+ "source": [
1156
+ "The training results can now be uploaded to the Hub. To do so, execute the `push_to_hub` command and save the preprocessor object we created:"
1157
+ ]
1158
+ },
1159
+ {
1160
+ "cell_type": "code",
1161
+ "execution_count": null,
1162
+ "id": "d7030622-caf7-4039-939b-6195cdaa2585",
1163
+ "metadata": {
1164
+ "id": "d7030622-caf7-4039-939b-6195cdaa2585"
1165
+ },
1166
+ "outputs": [],
1167
+ "source": [
1168
+ "trainer.push_to_hub(**kwargs)"
1169
+ ]
1170
+ },
1171
+ {
1172
+ "cell_type": "markdown",
1173
+ "id": "ca743fbd-602c-48d4-ba8d-a2fe60af64ba",
1174
+ "metadata": {
1175
+ "id": "ca743fbd-602c-48d4-ba8d-a2fe60af64ba"
1176
+ },
1177
+ "source": [
1178
+ "## Closing Remarks"
1179
+ ]
1180
+ },
1181
+ {
1182
+ "cell_type": "markdown",
1183
+ "id": "7f737783-2870-4e35-aa11-86a42d7d997a",
1184
+ "metadata": {
1185
+ "id": "7f737783-2870-4e35-aa11-86a42d7d997a"
1186
+ },
1187
+ "source": [
1188
+ "In this blog, we covered a step-by-step guide on fine-tuning Whisper for multilingual ASR \n",
1189
+ "using 🤗 Datasets, Transformers and the Hugging Face Hub. For more details on the Whisper model, the Common Voice dataset and the theory behind fine-tuning, refere to the accompanying [blog post](https://huggingface.co/blog/fine-tune-whisper). If you're interested in fine-tuning other \n",
1190
+ "Transformers models, both for English and multilingual ASR, be sure to check out the \n",
1191
+ "examples scripts at [examples/pytorch/speech-recognition](https://github.com/huggingface/transformers/tree/main/examples/pytorch/speech-recognition)."
1192
+ ]
1193
+ }
1194
+ ],
1195
+ "metadata": {
1196
+ "colab": {
1197
+ "include_colab_link": true,
1198
+ "provenance": []
1199
+ },
1200
+ "kernelspec": {
1201
+ "display_name": "Python 3",
1202
+ "language": "python",
1203
+ "name": "python3"
1204
+ },
1205
+ "language_info": {
1206
+ "codemirror_mode": {
1207
+ "name": "ipython",
1208
+ "version": 3
1209
+ },
1210
+ "file_extension": ".py",
1211
+ "mimetype": "text/x-python",
1212
+ "name": "python",
1213
+ "nbconvert_exporter": "python",
1214
+ "pygments_lexer": "ipython3",
1215
+ "version": "3.9.5 (default, Nov 23 2021, 15:27:38) \n[GCC 9.3.0]"
1216
+ },
1217
+ "vscode": {
1218
+ "interpreter": {
1219
+ "hash": "f9f85f796d01129d0dd105a088854619f454435301f6ffec2fea96ecbd9be4ac"
1220
+ }
1221
+ }
1222
+ },
1223
+ "nbformat": 4,
1224
+ "nbformat_minor": 5
1225
+ }
.ipynb_checkpoints/mgb2_speech-checkpoint.py ADDED
@@ -0,0 +1,169 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import datasets
2
+ import os
3
+
4
+
5
+ _DESCRIPTION = "MGB2 speech recognition dataset AR"
6
+ _HOMEPAGE = "https://arabicspeech.org/mgb2/"
7
+ _LICENSE = "MGB-2 License agreement"
8
+ _CITATION = """@misc{https://doi.org/10.48550/arxiv.1609.05625,
9
+ doi = {10.48550/ARXIV.1609.05625},
10
+
11
+ url = {https://arxiv.org/abs/1609.05625},
12
+
13
+ author = {Ali, Ahmed and Bell, Peter and Glass, James and Messaoui, Yacine and Mubarak, Hamdy and Renals, Steve and Zhang, Yifan},
14
+
15
+ keywords = {Computation and Language (cs.CL), FOS: Computer and information sciences, FOS: Computer and information sciences},
16
+
17
+ title = {The MGB-2 Challenge: Arabic Multi-Dialect Broadcast Media Recognition},
18
+
19
+ publisher = {arXiv},
20
+
21
+ year = {2016},
22
+
23
+ copyright = {arXiv.org perpetual, non-exclusive license}
24
+ }
25
+ """
26
+ _DATA_ARCHIVE_ROOT = "archives/"
27
+ _DATA_URL = {
28
+ "test": _DATA_ARCHIVE_ROOT + "mgb2_wav.test.tar.gz",
29
+ "dev": _DATA_ARCHIVE_ROOT + "mgb2_wav.dev.tar.gz",
30
+ "train": [_DATA_ARCHIVE_ROOT + f"mgb2_wav_{x}.train.tar.gz" for x in range(48)], # we have 48 archives
31
+ }
32
+ _TEXT_URL = {
33
+ "test": _DATA_ARCHIVE_ROOT + "mgb2_txt.test.tar.gz",
34
+ "dev": _DATA_ARCHIVE_ROOT + "mgb2_txt.dev.tar.gz",
35
+ "train": _DATA_ARCHIVE_ROOT + "mgb2_txt.train.tar.gz",
36
+ }
37
+
38
+ class MGDB2Dataset(datasets.GeneratorBasedBuilder):
39
+ def _info(self):
40
+ return datasets.DatasetInfo(
41
+ description=_DESCRIPTION,
42
+ features=datasets.Features(
43
+ {
44
+ "path": datasets.Value("string"),
45
+ "audio": datasets.Audio(sampling_rate=16_000),
46
+ "text": datasets.Value("string"),
47
+ }
48
+ ),
49
+ supervised_keys=None,
50
+ homepage=_HOMEPAGE,
51
+ license=_LICENSE,
52
+ citation=_CITATION,
53
+ )
54
+
55
+ def _split_generators(self, dl_manager):
56
+ wav_archive = dl_manager.download(_DATA_URL)
57
+ txt_archive = dl_manager.download(_TEXT_URL)
58
+ test_dir = "dataset/test"
59
+ dev_dir = "dataset/dev"
60
+ train_dir = "dataset/train"
61
+
62
+ if dl_manager.is_streaming:
63
+
64
+ return [
65
+ datasets.SplitGenerator(
66
+ name=datasets.Split.TEST,
67
+ gen_kwargs={
68
+ "path_to_txt": test_dir + "/txt",
69
+ "path_to_wav": test_dir + "/wav",
70
+ "wav_files": [dl_manager.iter_archive(wav_archive['test'])],
71
+ "txt_files": dl_manager.iter_archive(txt_archive['test']),
72
+ },
73
+ ),
74
+ datasets.SplitGenerator(
75
+ name=datasets.Split.VALIDATION,
76
+ gen_kwargs={
77
+ "path_to_txt": dev_dir + "/txt",
78
+ "path_to_wav": dev_dir + "/wav",
79
+ "wav_files": [dl_manager.iter_archive(wav_archive['dev'])],
80
+ "txt_files": dl_manager.iter_archive(txt_archive['dev']),
81
+ },
82
+ ),
83
+ datasets.SplitGenerator(
84
+ name=datasets.Split.TRAIN,
85
+ gen_kwargs={
86
+ "path_to_txt": train_dir + "/txt",
87
+ "path_to_wav": train_dir + "/wav",
88
+ "wav_files": [dl_manager.iter_archive(a) for a in wav_archive['train']],
89
+ "txt_files": dl_manager.iter_archive(txt_archive['train']),
90
+ },
91
+ ),
92
+ ]
93
+ else:
94
+ return [
95
+ datasets.SplitGenerator(
96
+ name=datasets.Split.TEST,
97
+ gen_kwargs={
98
+ "path_to_txt": test_dir + "/txt",
99
+ "path_to_wav": test_dir + "/wav",
100
+ "wav_files": [dl_manager.extract(wav_archive['test'])],
101
+ "txt_files": dl_manager.extract(txt_archive['test']),
102
+ },
103
+ ),
104
+ datasets.SplitGenerator(
105
+ name=datasets.Split.VALIDATION,
106
+ gen_kwargs={
107
+ "path_to_txt": dev_dir + "/txt",
108
+ "path_to_wav": dev_dir + "/wav",
109
+ "wav_files": [dl_manager.extract(wav_archive['dev'])],
110
+ "txt_files": dl_manager.extract(txt_archive['dev']),
111
+ },
112
+ ),
113
+ datasets.SplitGenerator(
114
+ name=datasets.Split.TRAIN,
115
+ gen_kwargs={
116
+ "path_to_txt": train_dir + "/txt",
117
+ "path_to_wav": train_dir + "/wav",
118
+ "wav_files": [dl_manager.extract(a) for a in wav_archive['train']],
119
+ "txt_files": dl_manager.extract(txt_archive['train']),
120
+ },
121
+ ),
122
+ ]
123
+
124
+
125
+
126
+ def _generate_examples(self, path_to_txt, path_to_wav, wav_files, txt_files):
127
+ """
128
+ This assumes that the text directory alphabetically precedes the wav dir
129
+ The file names for wav and text seem to match and are unique
130
+ We can use them for the dictionary matching them
131
+ """
132
+ examples = {}
133
+ id_ = 0
134
+ # need to prepare the transcript - wave map
135
+ for item in txt_files:
136
+ if type(item) is tuple:
137
+ # iter_archive will return path and file
138
+ path, f = item
139
+ txt = f.read().decode(encoding="utf-8").strip()
140
+ else:
141
+ # extract will return path only
142
+ path = item
143
+ with open(path, encoding="utf-8") as f:
144
+ txt = f.read().strip()
145
+
146
+ if path.find(path_to_txt) > -1:
147
+ # construct the wav path
148
+ # which is used as an identifier
149
+ wav_path = os.path.split(path)[1].replace("_utf8", "").replace(".txt", ".wav").strip()
150
+
151
+ examples[wav_path] = {
152
+ "text": txt,
153
+ "path": wav_path,
154
+ }
155
+
156
+ for wf in wav_files:
157
+ for item in wf:
158
+ if type(item) is tuple:
159
+ path, f = item
160
+ wav_data = f.read()
161
+ else:
162
+ path = item
163
+ with open(path, "rb") as f:
164
+ wav_data = f.read()
165
+ if path.find(path_to_wav) > -1:
166
+ wav_path = os.path.split(path)[1].strip()
167
+ audio = {"path": path, "bytes": wav_data}
168
+ yield id_, {**examples[wav_path], "audio": audio}
169
+ id_ += 1
.ipynb_checkpoints/run_mgb2-checkpoint.sh ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ python run_speech_recognition_seq2seq_mixed_mgb2-cv1.py \
2
+ --model_name_or_path="openai/whisper-small" \
3
+ --dataset_name="arbml/mgb2_speech" \
4
+ --dataset_config_name="ar" \
5
+ --language="Arabic" \
6
+ --train_split_name="train" \
7
+ --eval_split_name="test" \
8
+ --model_index_name="Whisper Small Arabic" \
9
+ --max_steps="5000" \
10
+ --output_dir="./" \
11
+ --per_device_train_batch_size="64" \
12
+ --per_device_eval_batch_size="8" \
13
+ --logging_steps="25" \
14
+ --learning_rate="1e-5" \
15
+ --warmup_steps="500" \
16
+ --evaluation_strategy="steps" \
17
+ --eval_steps="1000" \
18
+ --save_strategy="steps" \
19
+ --save_steps="1000" \
20
+ --generation_max_length="225" \
21
+ --length_column_name="input_length" \
22
+ --max_duration_in_seconds="30" \
23
+ --text_column_name="sentence" \
24
+ --freeze_feature_encoder="False" \
25
+ --report_to="tensorboard" \
26
+ --metric_for_best_model="wer" \
27
+ --greater_is_better="False" \
28
+ --load_best_model_at_end \
29
+ --gradient_checkpointing \
30
+ --fp16 \
31
+ --overwrite_output_dir \
32
+ --optim="adamw_bnb_8bit" \
33
+ --do_train \
34
+ --do_eval \
35
+ --predict_with_generate \
36
+ --do_normalize_eval \
37
+ --use_auth_token \
38
+ --push_to_hub
.ipynb_checkpoints/run_speech_recognition_seq2seq_mixed_mgb2-checkpoint.py ADDED
@@ -0,0 +1,748 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # coding=utf-8
3
+ # Copyright 2022 The HuggingFace Team. All rights reserved.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ """
17
+ Fine-tuning the library models for sequence to sequence speech recognition
18
+ with 🤗 Datasets' streaming mode.
19
+ """
20
+ # You can also adapt this script for your own sequence to sequence speech
21
+ # recognition task. Pointers for this are left as comments.
22
+
23
+ import logging
24
+ import os
25
+ import sys
26
+ from dataclasses import dataclass, field
27
+ from typing import Any, Dict, List, Optional, Union
28
+
29
+ import datasets
30
+ import torch
31
+ from datasets import DatasetDict, IterableDatasetDict, interleave_datasets, load_dataset
32
+ from torch.utils.data import IterableDataset
33
+
34
+ import evaluate
35
+ import transformers
36
+ from transformers import (
37
+ AutoConfig,
38
+ AutoFeatureExtractor,
39
+ AutoModelForSpeechSeq2Seq,
40
+ AutoProcessor,
41
+ AutoTokenizer,
42
+ HfArgumentParser,
43
+ Seq2SeqTrainer,
44
+ Seq2SeqTrainingArguments,
45
+ TrainerCallback,
46
+ set_seed,
47
+ )
48
+ from transformers.models.whisper.english_normalizer import BasicTextNormalizer
49
+ from transformers.trainer_pt_utils import IterableDatasetShard
50
+ from transformers.trainer_utils import get_last_checkpoint, is_main_process
51
+ from transformers.utils import check_min_version, send_example_telemetry
52
+ from transformers.utils.versions import require_version
53
+
54
+
55
+ # Will error if the minimal version of Transformers is not installed. Remove at your own risks.
56
+ check_min_version("4.25.0.dev0")
57
+
58
+ require_version(
59
+ "datasets>=1.18.2",
60
+ "To fix: pip install -r examples/pytorch/speech-recognition/requirements.txt",
61
+ )
62
+
63
+ logger = logging.getLogger(__name__)
64
+
65
+
66
+ @dataclass
67
+ class ModelArguments:
68
+ """
69
+ Arguments pertaining to which model/config/tokenizer we are going to fine-tune from.
70
+ """
71
+
72
+ model_name_or_path: str = field(
73
+ metadata={
74
+ "help": "Path to pretrained model or model identifier from huggingface.co/models"
75
+ }
76
+ )
77
+ config_name: Optional[str] = field(
78
+ default=None,
79
+ metadata={
80
+ "help": "Pretrained config name or path if not the same as model_name"
81
+ },
82
+ )
83
+ tokenizer_name: Optional[str] = field(
84
+ default=None,
85
+ metadata={
86
+ "help": "Pretrained tokenizer name or path if not the same as model_name"
87
+ },
88
+ )
89
+ feature_extractor_name: Optional[str] = field(
90
+ default=None,
91
+ metadata={
92
+ "help": "feature extractor name or path if not the same as model_name"
93
+ },
94
+ )
95
+ cache_dir: Optional[str] = field(
96
+ default=None,
97
+ metadata={
98
+ "help": "Where to store the pretrained models downloaded from huggingface.co"
99
+ },
100
+ )
101
+ use_fast_tokenizer: bool = field(
102
+ default=True,
103
+ metadata={
104
+ "help": "Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."
105
+ },
106
+ )
107
+ model_revision: str = field(
108
+ default="main",
109
+ metadata={
110
+ "help": "The specific model version to use (can be a branch name, tag name or commit id)."
111
+ },
112
+ )
113
+ use_auth_token: bool = field(
114
+ default=False,
115
+ metadata={
116
+ "help": (
117
+ "Will use the token generated when running `huggingface-cli login` (necessary to use this script "
118
+ "with private models)."
119
+ )
120
+ },
121
+ )
122
+ freeze_feature_encoder: bool = field(
123
+ default=True,
124
+ metadata={"help": "Whether to freeze the feature encoder layers of the model."},
125
+ )
126
+ freeze_encoder: bool = field(
127
+ default=False,
128
+ metadata={"help": "Whether to freeze the entire encoder of the seq2seq model."},
129
+ )
130
+ forced_decoder_ids: List[List[int]] = field(
131
+ default=None,
132
+ metadata={
133
+ "help": (
134
+ "A list of pairs of integers which indicates a mapping from generation indices to token indices "
135
+ "that will be forced before sampling. For example, [[0, 123]] means the first generated token "
136
+ "will always be a token of index 123."
137
+ )
138
+ },
139
+ )
140
+ suppress_tokens: List[int] = field(
141
+ default=None,
142
+ metadata={"help": "A list of tokens that will be suppressed at generation."},
143
+ )
144
+ model_index_name: str = field(
145
+ default=None, metadata={"help": "Pretty name for the model card."}
146
+ )
147
+
148
+
149
+ @dataclass
150
+ class DataTrainingArguments:
151
+ """
152
+ Arguments pertaining to what data we are going to input our model for training and eval.
153
+ """
154
+
155
+ dataset_name: str = field(
156
+ default=None,
157
+ metadata={"help": "The name of the dataset to use (via the datasets library)."},
158
+ )
159
+ dataset_config_name: Optional[str] = field(
160
+ default=None,
161
+ metadata={
162
+ "help": "The configuration name of the dataset to use (via the datasets library)."
163
+ },
164
+ )
165
+ text_column: Optional[str] = field(
166
+ default=None,
167
+ metadata={
168
+ "help": "The name of the column in the datasets containing the full texts (for summarization)."
169
+ },
170
+ )
171
+ max_train_samples: Optional[int] = field(
172
+ default=None,
173
+ metadata={
174
+ "help": (
175
+ "For debugging purposes or quicker training, truncate the number of training examples to this "
176
+ "value if set."
177
+ )
178
+ },
179
+ )
180
+ max_eval_samples: Optional[int] = field(
181
+ default=None,
182
+ metadata={
183
+ "help": (
184
+ "For debugging purposes or quicker training, truncate the number of evaluation examples to this "
185
+ "value if set."
186
+ )
187
+ },
188
+ )
189
+ audio_column_name: str = field(
190
+ default="audio",
191
+ metadata={
192
+ "help": "The name of the dataset column containing the audio data. Defaults to 'audio'"
193
+ },
194
+ )
195
+ text_column_name: str = field(
196
+ default="text",
197
+ metadata={
198
+ "help": "The name of the dataset column containing the text data. Defaults to 'text'"
199
+ },
200
+ )
201
+ max_duration_in_seconds: float = field(
202
+ default=20.0,
203
+ metadata={
204
+ "help": (
205
+ "Truncate audio files that are longer than `max_duration_in_seconds` seconds to"
206
+ " 'max_duration_in_seconds`"
207
+ )
208
+ },
209
+ )
210
+ min_duration_in_seconds: float = field(
211
+ default=0.0,
212
+ metadata={
213
+ "help": "Filter audio files that are shorter than `min_duration_in_seconds` seconds"
214
+ },
215
+ )
216
+ train_split_name: str = field(
217
+ default="train",
218
+ metadata={
219
+ "help": "The name of the training data set split to use (via the datasets library). Defaults to 'train'"
220
+ },
221
+ )
222
+ eval_split_name: str = field(
223
+ default="test",
224
+ metadata={
225
+ "help": "The name of the training data set split to use (via the datasets library). Defaults to 'train'"
226
+ },
227
+ )
228
+ do_lower_case: bool = field(
229
+ default=False,
230
+ metadata={"help": "Whether the target text should be lower cased."},
231
+ )
232
+ do_remove_punctuation: bool = field(
233
+ default=False,
234
+ metadata={"help": "Whether the target text should be striped of punctuation."},
235
+ )
236
+ do_normalize_eval: bool = field(
237
+ default=True,
238
+ metadata={
239
+ "help": "Whether to normalise the references and predictions in the eval WER calculation."
240
+ },
241
+ )
242
+ language: str = field(
243
+ default=None,
244
+ metadata={
245
+ "help": (
246
+ "Language for multilingual fine-tuning. This argument should be set for multilingual fine-tuning "
247
+ "only. For English speech recognition, it should be set to `None`."
248
+ )
249
+ },
250
+ )
251
+ task: str = field(
252
+ default="transcribe",
253
+ metadata={
254
+ "help": "Task, either `transcribe` for speech recognition or `translate` for speech translation."
255
+ },
256
+ )
257
+ shuffle_buffer_size: Optional[int] = field(
258
+ default=500,
259
+ metadata={
260
+ "help": (
261
+ "The number of streamed examples to download before shuffling them. The large the buffer, "
262
+ "the closer it is to real offline shuffling."
263
+ )
264
+ },
265
+ )
266
+ streaming: bool = field(
267
+ default=True,
268
+ metadata={
269
+ "help": "Whether to use streaming mode to load and pre-process the data."
270
+ },
271
+ )
272
+
273
+
274
+ @dataclass
275
+ class DataCollatorSpeechSeq2SeqWithPadding:
276
+ """
277
+ Data collator that will dynamically pad the inputs received.
278
+ Args:
279
+ processor ([`WhisperProcessor`])
280
+ The processor used for processing the data.
281
+ decoder_start_token_id (`int`)
282
+ The begin-of-sentence of the decoder.
283
+ """
284
+
285
+ processor: Any
286
+ decoder_start_token_id: int
287
+
288
+ def __call__(
289
+ self, features: List[Dict[str, Union[List[int], torch.Tensor]]]
290
+ ) -> Dict[str, torch.Tensor]:
291
+ # split inputs and labels since they have to be of different lengths and need
292
+ # different padding methods
293
+ model_input_name = self.processor.model_input_names[0]
294
+ input_features = [
295
+ {model_input_name: feature[model_input_name]} for feature in features
296
+ ]
297
+ label_features = [{"input_ids": feature["labels"]} for feature in features]
298
+
299
+ batch = self.processor.feature_extractor.pad(
300
+ input_features, return_tensors="pt"
301
+ )
302
+
303
+ labels_batch = self.processor.tokenizer.pad(label_features, return_tensors="pt")
304
+
305
+ # replace padding with -100 to ignore loss correctly
306
+ labels = labels_batch["input_ids"].masked_fill(
307
+ labels_batch.attention_mask.ne(1), -100
308
+ )
309
+
310
+ # if bos token is appended in previous tokenization step,
311
+ # cut bos token here as it's append later anyways
312
+ if (labels[:, 0] == self.decoder_start_token_id).all().cpu().item():
313
+ labels = labels[:, 1:]
314
+
315
+ batch["labels"] = labels
316
+
317
+ return batch
318
+
319
+
320
+ def load_maybe_streaming_dataset(
321
+ dataset_name, dataset_config_name, split="train", streaming=True, **kwargs
322
+ ):
323
+ """
324
+ Utility function to load a dataset in streaming mode. For datasets with multiple splits,
325
+ each split is loaded individually and then splits combined by taking alternating examples from
326
+ each (interleaving).
327
+ """
328
+ if "+" in split:
329
+ # load multiple splits separated by the `+` symbol with streaming mode
330
+ dataset_splits = [
331
+ load_dataset(
332
+ dataset_name,
333
+ dataset_config_name,
334
+ split=split_name,
335
+ streaming=streaming,
336
+ **kwargs,
337
+ )
338
+ for split_name in split.split("+")
339
+ ]
340
+ # interleave multiple splits to form one dataset
341
+ interleaved_dataset = interleave_datasets(dataset_splits)
342
+ return interleaved_dataset
343
+ else:
344
+ # load a single split *with* streaming mode
345
+ dataset = load_dataset(
346
+ dataset_name,
347
+ dataset_config_name,
348
+ split=split,
349
+ streaming=streaming,
350
+ **kwargs,
351
+ )
352
+ return dataset
353
+
354
+
355
+ def main():
356
+ # 1. Parse input arguments
357
+ # See all possible arguments in src/transformers/training_args.py
358
+ # or by passing the --help flag to this script.
359
+ # We now keep distinct sets of args, for a cleaner separation of concerns.
360
+ parser = HfArgumentParser(
361
+ (ModelArguments, DataTrainingArguments, Seq2SeqTrainingArguments)
362
+ )
363
+
364
+ if len(sys.argv) == 2 and sys.argv[1].endswith(".json"):
365
+ # If we pass only one argument to the script and it's the path to a json file,
366
+ # let's parse it to get our arguments.
367
+ model_args, data_args, training_args = parser.parse_json_file(
368
+ json_file=os.path.abspath(sys.argv[1])
369
+ )
370
+ else:
371
+ model_args, data_args, training_args = parser.parse_args_into_dataclasses()
372
+
373
+ # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
374
+ # information sent is the one passed as arguments along with your Python/PyTorch versions.
375
+ send_example_telemetry(
376
+ "run_speech_recognition_seq2seq_streaming", model_args, data_args
377
+ )
378
+
379
+ # 2. Setup logging
380
+ logging.basicConfig(
381
+ format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
382
+ datefmt="%m/%d/%Y %H:%M:%S",
383
+ handlers=[logging.StreamHandler(sys.stdout)],
384
+ )
385
+ log_level = training_args.get_process_log_level()
386
+ logger.setLevel(log_level)
387
+ datasets.utils.logging.set_verbosity(log_level)
388
+ transformers.utils.logging.set_verbosity(log_level)
389
+ transformers.utils.logging.enable_default_handler()
390
+ transformers.utils.logging.enable_explicit_format()
391
+
392
+ logger.setLevel(
393
+ logging.INFO if is_main_process(training_args.local_rank) else logging.WARN
394
+ )
395
+
396
+ # Log on each process the small summary:
397
+ logger.warning(
398
+ f"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}"
399
+ f"distributed training: {bool(training_args.local_rank != -1)}, 16-bits training: {training_args.fp16}"
400
+ )
401
+ logger.info(f"Training/evaluation parameters {training_args}")
402
+
403
+ # Set the verbosity to info of the Transformers logger (on main process only):
404
+ if is_main_process(training_args.local_rank):
405
+ transformers.utils.logging.set_verbosity_info()
406
+ logger.info("Training/evaluation parameters %s", training_args)
407
+
408
+ # 3. Detecting last checkpoint and eventually continue from last checkpoint
409
+ last_checkpoint = None
410
+ if (
411
+ os.path.isdir(training_args.output_dir)
412
+ and training_args.do_train
413
+ and not training_args.overwrite_output_dir
414
+ ):
415
+ last_checkpoint = get_last_checkpoint(training_args.output_dir)
416
+ if last_checkpoint is None and len(os.listdir(training_args.output_dir)) > 0:
417
+ raise ValueError(
418
+ f"Output directory ({training_args.output_dir}) already exists and is not empty. "
419
+ "Use --overwrite_output_dir to overcome."
420
+ )
421
+ elif (
422
+ last_checkpoint is not None and training_args.resume_from_checkpoint is None
423
+ ):
424
+ logger.info(
425
+ f"Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change "
426
+ "the `--output_dir` or add `--overwrite_output_dir` to train from scratch."
427
+ )
428
+
429
+ # Set seed before initializing model.
430
+ set_seed(training_args.seed)
431
+
432
+ # 4. Load dataset
433
+ raw_datasets = IterableDatasetDict()
434
+
435
+ if training_args.do_train:
436
+ raw_datasets["train"] = load_maybe_streaming_dataset(
437
+ data_args.dataset_name,
438
+ data_args.dataset_config_name,
439
+ split=data_args.train_split_name,
440
+ streaming=True,
441
+ use_auth_token=True if model_args.use_auth_token else None,
442
+ )
443
+
444
+ if training_args.do_eval:
445
+ raw_datasets["eval"] = load_maybe_streaming_dataset(
446
+ "arbml/mgb3",
447
+ data_args.dataset_config_name,
448
+ split="train",
449
+ streaming=False,
450
+ use_auth_token=True if model_args.use_auth_token else None,
451
+ )
452
+
453
+ raw_datasets_features = list(next(iter(raw_datasets.values())).features.keys())
454
+
455
+ if data_args.audio_column_name not in raw_datasets_features:
456
+ raise ValueError(
457
+ f"--audio_column_name '{data_args.audio_column_name}' not found in dataset '{data_args.dataset_name}'. "
458
+ "Make sure to set `--audio_column_name` to the correct audio column - one of "
459
+ f"{', '.join(raw_datasets_features)}."
460
+ )
461
+
462
+ if data_args.text_column_name not in raw_datasets_features:
463
+ raise ValueError(
464
+ f"--text_column_name {data_args.text_column_name} not found in dataset '{data_args.dataset_name}'. "
465
+ "Make sure to set `--text_column_name` to the correct text column - one of "
466
+ f"{', '.join(raw_datasets_features)}."
467
+ )
468
+
469
+ # 5. Load pretrained model, tokenizer, and feature extractor
470
+ #
471
+ # Distributed training:
472
+ # The .from_pretrained methods guarantee that only one local process can concurrently
473
+ config = AutoConfig.from_pretrained(
474
+ model_args.config_name
475
+ if model_args.config_name
476
+ else model_args.model_name_or_path,
477
+ cache_dir=model_args.cache_dir,
478
+ revision=model_args.model_revision,
479
+ use_auth_token=True if model_args.use_auth_token else None,
480
+ )
481
+
482
+ config.update(
483
+ {
484
+ "forced_decoder_ids": model_args.forced_decoder_ids,
485
+ "suppress_tokens": model_args.suppress_tokens,
486
+ }
487
+ )
488
+
489
+ if training_args.gradient_checkpointing:
490
+ config.update({"use_cache": False})
491
+
492
+ feature_extractor = AutoFeatureExtractor.from_pretrained(
493
+ model_args.feature_extractor_name
494
+ if model_args.feature_extractor_name
495
+ else model_args.model_name_or_path,
496
+ cache_dir=model_args.cache_dir,
497
+ revision=model_args.model_revision,
498
+ use_auth_token=True if model_args.use_auth_token else None,
499
+ )
500
+ tokenizer = AutoTokenizer.from_pretrained(
501
+ model_args.tokenizer_name
502
+ if model_args.tokenizer_name
503
+ else model_args.model_name_or_path,
504
+ cache_dir=model_args.cache_dir,
505
+ use_fast=model_args.use_fast_tokenizer,
506
+ revision=model_args.model_revision,
507
+ use_auth_token=True if model_args.use_auth_token else None,
508
+ )
509
+ model = AutoModelForSpeechSeq2Seq.from_pretrained(
510
+ model_args.model_name_or_path,
511
+ config=config,
512
+ cache_dir=model_args.cache_dir,
513
+ revision=model_args.model_revision,
514
+ use_auth_token=True if model_args.use_auth_token else None,
515
+ )
516
+
517
+ if model.config.decoder_start_token_id is None:
518
+ raise ValueError(
519
+ "Make sure that `config.decoder_start_token_id` is correctly defined"
520
+ )
521
+
522
+ max_label_length = model.config.max_length
523
+
524
+ if model_args.freeze_feature_encoder:
525
+ model.freeze_feature_encoder()
526
+
527
+ if model_args.freeze_encoder:
528
+ model.freeze_encoder()
529
+ model.model.encoder.gradient_checkpointing = False
530
+
531
+ if data_args.language is not None:
532
+ # We only need to set the task id when the language is specified (i.e. in a multilingual setting)
533
+ tokenizer.set_prefix_tokens(language=data_args.language, task=data_args.task)
534
+
535
+ # 6. Resample speech dataset if necessary
536
+ dataset_sampling_rate = (
537
+ next(iter(raw_datasets.values()))
538
+ .features[data_args.audio_column_name]
539
+ .sampling_rate
540
+ )
541
+ if dataset_sampling_rate != feature_extractor.sampling_rate:
542
+ raw_datasets = raw_datasets.cast_column(
543
+ data_args.audio_column_name,
544
+ datasets.features.Audio(sampling_rate=feature_extractor.sampling_rate),
545
+ )
546
+
547
+ # 7. Preprocessing the datasets.
548
+ # We need to read the audio files as arrays and tokenize the targets.
549
+ max_input_length = (
550
+ data_args.max_duration_in_seconds * feature_extractor.sampling_rate
551
+ )
552
+ min_input_length = (
553
+ data_args.min_duration_in_seconds * feature_extractor.sampling_rate
554
+ )
555
+ audio_column_name = data_args.audio_column_name
556
+ text_column_name = data_args.text_column_name
557
+ model_input_name = feature_extractor.model_input_names[0]
558
+ do_lower_case = data_args.do_lower_case
559
+ do_remove_punctuation = data_args.do_remove_punctuation
560
+ normalizer = BasicTextNormalizer() # 'official' text normalizer from OpenAI
561
+
562
+ if data_args.max_train_samples is not None:
563
+ raw_datasets["train"] = raw_datasets["train"].take(data_args.max_train_samples)
564
+
565
+ if data_args.max_eval_samples is not None:
566
+ raw_datasets["eval"] = raw_datasets["eval"].select(
567
+ range(data_args.max_eval_samples)
568
+ )
569
+
570
+ def prepare_dataset(batch):
571
+ # process audio
572
+ sample = batch[audio_column_name]
573
+ inputs = feature_extractor(
574
+ sample["array"], sampling_rate=sample["sampling_rate"]
575
+ )
576
+ # process audio length
577
+ batch[model_input_name] = inputs.get(model_input_name)[0]
578
+ batch["input_length"] = len(sample["array"])
579
+
580
+ # process targets
581
+ input_str = (
582
+ batch[text_column_name].lower()
583
+ if do_lower_case
584
+ else batch[text_column_name]
585
+ )
586
+ if do_remove_punctuation:
587
+ input_str = normalizer(input_str).strip()
588
+ batch["labels"] = tokenizer(input_str).input_ids
589
+ return batch
590
+
591
+ with training_args.main_process_first(desc="dataset map pre-processing"):
592
+ vectorized_datasets = raw_datasets.map(
593
+ prepare_dataset,
594
+ remove_columns=raw_datasets_features,
595
+ ).with_format("torch")
596
+
597
+ if training_args.do_train:
598
+ vectorized_datasets["train"] = vectorized_datasets["train"].shuffle(
599
+ buffer_size=data_args.shuffle_buffer_size,
600
+ seed=training_args.seed,
601
+ )
602
+
603
+ # filter training data that is shorter than min_input_length or longer than
604
+ # max_input_length
605
+ def is_audio_in_length_range(length):
606
+ return min_input_length < length < max_input_length
607
+
608
+ vectorized_datasets["train"] = vectorized_datasets["train"].filter(
609
+ is_audio_in_length_range,
610
+ input_columns=["input_length"],
611
+ )
612
+
613
+ def filter_labels(labels):
614
+ """Filter label sequences longer than max length"""
615
+ return len(labels) < max_label_length
616
+
617
+ vectorized_datasets = vectorized_datasets.filter(
618
+ filter_labels, input_columns=["labels"]
619
+ )
620
+
621
+ # 8. Load Metric
622
+ metric = evaluate.load("wer")
623
+ do_normalize_eval = data_args.do_normalize_eval
624
+
625
+ def compute_metrics(pred):
626
+ pred_ids = pred.predictions
627
+
628
+ pred.label_ids[pred.label_ids == -100] = tokenizer.pad_token_id
629
+
630
+ pred_str = tokenizer.batch_decode(pred_ids, skip_special_tokens=True)
631
+ # we do not want to group tokens when computing the metrics
632
+ label_str = tokenizer.batch_decode(pred.label_ids, skip_special_tokens=True)
633
+
634
+ if do_normalize_eval:
635
+ pred_str = [normalizer(pred) for pred in pred_str]
636
+ label_str = [normalizer(label) for label in label_str]
637
+ # filtering step to only evaluate the samples that correspond to non-zero references:
638
+ pred_str = [
639
+ pred_str[i] for i in range(len(pred_str)) if len(label_str[i]) > 0
640
+ ]
641
+ label_str = [
642
+ label_str[i] for i in range(len(label_str)) if len(label_str[i]) > 0
643
+ ]
644
+
645
+ wer = 100 * metric.compute(predictions=pred_str, references=label_str)
646
+
647
+ return {"wer": wer}
648
+
649
+ # 9. Create a single speech processor
650
+ if is_main_process(training_args.local_rank):
651
+ # save feature extractor, tokenizer and config
652
+ feature_extractor.save_pretrained(training_args.output_dir)
653
+ tokenizer.save_pretrained(training_args.output_dir)
654
+ config.save_pretrained(training_args.output_dir)
655
+
656
+ processor = AutoProcessor.from_pretrained(training_args.output_dir)
657
+
658
+ # 10. Define data collator
659
+ data_collator = DataCollatorSpeechSeq2SeqWithPadding(
660
+ processor=processor,
661
+ decoder_start_token_id=model.config.decoder_start_token_id,
662
+ )
663
+
664
+ # 11. Configure Trainer
665
+ # Trainer callback to reinitialise and reshuffle the streamable datasets at the beginning of each epoch
666
+ # Only required for streaming: Trainer automatically shuffles non-streaming datasets
667
+ class ShuffleCallback(TrainerCallback):
668
+ def on_epoch_begin(self, args, state, control, train_dataloader, **kwargs):
669
+ if isinstance(train_dataloader.dataset, IterableDatasetShard):
670
+ pass # set_epoch() is handled by the Trainer
671
+ elif isinstance(train_dataloader.dataset, IterableDataset):
672
+ train_dataloader.dataset.set_epoch(train_dataloader.dataset._epoch + 1)
673
+
674
+ # Initialize Trainer
675
+ trainer = Seq2SeqTrainer(
676
+ model=model,
677
+ args=training_args,
678
+ train_dataset=vectorized_datasets["train"] if training_args.do_train else None,
679
+ eval_dataset=vectorized_datasets["eval"] if training_args.do_eval else None,
680
+ tokenizer=feature_extractor,
681
+ data_collator=data_collator,
682
+ compute_metrics=compute_metrics
683
+ if training_args.predict_with_generate
684
+ else None,
685
+ callbacks=[ShuffleCallback()],
686
+ )
687
+
688
+ # 12. Training
689
+ if training_args.do_train:
690
+ checkpoint = None
691
+ if training_args.resume_from_checkpoint is not None:
692
+ checkpoint = training_args.resume_from_checkpoint
693
+ elif last_checkpoint is not None:
694
+ checkpoint = last_checkpoint
695
+ train_result = trainer.train(resume_from_checkpoint=checkpoint)
696
+ trainer.save_model() # Saves the feature extractor too for easy upload
697
+
698
+ metrics = train_result.metrics
699
+ if data_args.max_train_samples:
700
+ metrics["train_samples"] = data_args.max_train_samples
701
+ trainer.log_metrics("train", metrics)
702
+ trainer.save_metrics("train", metrics)
703
+ trainer.save_state()
704
+
705
+ # 13. Evaluation
706
+ results = {}
707
+ if training_args.do_eval:
708
+ logger.info("*** Evaluate ***")
709
+ metrics = trainer.evaluate(
710
+ metric_key_prefix="eval",
711
+ max_length=training_args.generation_max_length,
712
+ num_beams=training_args.generation_num_beams,
713
+ )
714
+ if data_args.max_eval_samples:
715
+ metrics["eval_samples"] = data_args.max_eval_samples
716
+
717
+ trainer.log_metrics("eval", metrics)
718
+ trainer.save_metrics("eval", metrics)
719
+
720
+ # 14. Write Training Stats
721
+ kwargs = {
722
+ "finetuned_from": model_args.model_name_or_path,
723
+ "tasks": "automatic-speech-recognition",
724
+ "tags": "whisper-event",
725
+ }
726
+ if data_args.dataset_name is not None:
727
+ kwargs["dataset_tags"] = data_args.dataset_name
728
+ if data_args.dataset_config_name is not None:
729
+ kwargs[
730
+ "dataset"
731
+ ] = f"{data_args.dataset_name} {data_args.dataset_config_name}"
732
+ else:
733
+ kwargs["dataset"] = data_args.dataset_name
734
+ if "common_voice" in data_args.dataset_name:
735
+ kwargs["language"] = data_args.dataset_config_name[:2]
736
+ if model_args.model_index_name is not None:
737
+ kwargs["model_name"] = model_args.model_index_name
738
+
739
+ if training_args.push_to_hub:
740
+ trainer.push_to_hub(**kwargs)
741
+ else:
742
+ trainer.create_model_card(**kwargs)
743
+
744
+ return results
745
+
746
+
747
+ if __name__ == "__main__":
748
+ main()
.ipynb_checkpoints/run_speech_recognition_seq2seq_mixed_mgb2-cv1-checkpoint.py ADDED
@@ -0,0 +1,802 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # coding=utf-8
3
+ # Copyright 2022 The HuggingFace Team. All rights reserved.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ """
17
+ Fine-tuning the library models for sequence to sequence speech recognition
18
+ with 🤗 Datasets' streaming mode.
19
+ """
20
+ # You can also adapt this script for your own sequence to sequence speech
21
+ # recognition task. Pointers for this are left as comments.
22
+
23
+ import logging
24
+ import os
25
+ import sys
26
+ from dataclasses import dataclass, field
27
+ from typing import Any, Dict, List, Optional, Union
28
+
29
+ import datasets
30
+ import torch
31
+ from datasets import DatasetDict, IterableDatasetDict, interleave_datasets, load_dataset
32
+ from datasets import Audio, interleave_datasets, IterableDataset
33
+ from torch.utils.data import IterableDataset
34
+
35
+ import evaluate
36
+ import transformers
37
+ from transformers import (
38
+ AutoConfig,
39
+ AutoFeatureExtractor,
40
+ AutoModelForSpeechSeq2Seq,
41
+ AutoProcessor,
42
+ AutoTokenizer,
43
+ HfArgumentParser,
44
+ Seq2SeqTrainer,
45
+ Seq2SeqTrainingArguments,
46
+ TrainerCallback,
47
+ set_seed,
48
+ )
49
+ from transformers.models.whisper.english_normalizer import BasicTextNormalizer
50
+ from transformers.trainer_pt_utils import IterableDatasetShard
51
+ from transformers.trainer_utils import get_last_checkpoint, is_main_process
52
+ from transformers.utils import check_min_version, send_example_telemetry
53
+ from transformers.utils.versions import require_version
54
+
55
+
56
+ # Will error if the minimal version of Transformers is not installed. Remove at your own risks.
57
+ check_min_version("4.25.0.dev0")
58
+
59
+ require_version(
60
+ "datasets>=1.18.2",
61
+ "To fix: pip install -r examples/pytorch/speech-recognition/requirements.txt",
62
+ )
63
+
64
+ logger = logging.getLogger(__name__)
65
+
66
+
67
+ @dataclass
68
+ class ModelArguments:
69
+ """
70
+ Arguments pertaining to which model/config/tokenizer we are going to fine-tune from.
71
+ """
72
+
73
+ model_name_or_path: str = field(
74
+ metadata={
75
+ "help": "Path to pretrained model or model identifier from huggingface.co/models"
76
+ }
77
+ )
78
+ config_name: Optional[str] = field(
79
+ default=None,
80
+ metadata={
81
+ "help": "Pretrained config name or path if not the same as model_name"
82
+ },
83
+ )
84
+ tokenizer_name: Optional[str] = field(
85
+ default=None,
86
+ metadata={
87
+ "help": "Pretrained tokenizer name or path if not the same as model_name"
88
+ },
89
+ )
90
+ feature_extractor_name: Optional[str] = field(
91
+ default=None,
92
+ metadata={
93
+ "help": "feature extractor name or path if not the same as model_name"
94
+ },
95
+ )
96
+ cache_dir: Optional[str] = field(
97
+ default=None,
98
+ metadata={
99
+ "help": "Where to store the pretrained models downloaded from huggingface.co"
100
+ },
101
+ )
102
+ use_fast_tokenizer: bool = field(
103
+ default=True,
104
+ metadata={
105
+ "help": "Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."
106
+ },
107
+ )
108
+ model_revision: str = field(
109
+ default="main",
110
+ metadata={
111
+ "help": "The specific model version to use (can be a branch name, tag name or commit id)."
112
+ },
113
+ )
114
+ use_auth_token: bool = field(
115
+ default=False,
116
+ metadata={
117
+ "help": (
118
+ "Will use the token generated when running `huggingface-cli login` (necessary to use this script "
119
+ "with private models)."
120
+ )
121
+ },
122
+ )
123
+ freeze_feature_encoder: bool = field(
124
+ default=True,
125
+ metadata={"help": "Whether to freeze the feature encoder layers of the model."},
126
+ )
127
+ freeze_encoder: bool = field(
128
+ default=False,
129
+ metadata={"help": "Whether to freeze the entire encoder of the seq2seq model."},
130
+ )
131
+ forced_decoder_ids: List[List[int]] = field(
132
+ default=None,
133
+ metadata={
134
+ "help": (
135
+ "A list of pairs of integers which indicates a mapping from generation indices to token indices "
136
+ "that will be forced before sampling. For example, [[0, 123]] means the first generated token "
137
+ "will always be a token of index 123."
138
+ )
139
+ },
140
+ )
141
+ suppress_tokens: List[int] = field(
142
+ default=None,
143
+ metadata={"help": "A list of tokens that will be suppressed at generation."},
144
+ )
145
+ model_index_name: str = field(
146
+ default=None, metadata={"help": "Pretty name for the model card."}
147
+ )
148
+
149
+
150
+ @dataclass
151
+ class DataTrainingArguments:
152
+ """
153
+ Arguments pertaining to what data we are going to input our model for training and eval.
154
+ """
155
+
156
+ dataset_name: str = field(
157
+ default=None,
158
+ metadata={"help": "The name of the dataset to use (via the datasets library)."},
159
+ )
160
+ dataset_config_name: Optional[str] = field(
161
+ default=None,
162
+ metadata={
163
+ "help": "The configuration name of the dataset to use (via the datasets library)."
164
+ },
165
+ )
166
+ text_column: Optional[str] = field(
167
+ default=None,
168
+ metadata={
169
+ "help": "The name of the column in the datasets containing the full texts (for summarization)."
170
+ },
171
+ )
172
+ max_train_samples: Optional[int] = field(
173
+ default=None,
174
+ metadata={
175
+ "help": (
176
+ "For debugging purposes or quicker training, truncate the number of training examples to this "
177
+ "value if set."
178
+ )
179
+ },
180
+ )
181
+ max_eval_samples: Optional[int] = field(
182
+ default=None,
183
+ metadata={
184
+ "help": (
185
+ "For debugging purposes or quicker training, truncate the number of evaluation examples to this "
186
+ "value if set."
187
+ )
188
+ },
189
+ )
190
+ audio_column_name: str = field(
191
+ default="audio",
192
+ metadata={
193
+ "help": "The name of the dataset column containing the audio data. Defaults to 'audio'"
194
+ },
195
+ )
196
+ text_column_name: str = field(
197
+ default="text",
198
+ metadata={
199
+ "help": "The name of the dataset column containing the text data. Defaults to 'text'"
200
+ },
201
+ )
202
+ max_duration_in_seconds: float = field(
203
+ default=20.0,
204
+ metadata={
205
+ "help": (
206
+ "Truncate audio files that are longer than `max_duration_in_seconds` seconds to"
207
+ " 'max_duration_in_seconds`"
208
+ )
209
+ },
210
+ )
211
+ min_duration_in_seconds: float = field(
212
+ default=0.0,
213
+ metadata={
214
+ "help": "Filter audio files that are shorter than `min_duration_in_seconds` seconds"
215
+ },
216
+ )
217
+ train_split_name: str = field(
218
+ default="train",
219
+ metadata={
220
+ "help": "The name of the training data set split to use (via the datasets library). Defaults to 'train'"
221
+ },
222
+ )
223
+ eval_split_name: str = field(
224
+ default="test",
225
+ metadata={
226
+ "help": "The name of the training data set split to use (via the datasets library). Defaults to 'train'"
227
+ },
228
+ )
229
+ do_lower_case: bool = field(
230
+ default=False,
231
+ metadata={"help": "Whether the target text should be lower cased."},
232
+ )
233
+ do_remove_punctuation: bool = field(
234
+ default=False,
235
+ metadata={"help": "Whether the target text should be striped of punctuation."},
236
+ )
237
+ do_normalize_eval: bool = field(
238
+ default=True,
239
+ metadata={
240
+ "help": "Whether to normalise the references and predictions in the eval WER calculation."
241
+ },
242
+ )
243
+ language: str = field(
244
+ default=None,
245
+ metadata={
246
+ "help": (
247
+ "Language for multilingual fine-tuning. This argument should be set for multilingual fine-tuning "
248
+ "only. For English speech recognition, it should be set to `None`."
249
+ )
250
+ },
251
+ )
252
+ task: str = field(
253
+ default="transcribe",
254
+ metadata={
255
+ "help": "Task, either `transcribe` for speech recognition or `translate` for speech translation."
256
+ },
257
+ )
258
+ shuffle_buffer_size: Optional[int] = field(
259
+ default=500,
260
+ metadata={
261
+ "help": (
262
+ "The number of streamed examples to download before shuffling them. The large the buffer, "
263
+ "the closer it is to real offline shuffling."
264
+ )
265
+ },
266
+ )
267
+ streaming: bool = field(
268
+ default=True,
269
+ metadata={
270
+ "help": "Whether to use streaming mode to load and pre-process the data."
271
+ },
272
+ )
273
+
274
+
275
+ @dataclass
276
+ class DataCollatorSpeechSeq2SeqWithPadding:
277
+ """
278
+ Data collator that will dynamically pad the inputs received.
279
+ Args:
280
+ processor ([`WhisperProcessor`])
281
+ The processor used for processing the data.
282
+ decoder_start_token_id (`int`)
283
+ The begin-of-sentence of the decoder.
284
+ """
285
+
286
+ processor: Any
287
+ decoder_start_token_id: int
288
+
289
+ def __call__(
290
+ self, features: List[Dict[str, Union[List[int], torch.Tensor]]]
291
+ ) -> Dict[str, torch.Tensor]:
292
+ # split inputs and labels since they have to be of different lengths and need
293
+ # different padding methods
294
+ model_input_name = self.processor.model_input_names[0]
295
+ input_features = [
296
+ {model_input_name: feature[model_input_name]} for feature in features
297
+ ]
298
+ label_features = [{"input_ids": feature["labels"]} for feature in features]
299
+
300
+ batch = self.processor.feature_extractor.pad(
301
+ input_features, return_tensors="pt"
302
+ )
303
+
304
+ labels_batch = self.processor.tokenizer.pad(label_features, return_tensors="pt")
305
+
306
+ # replace padding with -100 to ignore loss correctly
307
+ labels = labels_batch["input_ids"].masked_fill(
308
+ labels_batch.attention_mask.ne(1), -100
309
+ )
310
+
311
+ # if bos token is appended in previous tokenization step,
312
+ # cut bos token here as it's append later anyways
313
+ if (labels[:, 0] == self.decoder_start_token_id).all().cpu().item():
314
+ labels = labels[:, 1:]
315
+
316
+ batch["labels"] = labels
317
+
318
+ return batch
319
+
320
+
321
+ def load_maybe_streaming_dataset(
322
+ dataset_name, dataset_config_name, split="train", streaming=True, **kwargs
323
+ ):
324
+ """
325
+ Utility function to load a dataset in streaming mode. For datasets with multiple splits,
326
+ each split is loaded individually and then splits combined by taking alternating examples from
327
+ each (interleaving).
328
+ """
329
+ if "+" in split:
330
+ # load multiple splits separated by the `+` symbol with streaming mode
331
+ dataset_splits = [
332
+ load_dataset(
333
+ dataset_name,
334
+ dataset_config_name,
335
+ split=split_name,
336
+ streaming=streaming,
337
+ **kwargs,
338
+ )
339
+ for split_name in split.split("+")
340
+ ]
341
+ # interleave multiple splits to form one dataset
342
+ interleaved_dataset = interleave_datasets(dataset_splits)
343
+ return interleaved_dataset
344
+ else:
345
+ # load a single split *with* streaming mode
346
+ dataset = load_dataset(
347
+ dataset_name,
348
+ dataset_config_name,
349
+ split=split,
350
+ streaming=streaming,
351
+ **kwargs,
352
+ )
353
+ return dataset
354
+
355
+ def load_multiple_streaming_datasets(
356
+ dataset_names: List,
357
+ dataset_config_names: List,
358
+ splits: Optional[List] = None,
359
+ text_column_names: Optional[List] = None,
360
+ sampling_rate: Optional[int] = 16000,
361
+ stopping_strategy: Optional[str] = "first_exhausted",
362
+ **kwargs
363
+ ) -> IterableDataset:
364
+
365
+ if len(dataset_names) != len(dataset_config_names):
366
+ raise ValueError(
367
+ f"Ensure one config is passed for each dataset, got {len(dataset_names)} datasets and"
368
+ f" {len(dataset_config_names)} configs."
369
+ )
370
+
371
+ if splits is not None and len(splits) != len(dataset_names):
372
+ raise ValueError(
373
+ f"Ensure one split is passed for each dataset, got {len(dataset_names)} datasets and {len(splits)} splits."
374
+ )
375
+
376
+ if text_column_names is not None and len(text_column_names) != len(dataset_names):
377
+ raise ValueError(
378
+ f"Ensure one text column name is passed for each dataset, got {len(dataset_names)} datasets and"
379
+ f" {len(text_column_names)} text column names."
380
+ )
381
+
382
+ splits = splits if splits is not None else ["train" for i in range(len(dataset_names))]
383
+ text_column_names = (
384
+ text_column_names if text_column_names is not None else ["text" for i in range(len(dataset_names))]
385
+ )
386
+
387
+ all_datasets = []
388
+ # iterate over the datasets we want to interleave
389
+ for i, dataset_name in enumerate(dataset_names):
390
+ dataset = load_dataset(dataset_name, dataset_config_names[i], split=splits[i], streaming=True, **kwargs)
391
+ print(dataset)
392
+ # resample to specified sampling rate
393
+ dataset = dataset.cast_column("audio", Audio(sampling_rate))
394
+ # normalise columns to ["audio", "sentence"]
395
+ if text_column_names[i] != "sentence":
396
+ dataset = dataset.rename_column(text_column_names[i], "sentence")
397
+ dataset = dataset.remove_columns(set(dataset.features.keys()) - set(["audio", "sentence"]))
398
+ all_datasets.append(dataset)
399
+ print("DATASET:",dataset.features.keys())
400
+ interleaved_dataset = interleave_datasets(all_datasets, stopping_strategy=stopping_strategy)
401
+ return interleaved_dataset
402
+
403
+
404
+ def main():
405
+ # 1. Parse input arguments
406
+ # See all possible arguments in src/transformers/training_args.py
407
+ # or by passing the --help flag to this script.
408
+ # We now keep distinct sets of args, for a cleaner separation of concerns.
409
+ parser = HfArgumentParser(
410
+ (ModelArguments, DataTrainingArguments, Seq2SeqTrainingArguments)
411
+ )
412
+
413
+ if len(sys.argv) == 2 and sys.argv[1].endswith(".json"):
414
+ # If we pass only one argument to the script and it's the path to a json file,
415
+ # let's parse it to get our arguments.
416
+ model_args, data_args, training_args = parser.parse_json_file(
417
+ json_file=os.path.abspath(sys.argv[1])
418
+ )
419
+ else:
420
+ model_args, data_args, training_args = parser.parse_args_into_dataclasses()
421
+
422
+ # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
423
+ # information sent is the one passed as arguments along with your Python/PyTorch versions.
424
+ send_example_telemetry(
425
+ "run_speech_recognition_seq2seq_streaming", model_args, data_args
426
+ )
427
+
428
+ # 2. Setup logging
429
+ logging.basicConfig(
430
+ format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
431
+ datefmt="%m/%d/%Y %H:%M:%S",
432
+ handlers=[logging.StreamHandler(sys.stdout)],
433
+ )
434
+ log_level = training_args.get_process_log_level()
435
+ logger.setLevel(log_level)
436
+ datasets.utils.logging.set_verbosity(log_level)
437
+ transformers.utils.logging.set_verbosity(log_level)
438
+ transformers.utils.logging.enable_default_handler()
439
+ transformers.utils.logging.enable_explicit_format()
440
+
441
+ logger.setLevel(
442
+ logging.INFO if is_main_process(training_args.local_rank) else logging.WARN
443
+ )
444
+
445
+ # Log on each process the small summary:
446
+ logger.warning(
447
+ f"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}"
448
+ f"distributed training: {bool(training_args.local_rank != -1)}, 16-bits training: {training_args.fp16}"
449
+ )
450
+ logger.info(f"Training/evaluation parameters {training_args}")
451
+
452
+ # Set the verbosity to info of the Transformers logger (on main process only):
453
+ if is_main_process(training_args.local_rank):
454
+ transformers.utils.logging.set_verbosity_info()
455
+ logger.info("Training/evaluation parameters %s", training_args)
456
+
457
+ # 3. Detecting last checkpoint and eventually continue from last checkpoint
458
+ last_checkpoint = None
459
+ if (
460
+ os.path.isdir(training_args.output_dir)
461
+ and training_args.do_train
462
+ and not training_args.overwrite_output_dir
463
+ ):
464
+ last_checkpoint = get_last_checkpoint(training_args.output_dir)
465
+ if last_checkpoint is None and len(os.listdir(training_args.output_dir)) > 0:
466
+ raise ValueError(
467
+ f"Output directory ({training_args.output_dir}) already exists and is not empty. "
468
+ "Use --overwrite_output_dir to overcome."
469
+ )
470
+ elif (
471
+ last_checkpoint is not None and training_args.resume_from_checkpoint is None
472
+ ):
473
+ logger.info(
474
+ f"Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change "
475
+ "the `--output_dir` or add `--overwrite_output_dir` to train from scratch."
476
+ )
477
+
478
+ # Set seed before initializing model.
479
+ set_seed(training_args.seed)
480
+
481
+ # 4. Load dataset
482
+ raw_datasets = IterableDatasetDict()
483
+
484
+ dataset_names = ["mozilla-foundation/common_voice_11_0", "arbml/mgb2_speech", ]
485
+ dataset_config_names = ["ar", "ar", ]
486
+ text_column_names = ["sentence", "text",]
487
+
488
+ if training_args.do_train:
489
+ raw_datasets["train"] = load_multiple_streaming_datasets(
490
+ dataset_names,
491
+ dataset_config_names=dataset_config_names,
492
+ text_column_names=text_column_names,
493
+ splits=["train","train"],
494
+ use_auth_token=True
495
+ )
496
+
497
+ if training_args.do_eval:
498
+ raw_datasets["eval"] = load_multiple_streaming_datasets(
499
+ dataset_names,
500
+ dataset_config_names=dataset_config_names,
501
+ text_column_names=text_column_names,
502
+ splits=["validation","validation"],
503
+ use_auth_token=True
504
+ )
505
+
506
+ raw_datasets_features = list(next(iter(raw_datasets.values())).features.keys())
507
+
508
+ if data_args.audio_column_name not in raw_datasets_features:
509
+ raise ValueError(
510
+ f"--audio_column_name '{data_args.audio_column_name}' not found in dataset '{data_args.dataset_name}'. "
511
+ "Make sure to set `--audio_column_name` to the correct audio column - one of "
512
+ f"{', '.join(raw_datasets_features)}."
513
+ )
514
+
515
+ # if data_args.text_column_name not in raw_datasets_features:
516
+ # print("raw_datasets_features:",raw_datasets_features)
517
+ # raise ValueError(
518
+ # f"--text_column_name {data_args.text_column_name} not found in dataset '{data_args.dataset_name}'. "
519
+ # "Make sure to set `--text_column_name` to the correct text column - one of "
520
+ # f"{', '.join(raw_datasets_features)}."
521
+ # )
522
+
523
+ # 5. Load pretrained model, tokenizer, and feature extractor
524
+ #
525
+ # Distributed training:
526
+ # The .from_pretrained methods guarantee that only one local process can concurrently
527
+ config = AutoConfig.from_pretrained(
528
+ model_args.config_name
529
+ if model_args.config_name
530
+ else model_args.model_name_or_path,
531
+ cache_dir=model_args.cache_dir,
532
+ revision=model_args.model_revision,
533
+ use_auth_token=True if model_args.use_auth_token else None,
534
+ )
535
+
536
+ config.update(
537
+ {
538
+ "forced_decoder_ids": model_args.forced_decoder_ids,
539
+ "suppress_tokens": model_args.suppress_tokens,
540
+ }
541
+ )
542
+
543
+ if training_args.gradient_checkpointing:
544
+ config.update({"use_cache": False})
545
+
546
+ feature_extractor = AutoFeatureExtractor.from_pretrained(
547
+ model_args.feature_extractor_name
548
+ if model_args.feature_extractor_name
549
+ else model_args.model_name_or_path,
550
+ cache_dir=model_args.cache_dir,
551
+ revision=model_args.model_revision,
552
+ use_auth_token=True if model_args.use_auth_token else None,
553
+ )
554
+ tokenizer = AutoTokenizer.from_pretrained(
555
+ model_args.tokenizer_name
556
+ if model_args.tokenizer_name
557
+ else model_args.model_name_or_path,
558
+ cache_dir=model_args.cache_dir,
559
+ use_fast=model_args.use_fast_tokenizer,
560
+ revision=model_args.model_revision,
561
+ use_auth_token=True if model_args.use_auth_token else None,
562
+ )
563
+ model = AutoModelForSpeechSeq2Seq.from_pretrained(
564
+ model_args.model_name_or_path,
565
+ config=config,
566
+ cache_dir=model_args.cache_dir,
567
+ revision=model_args.model_revision,
568
+ use_auth_token=True if model_args.use_auth_token else None,
569
+ )
570
+
571
+ if model.config.decoder_start_token_id is None:
572
+ raise ValueError(
573
+ "Make sure that `config.decoder_start_token_id` is correctly defined"
574
+ )
575
+
576
+ max_label_length = model.config.max_length
577
+
578
+ if model_args.freeze_feature_encoder:
579
+ model.freeze_feature_encoder()
580
+
581
+ if model_args.freeze_encoder:
582
+ model.freeze_encoder()
583
+ model.model.encoder.gradient_checkpointing = False
584
+
585
+ if data_args.language is not None:
586
+ # We only need to set the task id when the language is specified (i.e. in a multilingual setting)
587
+ tokenizer.set_prefix_tokens(language=data_args.language, task=data_args.task)
588
+
589
+ # 6. Resample speech dataset if necessary
590
+ dataset_sampling_rate = (
591
+ next(iter(raw_datasets.values()))
592
+ .features[data_args.audio_column_name]
593
+ .sampling_rate
594
+ )
595
+ if dataset_sampling_rate != feature_extractor.sampling_rate:
596
+ raw_datasets = raw_datasets.cast_column(
597
+ data_args.audio_column_name,
598
+ datasets.features.Audio(sampling_rate=feature_extractor.sampling_rate),
599
+ )
600
+
601
+ # 7. Preprocessing the datasets.
602
+ # We need to read the audio files as arrays and tokenize the targets.
603
+ max_input_length = (
604
+ data_args.max_duration_in_seconds * feature_extractor.sampling_rate
605
+ )
606
+ min_input_length = (
607
+ data_args.min_duration_in_seconds * feature_extractor.sampling_rate
608
+ )
609
+ audio_column_name = data_args.audio_column_name
610
+ text_column_name = data_args.text_column_name
611
+ model_input_name = feature_extractor.model_input_names[0]
612
+ do_lower_case = data_args.do_lower_case
613
+ do_remove_punctuation = data_args.do_remove_punctuation
614
+ normalizer = BasicTextNormalizer() # 'official' text normalizer from OpenAI
615
+
616
+ if data_args.max_train_samples is not None:
617
+ raw_datasets["train"] = raw_datasets["train"].take(data_args.max_train_samples)
618
+
619
+ if data_args.max_eval_samples is not None:
620
+ raw_datasets["eval"] = raw_datasets["eval"].select(
621
+ range(data_args.max_eval_samples)
622
+ )
623
+
624
+ def prepare_dataset(batch):
625
+ # process audio
626
+ sample = batch[audio_column_name]
627
+ inputs = feature_extractor(
628
+ sample["array"], sampling_rate=sample["sampling_rate"]
629
+ )
630
+ # process audio length
631
+ batch[model_input_name] = inputs.get(model_input_name)[0]
632
+ batch["input_length"] = len(sample["array"])
633
+
634
+ # process targets
635
+ input_str = (
636
+ batch[text_column_name].lower()
637
+ if do_lower_case
638
+ else batch[text_column_name]
639
+ )
640
+ if do_remove_punctuation:
641
+ input_str = normalizer(input_str).strip()
642
+ batch["labels"] = tokenizer(input_str).input_ids
643
+ return batch
644
+
645
+ with training_args.main_process_first(desc="dataset map pre-processing"):
646
+ vectorized_datasets = raw_datasets.map(
647
+ prepare_dataset,
648
+ remove_columns=raw_datasets_features,
649
+ ).with_format("torch")
650
+
651
+ if training_args.do_train:
652
+ vectorized_datasets["train"] = vectorized_datasets["train"].shuffle(
653
+ buffer_size=data_args.shuffle_buffer_size,
654
+ seed=training_args.seed,
655
+ )
656
+
657
+ # filter training data that is shorter than min_input_length or longer than
658
+ # max_input_length
659
+ def is_audio_in_length_range(length):
660
+ return min_input_length < length < max_input_length
661
+
662
+ vectorized_datasets["train"] = vectorized_datasets["train"].filter(
663
+ is_audio_in_length_range,
664
+ input_columns=["input_length"],
665
+ )
666
+
667
+ def filter_labels(labels):
668
+ """Filter label sequences longer than max length"""
669
+ return len(labels) < max_label_length
670
+
671
+ vectorized_datasets = vectorized_datasets.filter(
672
+ filter_labels, input_columns=["labels"]
673
+ )
674
+
675
+ # 8. Load Metric
676
+ metric = evaluate.load("wer")
677
+ do_normalize_eval = data_args.do_normalize_eval
678
+
679
+ def compute_metrics(pred):
680
+ pred_ids = pred.predictions
681
+
682
+ pred.label_ids[pred.label_ids == -100] = tokenizer.pad_token_id
683
+
684
+ pred_str = tokenizer.batch_decode(pred_ids, skip_special_tokens=True)
685
+ # we do not want to group tokens when computing the metrics
686
+ label_str = tokenizer.batch_decode(pred.label_ids, skip_special_tokens=True)
687
+
688
+ if do_normalize_eval:
689
+ pred_str = [normalizer(pred) for pred in pred_str]
690
+ label_str = [normalizer(label) for label in label_str]
691
+ # filtering step to only evaluate the samples that correspond to non-zero references:
692
+ pred_str = [
693
+ pred_str[i] for i in range(len(pred_str)) if len(label_str[i]) > 0
694
+ ]
695
+ label_str = [
696
+ label_str[i] for i in range(len(label_str)) if len(label_str[i]) > 0
697
+ ]
698
+
699
+ wer = 100 * metric.compute(predictions=pred_str, references=label_str)
700
+
701
+ return {"wer": wer}
702
+
703
+ # 9. Create a single speech processor
704
+ if is_main_process(training_args.local_rank):
705
+ # save feature extractor, tokenizer and config
706
+ feature_extractor.save_pretrained(training_args.output_dir)
707
+ tokenizer.save_pretrained(training_args.output_dir)
708
+ config.save_pretrained(training_args.output_dir)
709
+
710
+ processor = AutoProcessor.from_pretrained(training_args.output_dir)
711
+
712
+ # 10. Define data collator
713
+ data_collator = DataCollatorSpeechSeq2SeqWithPadding(
714
+ processor=processor,
715
+ decoder_start_token_id=model.config.decoder_start_token_id,
716
+ )
717
+
718
+ # 11. Configure Trainer
719
+ # Trainer callback to reinitialise and reshuffle the streamable datasets at the beginning of each epoch
720
+ # Only required for streaming: Trainer automatically shuffles non-streaming datasets
721
+ class ShuffleCallback(TrainerCallback):
722
+ def on_epoch_begin(self, args, state, control, train_dataloader, **kwargs):
723
+ if isinstance(train_dataloader.dataset, IterableDatasetShard):
724
+ pass # set_epoch() is handled by the Trainer
725
+ elif isinstance(train_dataloader.dataset, IterableDataset):
726
+ train_dataloader.dataset.set_epoch(train_dataloader.dataset._epoch + 1)
727
+
728
+ # Initialize Trainer
729
+ trainer = Seq2SeqTrainer(
730
+ model=model,
731
+ args=training_args,
732
+ train_dataset=vectorized_datasets["train"] if training_args.do_train else None,
733
+ eval_dataset=vectorized_datasets["eval"] if training_args.do_eval else None,
734
+ tokenizer=feature_extractor,
735
+ data_collator=data_collator,
736
+ compute_metrics=compute_metrics
737
+ if training_args.predict_with_generate
738
+ else None,
739
+ callbacks=[ShuffleCallback()],
740
+ )
741
+
742
+ # 12. Training
743
+ if training_args.do_train:
744
+ checkpoint = None
745
+ if training_args.resume_from_checkpoint is not None:
746
+ checkpoint = training_args.resume_from_checkpoint
747
+ elif last_checkpoint is not None:
748
+ checkpoint = last_checkpoint
749
+ train_result = trainer.train(resume_from_checkpoint=checkpoint)
750
+ trainer.save_model() # Saves the feature extractor too for easy upload
751
+
752
+ metrics = train_result.metrics
753
+ if data_args.max_train_samples:
754
+ metrics["train_samples"] = data_args.max_train_samples
755
+ trainer.log_metrics("train", metrics)
756
+ trainer.save_metrics("train", metrics)
757
+ trainer.save_state()
758
+
759
+ # 13. Evaluation
760
+ results = {}
761
+ if training_args.do_eval:
762
+ logger.info("*** Evaluate ***")
763
+ metrics = trainer.evaluate(
764
+ metric_key_prefix="eval",
765
+ max_length=training_args.generation_max_length,
766
+ num_beams=training_args.generation_num_beams,
767
+ )
768
+ if data_args.max_eval_samples:
769
+ metrics["eval_samples"] = data_args.max_eval_samples
770
+
771
+ trainer.log_metrics("eval", metrics)
772
+ trainer.save_metrics("eval", metrics)
773
+
774
+ # 14. Write Training Stats
775
+ kwargs = {
776
+ "finetuned_from": model_args.model_name_or_path,
777
+ "tasks": "automatic-speech-recognition",
778
+ "tags": "whisper-event",
779
+ }
780
+ if data_args.dataset_name is not None:
781
+ kwargs["dataset_tags"] = data_args.dataset_name
782
+ if data_args.dataset_config_name is not None:
783
+ kwargs[
784
+ "dataset"
785
+ ] = f"{data_args.dataset_name} {data_args.dataset_config_name}"
786
+ else:
787
+ kwargs["dataset"] = data_args.dataset_name
788
+ if "common_voice" in data_args.dataset_name:
789
+ kwargs["language"] = data_args.dataset_config_name[:2]
790
+ if model_args.model_index_name is not None:
791
+ kwargs["model_name"] = model_args.model_index_name
792
+
793
+ if training_args.push_to_hub:
794
+ trainer.push_to_hub(**kwargs)
795
+ else:
796
+ trainer.create_model_card(**kwargs)
797
+
798
+ return results
799
+
800
+
801
+ if __name__ == "__main__":
802
+ main()
README.md ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # whisper_sprint
2
+
3
+ ## training
4
+
5
+ ```bash
6
+ git clone https://github.com/ARBML/whisper_sprint
7
+ cd whisper_sprint
8
+ ```
9
+
10
+ Then setup the enviornment
11
+
12
+ ```bash
13
+ bash setup_env.sh
14
+ ```
15
+
16
+ Then setup the libraries, this will install transofrmers, etc. and create a directory in the hub for training the model ...
17
+
18
+ ```bash
19
+ bash setup_libs.sh HF_USER_NAME MODEL_NAME
20
+ ```
21
+
22
+ After that, you can run training by
23
+
24
+ ```
25
+ cd MODEL_NAME
26
+ bash run_mgb2.sh
27
+ ```
28
+
29
+ You can also run with deepspeed wich allows running whisper-large v2 with batch size 32 on A100
30
+
31
+ ```
32
+ bash run_mgb2_deepspeed.sh
33
+ ```
34
+
35
+ ## Evaluation
36
+
37
+ ### Evaluation on Fleurs
38
+
39
+ ```
40
+ bash run_eval_fleurs.sh MODEL_NAME
41
+ ```
42
+
43
+ ### Evaluation on Common Voice 11
44
+
45
+ ```
46
+ bash run_eval_cv_11.sh MODEL_NAME
47
+ ```
48
+
49
+
50
+
51
+ evaluate on common voice 11
52
+
53
+ ```bash
54
+ bash run_eval_cv_11.sh HF_USER_NAME/MODEL_NAME
55
+ ```
56
+
57
+ evaluate on Fleurs
58
+
59
+ ```bash
60
+ bash run_eval_fleurs.sh HF_USER_NAME/MODEL_NAME
61
+ ```
62
+
63
+ ## Preparing the MGB2 data
64
+
65
+ While MGB2 dataset contains a richly transcribed speech dataset, the wav files were too lengthy to be used to train the whisper model. Therefore, we had to split the wave file and still maintain the correct correspondence with the transcribed text.
66
+
67
+ MGB2 provides and XML file corresponding to every wav file, which contains the transcribed sentences and the start and end time of each sentence in the recording. Using the `split_xml_mgb2.py`, we start with the xml file and split the lengthy wav files into smaller ones that are shorter than 30 seconds in length, as required to fine-tune whisper. The operation produced over 370K sentences with their corresponding wav files.
68
+
69
+ ## Hosting on HuggingFace (Privately)
70
+
71
+ To host mgb2 at HF, at least 3 things need to happen:
72
+
73
+ 1. Create the dataset repository on HF. This was created privately at arbml/mgb2_speech for the dataset
74
+ 2. Data must be hosted somewhere or uploaded to HF repo
75
+ 3. HF loading script must be written so the data can be integrated into the HF hub.
76
+
77
+
78
+ ### Uploading the data
79
+
80
+ The dataset was >100Gb in size. HF utilizes git lfs to host large files. However, git lfs has a max limit of 5gb size for any file. Uploading over 370K individual files was also not feasible and caused issues with git.
81
+ Therefore, the solution was to archive groups of wav files together into sequentially numbered archive files, such that the archive file is no bigger than 5GB. To achieve that, the wav files were grouped based on the first 2 letters of the file name. The naming scheme seems to use a base64 encoding. So, characters would be 0 to 9 or A to F. The files were grouped as follows:
82
+
83
+ | First 2 Letters | Archive Number |
84
+ |:-:|---|
85
+ | 00-05 | 0 |
86
+ | 06-09 | 1 |
87
+ | 0A-0F | 2 |
88
+ | 10-15 | 3 |
89
+ | 16-19 | 4 |
90
+ | 1A-1F | 5 |
91
+ | ... | ... |
92
+ | F0-F5 | 45 |
93
+ | F6-F9 | 46 |
94
+ | FA-FF | 47 |
95
+
96
+ Only the training data was split using this scheme, the test and validation data was smaller than 5GB when archived.
97
+
98
+ ### HF Data Loading Script
99
+
100
+ The loading script determines the features of the data based on split and selected configuration. We had test, dev, and train split with a single language configuration. Using the _generate_example function, the script is used by GH to correctly produce the associated transcript and wav files. The function works as follows:
101
+
102
+ 1. Go through all the entries in the archive containing the text transcripts and create a map where the name of the file (the 64base encoded one) is used as the key and the transcript at the value
103
+ 2. Iterate through all the wav files in all the archive, and for every wav file, get the corresponding transcript from the map constructed in previous step (using the file name) and yield the wav file, transcript, and path to the wav file
104
+
added_tokens.json ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "<|af|>": 50327,
3
+ "<|am|>": 50334,
4
+ "<|ar|>": 50272,
5
+ "<|as|>": 50350,
6
+ "<|az|>": 50304,
7
+ "<|ba|>": 50355,
8
+ "<|be|>": 50330,
9
+ "<|bg|>": 50292,
10
+ "<|bn|>": 50302,
11
+ "<|bo|>": 50347,
12
+ "<|br|>": 50309,
13
+ "<|bs|>": 50315,
14
+ "<|ca|>": 50270,
15
+ "<|cs|>": 50283,
16
+ "<|cy|>": 50297,
17
+ "<|da|>": 50285,
18
+ "<|de|>": 50261,
19
+ "<|el|>": 50281,
20
+ "<|endoftext|>": 50257,
21
+ "<|en|>": 50259,
22
+ "<|es|>": 50262,
23
+ "<|et|>": 50307,
24
+ "<|eu|>": 50310,
25
+ "<|fa|>": 50300,
26
+ "<|fi|>": 50277,
27
+ "<|fo|>": 50338,
28
+ "<|fr|>": 50265,
29
+ "<|gl|>": 50319,
30
+ "<|gu|>": 50333,
31
+ "<|haw|>": 50352,
32
+ "<|ha|>": 50354,
33
+ "<|hi|>": 50276,
34
+ "<|hr|>": 50291,
35
+ "<|ht|>": 50339,
36
+ "<|hu|>": 50286,
37
+ "<|hy|>": 50312,
38
+ "<|id|>": 50275,
39
+ "<|is|>": 50311,
40
+ "<|it|>": 50274,
41
+ "<|iw|>": 50279,
42
+ "<|ja|>": 50266,
43
+ "<|jw|>": 50356,
44
+ "<|ka|>": 50329,
45
+ "<|kk|>": 50316,
46
+ "<|km|>": 50323,
47
+ "<|kn|>": 50306,
48
+ "<|ko|>": 50264,
49
+ "<|la|>": 50294,
50
+ "<|lb|>": 50345,
51
+ "<|ln|>": 50353,
52
+ "<|lo|>": 50336,
53
+ "<|lt|>": 50293,
54
+ "<|lv|>": 50301,
55
+ "<|mg|>": 50349,
56
+ "<|mi|>": 50295,
57
+ "<|mk|>": 50308,
58
+ "<|ml|>": 50296,
59
+ "<|mn|>": 50314,
60
+ "<|mr|>": 50320,
61
+ "<|ms|>": 50282,
62
+ "<|mt|>": 50343,
63
+ "<|my|>": 50346,
64
+ "<|ne|>": 50313,
65
+ "<|nl|>": 50271,
66
+ "<|nn|>": 50342,
67
+ "<|nocaptions|>": 50362,
68
+ "<|notimestamps|>": 50363,
69
+ "<|no|>": 50288,
70
+ "<|oc|>": 50328,
71
+ "<|pa|>": 50321,
72
+ "<|pl|>": 50269,
73
+ "<|ps|>": 50340,
74
+ "<|pt|>": 50267,
75
+ "<|ro|>": 50284,
76
+ "<|ru|>": 50263,
77
+ "<|sa|>": 50344,
78
+ "<|sd|>": 50332,
79
+ "<|si|>": 50322,
80
+ "<|sk|>": 50298,
81
+ "<|sl|>": 50305,
82
+ "<|sn|>": 50324,
83
+ "<|so|>": 50326,
84
+ "<|sq|>": 50317,
85
+ "<|sr|>": 50303,
86
+ "<|startoflm|>": 50360,
87
+ "<|startofprev|>": 50361,
88
+ "<|startoftranscript|>": 50258,
89
+ "<|su|>": 50357,
90
+ "<|sv|>": 50273,
91
+ "<|sw|>": 50318,
92
+ "<|ta|>": 50287,
93
+ "<|te|>": 50299,
94
+ "<|tg|>": 50331,
95
+ "<|th|>": 50289,
96
+ "<|tk|>": 50341,
97
+ "<|tl|>": 50348,
98
+ "<|transcribe|>": 50359,
99
+ "<|translate|>": 50358,
100
+ "<|tr|>": 50268,
101
+ "<|tt|>": 50351,
102
+ "<|uk|>": 50280,
103
+ "<|ur|>": 50290,
104
+ "<|uz|>": 50337,
105
+ "<|vi|>": 50278,
106
+ "<|yi|>": 50335,
107
+ "<|yo|>": 50325,
108
+ "<|zh|>": 50260
109
+ }
all_results.json ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "epoch": 1.44,
3
+ "eval_loss": 0.9784936308860779,
4
+ "eval_runtime": 1959.8449,
5
+ "eval_samples_per_second": 2.885,
6
+ "eval_steps_per_second": 0.361,
7
+ "eval_wer": 20.95505699346784,
8
+ "train_loss": 0.2953554097175598,
9
+ "train_runtime": 94208.4118,
10
+ "train_samples_per_second": 6.793,
11
+ "train_steps_per_second": 0.106
12
+ }
bigram_count.txt ADDED
@@ -0,0 +1,3875 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ (('5', 'غ'), 1)
2
+ (('ً', 'ط'), 1)
3
+ (('ي', 'آ'), 1)
4
+ (('ّ', '!'), 1)
5
+ ((',', 'ه'), 1)
6
+ (('I', 'ه'), 1)
7
+ (('6', '\\'), 1)
8
+ (('7', 'ي'), 1)
9
+ (('ن', '7'), 1)
10
+ (('P', ','), 1)
11
+ (('m', 'G'), 1)
12
+ (('G', 'i'), 1)
13
+ (('M', 'V'), 1)
14
+ (('7', 'ه'), 1)
15
+ (('ف', '9'), 1)
16
+ (('ي', 'F'), 1)
17
+ (('5', 'M'), 1)
18
+ (('خ', '\\'), 1)
19
+ (('ر', '+'), 1)
20
+ (('م', '5'), 1)
21
+ (('ة', '4'), 1)
22
+ (('k', ','), 1)
23
+ (('خ', '!'), 1)
24
+ (('ِ', 'إ'), 1)
25
+ (('ـ', 'V'), 1)
26
+ (('2', 'س'), 1)
27
+ (('e', "'"), 1)
28
+ (('ـ', 'i'), 1)
29
+ (('ى', 'T'), 1)
30
+ (('s', 'أ'), 1)
31
+ (('r', 'ع'), 1)
32
+ (('ـ', 't'), 1)
33
+ (('ذ', '2'), 1)
34
+ ((',', '1'), 1)
35
+ (('7', 'ض'), 1)
36
+ (('ٍ', 'ر'), 1)
37
+ (('ل', 'C'), 1)
38
+ (('ي', 't'), 1)
39
+ (('S', 'K'), 1)
40
+ (('n', 'أ'), 1)
41
+ (('ز', 'ـ'), 1)
42
+ (('و', 'F'), 1)
43
+ (('<S>', '٥'), 1)
44
+ (('غ', '!'), 1)
45
+ (('ي', '9'), 1)
46
+ (('8', 'ح'), 1)
47
+ (('ا', '4'), 1)
48
+ (('ـ', 'X'), 1)
49
+ (('e', 'j'), 1)
50
+ (('ﻹ', 'ل'), 1)
51
+ (('S', 'Q'), 1)
52
+ (('Q', '<E>'), 1)
53
+ (('5', '؛'), 1)
54
+ (('أ', ','), 1)
55
+ (('س', ','), 1)
56
+ (('h', ','), 1)
57
+ (('ى', '9'), 1)
58
+ (('5', 'ا'), 1)
59
+ (('O', '2'), 1)
60
+ (('3', 'أ'), 1)
61
+ (('ٍ', 'خ'), 1)
62
+ (('9', 'ل'), 1)
63
+ (('ل', 'F'), 1)
64
+ (('ي', 'W'), 1)
65
+ (('I', 'X'), 1)
66
+ (('X', 'I'), 1)
67
+ (('ك', '1'), 1)
68
+ (('3', 'س'), 1)
69
+ (('1', 'م'), 1)
70
+ (('%', '9'), 1)
71
+ (('%', '3'), 1)
72
+ (('ى', 'B'), 1)
73
+ (('"', '3'), 1)
74
+ (('K', 'D'), 1)
75
+ (('L', 'T'), 1)
76
+ (('.', ','), 1)
77
+ (('T', 'y'), 1)
78
+ (('f', 'P'), 1)
79
+ (('0', 'غ'), 1)
80
+ (('J', 'b'), 1)
81
+ (('%', 'ه'), 1)
82
+ (('ل', 'r'), 1)
83
+ (('P', 'J'), 1)
84
+ (('ﻻ', 'ه'), 1)
85
+ (('ل', 'T'), 1)
86
+ (('3', 'و'), 1)
87
+ (('0', 'آ'), 1)
88
+ (('<S>', '﴿'), 1)
89
+ (('﴿', 'و'), 1)
90
+ (('َ', '﴾'), 1)
91
+ (('﴾', '<E>'), 1)
92
+ (('ـ', 'ض'), 1)
93
+ (('7', 'م'), 1)
94
+ (('%', 'و'), 1)
95
+ (('0', 'ض'), 1)
96
+ (('ر', 'ظ'), 1)
97
+ (('٦', '١'), 1)
98
+ (('ْ', 'ظ'), 1)
99
+ (('ة', 'p'), 1)
100
+ (('r', 'f'), 1)
101
+ (('L', 'K'), 1)
102
+ (('ج', 'ً'), 1)
103
+ (('ا', 'ى'), 1)
104
+ (('9', 'ا'), 1)
105
+ (('ٍ', 'ف'), 1)
106
+ (('ً', 'ؤ'), 1)
107
+ (('#', 'T'), 1)
108
+ (('‘', 'm'), 1)
109
+ (('ـ', 'U'), 1)
110
+ (('u', 'u'), 1)
111
+ (('O', 'v'), 1)
112
+ (('t', 'ع'), 1)
113
+ (('S', 'U'), 1)
114
+ (('L', 'B'), 1)
115
+ (('t', 'و'), 1)
116
+ (('K', 'O'), 1)
117
+ (('S', 'H'), 1)
118
+ (('K', 'C'), 1)
119
+ (('y', 'N'), 1)
120
+ (('d', 'م'), 1)
121
+ (('D', 'W'), 1)
122
+ (('ي', '5'), 1)
123
+ (('ث', 'C'), 1)
124
+ (('ٌ', 'ك'), 1)
125
+ (('%', '-'), 1)
126
+ (('S', 'R'), 1)
127
+ (('م', 'b'), 1)
128
+ (('a', "'"), 1)
129
+ (('V', 'R'), 1)
130
+ (('ى', 'َ'), 1)
131
+ (('٦', '٪'), 1)
132
+ (('<S>', '٧'), 1)
133
+ (('I', 'I'), 1)
134
+ (('ب', 'D'), 1)
135
+ (('t', '@'), 1)
136
+ (('@', 't'), 1)
137
+ (('ت', 'P'), 1)
138
+ (('C', 'D'), 1)
139
+ (('ُ', 'ٌ'), 1)
140
+ (('*', 'ش'), 1)
141
+ (('ـ', 'd'), 1)
142
+ (('g', 'ي'), 1)
143
+ (('c', 'C'), 1)
144
+ (('ـ', 'u'), 1)
145
+ (('t', 'ه'), 1)
146
+ (('B', 'G'), 1)
147
+ (('ـ', 'o'), 1)
148
+ (('r', 'و'), 1)
149
+ (('و', 'n'), 1)
150
+ (('؛', 'ً'), 1)
151
+ (('c', ','), 1)
152
+ (('د', 'آ'), 1)
153
+ (('ِ', 'ِ'), 1)
154
+ (('E', 'F'), 1)
155
+ (('6', 'آ'), 1)
156
+ (('C', 'V'), 1)
157
+ (('ح', '7'), 1)
158
+ (('G', 'B'), 1)
159
+ (('إ', 'ّ'), 1)
160
+ (('ن', '3'), 1)
161
+ (('ق', 'ئ'), 1)
162
+ (('1', 'ب'), 1)
163
+ (('-', ':'), 1)
164
+ (('،', '-'), 1)
165
+ (('%', '4'), 1)
166
+ (('ة', '|'), 1)
167
+ (('ـ', '٢'), 1)
168
+ (('٢', '٩'), 1)
169
+ (('ج', 'ص'), 1)
170
+ (('ة', 'ت'), 1)
171
+ (('آ', 'ء'), 1)
172
+ (('3', '+'), 1)
173
+ (('ث', 'ش'), 1)
174
+ (('w', 'b'), 1)
175
+ (('D', 'O'), 1)
176
+ (('W', 'N'), 1)
177
+ (('ﻻ', 'ّ'), 1)
178
+ (('،', "'"), 1)
179
+ (('<S>', 'ﺠ'), 1)
180
+ (('ﺠ', 'ﻌ'), 1)
181
+ (('ﻌ', 'ﻔ'), 1)
182
+ (('ﻔ', 'ﺎ'), 1)
183
+ (('ﺎ', 'ﺕ'), 1)
184
+ (('ﺕ', '<E>'), 1)
185
+ (('<S>', 'ﺯ'), 1)
186
+ (('ﺯ', 'ﺌ'), 1)
187
+ (('ﺌ', 'ﻴ'), 1)
188
+ (('ﻴ', 'ﻑ'), 1)
189
+ (('ﻑ', '<E>'), 1)
190
+ (('s', 'A'), 1)
191
+ (('#', 'C'), 1)
192
+ (('l', 'H'), 1)
193
+ (('l', 'S'), 1)
194
+ (('ا', 'f'), 1)
195
+ (('9', '\\'), 1)
196
+ (('s', 'و'), 1)
197
+ (('ً', 'د'), 1)
198
+ (('D', 'é'), 1)
199
+ (('é', 'g'), 1)
200
+ (('٧', '٢'), 1)
201
+ (('"', 'l'), 1)
202
+ (('8', 'و'), 1)
203
+ (('2', '='), 1)
204
+ (('=', '1'), 1)
205
+ (('ج', '!'), 1)
206
+ (('O', 'A'), 1)
207
+ (('E', 'y'), 1)
208
+ (('C', 'ا'), 1)
209
+ (('C', 'ل'), 1)
210
+ (('l', 'و'), 1)
211
+ (('C', 'ت'), 1)
212
+ (('A', 'خ'), 1)
213
+ (('ـ', 'h'), 1)
214
+ (('e', 'إ'), 1)
215
+ (('"', 'S'), 1)
216
+ (('و', 'ـ'), 1)
217
+ (('O', 'i'), 1)
218
+ (('<S>', '؟'), 1)
219
+ (('م', 'u'), 1)
220
+ (('ة', 'R'), 1)
221
+ (('ش', 'ز'), 1)
222
+ (('ﻹ', 'ف'), 1)
223
+ (('ح', 'أ'), 1)
224
+ (('ة', '5'), 1)
225
+ (('1', 'ي'), 1)
226
+ ((',', 'س'), 1)
227
+ (('T', '6'), 1)
228
+ (('K', 'G'), 1)
229
+ (('I', 'V'), 1)
230
+ (('،', '('), 1)
231
+ (('ا', 'i'), 1)
232
+ (('ِ', 'ؤ'), 1)
233
+ (('ه', 'c'), 1)
234
+ (('ﻻ', 'س'), 1)
235
+ (('ﻵ', 'ب'), 1)
236
+ (('K', ','), 1)
237
+ (('و', 'S'), 1)
238
+ (('2', 'ي'), 1)
239
+ (('ئ', '!'), 1)
240
+ (('ئ', '\\'), 1)
241
+ (('ا', 'n'), 1)
242
+ (('ي', '8'), 1)
243
+ (('I', 'd'), 1)
244
+ (('E', 'Q'), 1)
245
+ (('Q', 'A'), 1)
246
+ (('a', 'q'), 1)
247
+ (('q', 'i'), 1)
248
+ (('A', 'b'), 1)
249
+ (('*', '3'), 1)
250
+ (('*', '1'), 1)
251
+ (('s', '3'), 1)
252
+ (('J', 'N'), 1)
253
+ (('N', 'Z'), 1)
254
+ (('Z', '<E>'), 1)
255
+ (('ل', 'c'), 1)
256
+ (('o', 'q'), 1)
257
+ (('N', '1'), 1)
258
+ (('1', 'T'), 1)
259
+ (('ج', 'T'), 1)
260
+ (('ى', '4'), 1)
261
+ (('"', 'p'), 1)
262
+ (('،', ':'), 1)
263
+ (('0', 'ق'), 1)
264
+ (('"', 'H'), 1)
265
+ (('h', '\\'), 1)
266
+ (('H', 'Y'), 1)
267
+ (('R', 'L'), 1)
268
+ (('h', 'K'), 1)
269
+ (('K', 'u'), 1)
270
+ (('m', 'n'), 1)
271
+ (('ت', ';'), 1)
272
+ (('ٍ', 'د'), 1)
273
+ (('ٌ', 'س'), 1)
274
+ (('ٌ', 'ف'), 1)
275
+ (('ر', '|'), 1)
276
+ (('ب', '٦'), 1)
277
+ (('غ', '؛'), 1)
278
+ (('ة', '6'), 1)
279
+ (('ة', '3'), 1)
280
+ (('ة', '7'), 1)
281
+ (('ز', '!'), 1)
282
+ (('4', 'ع'), 1)
283
+ (('0', 'ص'), 1)
284
+ (('ُ', '\\'), 1)
285
+ (('ِ', 'C'), 1)
286
+ (('s', 'ف'), 1)
287
+ (('3', 'D'), 1)
288
+ (('@', 'm'), 1)
289
+ (('ن', 'N'), 1)
290
+ (('ب', 'N'), 1)
291
+ (('ى', 'I'), 1)
292
+ (('ى', 'R'), 1)
293
+ (('r', 'ا'), 1)
294
+ (('B', 'ف'), 1)
295
+ (('G', '2'), 1)
296
+ (('m', 'ه'), 1)
297
+ (('G', 'G'), 1)
298
+ (('d', 'v'), 1)
299
+ (('*', 'ك'), 1)
300
+ (('I', 'G'), 1)
301
+ (('H', 'T'), 1)
302
+ (('#', 'J'), 1)
303
+ (('s', 'F'), 1)
304
+ (('r', 'I'), 1)
305
+ (('U', 's'), 1)
306
+ (('D', 'ة'), 1)
307
+ (('<S>', 'é'), 1)
308
+ (('é', 'l'), 1)
309
+ (('m', 'é'), 1)
310
+ (('é', 'd'), 1)
311
+ (('n', 'é'), 1)
312
+ (('é', 'e'), 1)
313
+ (('B', 'E'), 1)
314
+ (('E', 'K'), 1)
315
+ (('I', 'K'), 1)
316
+ (('S', 'P'), 1)
317
+ (('ط', ','), 1)
318
+ (('M', '7'), 1)
319
+ (('ﻷ', 'ل'), 1)
320
+ (('I', '6'), 1)
321
+ (('e', 'ف'), 1)
322
+ (('.', '('), 1)
323
+ (('P', 's'), 1)
324
+ (('2', 'ا'), 1)
325
+ (('Q', 'U'), 1)
326
+ (('U', 'I'), 1)
327
+ (('M', 'M'), 1)
328
+ (('M', 'U'), 1)
329
+ (('ّ', 'ْ'), 1)
330
+ (('ى', 's'), 1)
331
+ (('d', 'b'), 1)
332
+ (('ً', 'ه'), 1)
333
+ ((')', '؟'), 1)
334
+ (('9', 'م'), 1)
335
+ (('Z', 'N'), 1)
336
+ (('٢', '٪'), 1)
337
+ (('ب', '٩'), 1)
338
+ (('٧', '٥'), 1)
339
+ (('<S>', 'ـ'), 1)
340
+ (('س', '1'), 1)
341
+ (('ل', 'u'), 1)
342
+ (('w', 'd'), 1)
343
+ (('ة', 'M'), 1)
344
+ (('a', 'ق'), 1)
345
+ (('<S>', 'X'), 1)
346
+ (('X', 'ا'), 1)
347
+ (('n', 'z'), 1)
348
+ (('4', 'ر'), 1)
349
+ (('A', 'j'), 1)
350
+ (('g', 'p'), 1)
351
+ (('4', '؛'), 1)
352
+ (('5', 'و'), 1)
353
+ (('ﻹ', 'ث'), 1)
354
+ (('8', '!'), 1)
355
+ (('0', '؛'), 1)
356
+ (('و', '|'), 1)
357
+ (('|', 'ا'), 1)
358
+ (('ع', 'l'), 1)
359
+ (('0', 'ح'), 1)
360
+ (('c', "'"), 1)
361
+ (("'", 'e'), 1)
362
+ (('L', "'"), 1)
363
+ (('p', 'é'), 1)
364
+ (('K', 'و'), 1)
365
+ (('ب', 'K'), 1)
366
+ (('ْ', '\\'), 1)
367
+ ((',', 'ت'), 1)
368
+ ((',', 'د'), 1)
369
+ (('ش', 'ً'), 1)
370
+ (('5', 'ر'), 1)
371
+ (('6', '!'), 1)
372
+ (('ث', '\\'), 1)
373
+ (('ـ', 'G'), 1)
374
+ (('ه', 'p'), 1)
375
+ (('ه', 'B'), 1)
376
+ (('O', 't'), 1)
377
+ (('،', '/'), 1)
378
+ (('M', 'D'), 1)
379
+ (('D', 'G'), 1)
380
+ (('G', 's'), 1)
381
+ (('"', 'P'), 1)
382
+ (('S', '\\'), 1)
383
+ (('k', 'h'), 1)
384
+ (('e', 'z'), 1)
385
+ (('l', 'O'), 1)
386
+ (('ذ', '3'), 1)
387
+ (('ً', '9'), 1)
388
+ (('آ', 'َ'), 1)
389
+ (('O', 's'), 1)
390
+ (('ى', 'ْ'), 1)
391
+ (('ل', ';'), 1)
392
+ (('ي', ';'), 1)
393
+ (('y', 'g'), 1)
394
+ (('R', 'C'), 1)
395
+ (('ٍ', 'أ'), 1)
396
+ (('4', 'ا'), 1)
397
+ (('3', '؛'), 1)
398
+ (('b', 'g'), 1)
399
+ (('g', 'v'), 1)
400
+ (('v', 'b'), 1)
401
+ (('y', 'y'), 1)
402
+ (('5', 'ه'), 1)
403
+ (('ِ', '\\'), 1)
404
+ (('س', '3'), 1)
405
+ (('ف', '3'), 1)
406
+ (('0', '*'), 1)
407
+ ((',', 'ا'), 1)
408
+ (('ر', '5'), 1)
409
+ (('ـ', 'ة'), 1)
410
+ (('ـ', '\\'), 1)
411
+ (('c', '\\'), 1)
412
+ (('V', 'H'), 1)
413
+ (('ّ', 'ؤ'), 1)
414
+ (('E', 'ا'), 1)
415
+ (('e', 'م'), 1)
416
+ (('O', 'D'), 1)
417
+ (('أ', '؛'), 1)
418
+ (('J', 'W'), 1)
419
+ (('y', 'a'), 1)
420
+ (('E', 'v'), 1)
421
+ (('ٌ', 'ة'), 1)
422
+ (('ء', 'ب'), 1)
423
+ (('ج', 'ط'), 1)
424
+ ((',', 'م'), 1)
425
+ (('g', 'ا'), 1)
426
+ (('ز', '2'), 1)
427
+ (('ى', 'ٍ'), 1)
428
+ (('G', 'F'), 1)
429
+ (('ـ', 'E'), 1)
430
+ (('ل', 'e'), 1)
431
+ (('ٌ', 'أ'), 1)
432
+ ((',', 'ن'), 1)
433
+ (('k', 'g'), 1)
434
+ (('M', 'F'), 1)
435
+ (('e', 'ض'), 1)
436
+ (('ا', 'S'), 1)
437
+ (('ى', 'ي'), 1)
438
+ (('3', 'ج'), 1)
439
+ (('ى', '5'), 1)
440
+ (('R', 'B'), 1)
441
+ (('B', 'D'), 1)
442
+ (('4', 'ج'), 1)
443
+ (('k', 'L'), 1)
444
+ (('ر', '6'), 1)
445
+ (('*', 'ط'), 1)
446
+ (('W', 'F'), 1)
447
+ (('S', 'L'), 1)
448
+ (('ط', 'ـ'), 1)
449
+ (('ﻻ', 'ف'), 1)
450
+ (('j', '1'), 1)
451
+ (('ُ', 'آ'), 1)
452
+ (('%', 'إ'), 1)
453
+ (('"', 't'), 1)
454
+ (('o', 'h'), 1)
455
+ (('f', 'y'), 1)
456
+ (('ض', 'ق'), 1)
457
+ (('z', 'y'), 1)
458
+ (('ت', '4'), 1)
459
+ (('ً', 'ب'), 1)
460
+ (('ﻻ', 'و'), 1)
461
+ (('ء', '9'), 1)
462
+ (('ِ', '؛'), 1)
463
+ (('O', 'C'), 1)
464
+ (('ي', 'M'), 1)
465
+ (('*', 'ص'), 1)
466
+ (('م', '6'), 1)
467
+ (('n', 'ي'), 1)
468
+ (('d', 'ا'), 1)
469
+ (('1', 'ع'), 1)
470
+ (('ـ', 'O'), 1)
471
+ (('C', 'W'), 1)
472
+ (('د', '4'), 1)
473
+ (('ٍ', 'إ'), 1)
474
+ (('ٍ', 'ط'), 1)
475
+ (('%', 'أ'), 1)
476
+ (('0', '!'), 1)
477
+ (('d', 'و'), 1)
478
+ (('ا', 'C'), 1)
479
+ (('C', '3'), 1)
480
+ (('"', 'c'), 1)
481
+ (('d', ','), 1)
482
+ (('l', ','), 1)
483
+ (('f', 's'), 1)
484
+ (('s', 'ا'), 1)
485
+ (('َ', 'ـ'), 1)
486
+ (('ت', '1'), 1)
487
+ (('و', 'U'), 1)
488
+ (('و', 'z'), 1)
489
+ (('ً', 'ث'), 1)
490
+ (('ن', '8'), 1)
491
+ (('K', 'ع'), 1)
492
+ (('i', 'H'), 1)
493
+ (('l', 'A'), 1)
494
+ (('M', 'X'), 1)
495
+ (('و', 'R'), 1)
496
+ (('ئ', '؛'), 1)
497
+ (('ـ', 's'), 1)
498
+ (('ة', 'H'), 1)
499
+ (('2', 'ص'), 1)
500
+ (('ش', '؛'), 1)
501
+ (('d', 'j'), 1)
502
+ (('ن', 't'), 1)
503
+ (('ك', ','), 1)
504
+ (('O', 'T'), 1)
505
+ (('B', 'L'), 1)
506
+ (('َ', '؛'), 1)
507
+ (('ﺇ', 'ر'), 1)
508
+ (('ْ', 'ز'), 1)
509
+ (('M', '4'), 1)
510
+ (('M', '5'), 1)
511
+ (('ٌ', '*'), 1)
512
+ (('ا', 'D'), 1)
513
+ (('ة', 'ن'), 1)
514
+ (('k', 'n'), 1)
515
+ (('ل', 'b'), 1)
516
+ (('l', 'p'), 1)
517
+ (('g', 'ب'), 1)
518
+ (('s', ','), 1)
519
+ (('ٍ', 'ض'), 1)
520
+ (('6', '؛'), 1)
521
+ (('*', 'خ'), 1)
522
+ (('7', '\\'), 1)
523
+ (('D', 'Y'), 1)
524
+ (('ع', '2'), 1)
525
+ (('ء', '2'), 1)
526
+ (('r', 'م'), 1)
527
+ (('P', '1'), 1)
528
+ (('ع', 'R'), 1)
529
+ (('ـ', 'ف'), 1)
530
+ (('ت', 'F'), 1)
531
+ (('N', '6'), 1)
532
+ (('ل', 's'), 1)
533
+ (('e', 'ب'), 1)
534
+ (('ق', 'أ'), 1)
535
+ (('M', 'T'), 1)
536
+ (('"', 'e'), 1)
537
+ (('T', 'ا'), 1)
538
+ (('و', 'p'), 1)
539
+ (('ل', 'G'), 1)
540
+ (('ت', 'M'), 1)
541
+ (('S', 'و'), 1)
542
+ (('s', 'ك'), 1)
543
+ (('8', 'إ'), 1)
544
+ (('<S>', 'ئ'), 1)
545
+ (('ٍ', '!'), 1)
546
+ (('ٍ', 'ء'), 1)
547
+ (('ـ', 'ؤ'), 1)
548
+ (('5', 'أ'), 1)
549
+ (('7', 'و'), 1)
550
+ (('5', 'ش'), 1)
551
+ (('C', 'أ'), 1)
552
+ (('ض', 'g'), 1)
553
+ (('*', '5'), 1)
554
+ (('٣', '٢'), 1)
555
+ (('<S>', '٩'), 1)
556
+ (('ذ', '\\'), 1)
557
+ (('٦', '٩'), 1)
558
+ (('o', 'ف'), 1)
559
+ (('ع', 'G'), 1)
560
+ (('4', 'k'), 1)
561
+ (('ة', 'ع'), 1)
562
+ (('2', 'O'), 1)
563
+ (('ظ', '\\'), 1)
564
+ (('َ', 'ٱ'), 1)
565
+ (('ٱ', 'ع'), 1)
566
+ (('<S>', 'ٱ'), 1)
567
+ (('ٱ', 'ل'), 1)
568
+ (('<S>', ']'), 1)
569
+ (('1', 'ق'), 1)
570
+ (('T', '7'), 1)
571
+ (('P', '7'), 1)
572
+ (('ذ', '؛'), 1)
573
+ (('*', 'و'), 1)
574
+ (('*', 'ح'), 1)
575
+ (('ب', 'S'), 1)
576
+ (('و', 'X'), 1)
577
+ (('ﻷ', 'ش'), 1)
578
+ (('ﻷ', 'غ'), 1)
579
+ (('ص', 'أ'), 1)
580
+ (('8', 'ق'), 1)
581
+ (('ى', 'ّ'), 1)
582
+ (('r', '3'), 1)
583
+ (('3', 'ف'), 1)
584
+ (('3', 'a'), 1)
585
+ (('A', 'U'), 1)
586
+ (('U', 'B'), 1)
587
+ (('ل', 'U'), 1)
588
+ (('6', 'J'), 1)
589
+ (('H', 'W'), 1)
590
+ (('b', '\\'), 1)
591
+ (('0', 'ش'), 1)
592
+ (('C', '4'), 1)
593
+ (('ر', 'L'), 1)
594
+ (('٨', '٥'), 1)
595
+ (('G', '7'), 1)
596
+ (('E', 'q'), 1)
597
+ (('1', 'ك'), 1)
598
+ (('r', ','), 1)
599
+ (('g', ','), 1)
600
+ (('R', 'U'), 1)
601
+ (('.', '%'), 1)
602
+ (('r', 'w'), 1)
603
+ (('ز', '1'), 1)
604
+ (('c', 'A'), 1)
605
+ (('A', 'V'), 1)
606
+ (('V', 'G'), 1)
607
+ (('ا', 'c'), 1)
608
+ (('ن', 'T'), 1)
609
+ (('ح', 'R'), 1)
610
+ (('<S>', '،'), 1)
611
+ (('W', '3'), 1)
612
+ (('3', 'C'), 1)
613
+ (('R', 'N'), 1)
614
+ (('ر', 'w'), 1)
615
+ (('ا', 'l'), 1)
616
+ (('h', 'b'), 1)
617
+ (('h', '@'), 1)
618
+ (('ـ', 'N'), 1)
619
+ (('َ', '!'), 1)
620
+ (('ة', 'm'), 1)
621
+ (('G', 'm'), 1)
622
+ (('.', '\\'), 1)
623
+ (('\\', '<E>'), 1)
624
+ (('O', 'r'), 1)
625
+ (('8', 'ع'), 1)
626
+ (('٤', '٩'), 1)
627
+ (('٥', '٣'), 1)
628
+ (('٩', '٣'), 1)
629
+ (('٢', '٤'), 1)
630
+ (('٣', '٩'), 1)
631
+ (('٤', '٧'), 1)
632
+ (('ى', 'D'), 1)
633
+ (('u', 'q'), 1)
634
+ (('ت', 'K'), 1)
635
+ (('2', 'ع'), 1)
636
+ (('d', 'è'), 1)
637
+ (('è', 'l'), 1)
638
+ (('l', 'é'), 1)
639
+ (('é', 'r'), 1)
640
+ (('n', 'ç'), 1)
641
+ (('ç', ';'), 1)
642
+ ((';', 'a'), 1)
643
+ (('i', 'é'), 1)
644
+ (('t', 'é'), 1)
645
+ (('é', 's'), 1)
646
+ (('1', 'ف'), 1)
647
+ (('N', 'Y'), 1)
648
+ (('b', 't'), 1)
649
+ (('3', 'ك'), 1)
650
+ (('6', 'م'), 1)
651
+ (('ه', 'A'), 1)
652
+ (('و', 'H'), 1)
653
+ (('P', 'T'), 1)
654
+ (('ـ', 'د'), 1)
655
+ (('t', 'b'), 1)
656
+ (('0', '+'), 1)
657
+ (('ة', 'g'), 1)
658
+ (('Z', 'D'), 1)
659
+ (('D', 'F'), 1)
660
+ (('2', 'ل'), 1)
661
+ (('.', '!'), 1)
662
+ ((',', 'أ'), 1)
663
+ (('ٍ', 'ً'), 1)
664
+ (('ً', '3'), 1)
665
+ (('ـ', 'H'), 1)
666
+ (('ل', 'L'), 1)
667
+ (('A', '2'), 1)
668
+ (('ا', 'L'), 1)
669
+ (('ى', 'L'), 1)
670
+ (('R', '5'), 1)
671
+ (('ٌ', 'و'), 1)
672
+ (('ل', 'E'), 1)
673
+ (('و', 't'), 1)
674
+ (('r', '@'), 1)
675
+ (('O', 'c'), 1)
676
+ (('ٍ', 'ك'), 1)
677
+ (('U', 'p'), 1)
678
+ (('ذ', 'ـ'), 1)
679
+ (('ك', 'w'), 1)
680
+ (('7', 'ح'), 1)
681
+ (('ئ', 'ى'), 1)
682
+ (('ْ', 'ص'), 1)
683
+ (('9', '؛'), 1)
684
+ (('ﻹ', 'م'), 1)
685
+ (('F', 'R'), 1)
686
+ (('أ', 'ـ'), 1)
687
+ (('"', 'o'), 1)
688
+ (('"', '\\'), 1)
689
+ (('ا', ';'), 1)
690
+ (('I', 'Z'), 1)
691
+ (('ر', 'N'), 1)
692
+ (('W', 'I'), 1)
693
+ (('I', 'F'), 1)
694
+ (('%', 'ا'), 1)
695
+ (('7', 'ا'), 1)
696
+ (('ه', '÷'), 1)
697
+ (('÷', '<E>'), 1)
698
+ (('f', '1'), 1)
699
+ (('1', 'ت'), 1)
700
+ (('C', 'M'), 1)
701
+ (('U', 'D'), 1)
702
+ (('I', 'ف'), 1)
703
+ (('ل', 'P'), 1)
704
+ (('ظ', 'ً'), 1)
705
+ (('ء', 'ّ'), 1)
706
+ (('n', 'ا'), 1)
707
+ (('ة', 'W'), 1)
708
+ (('خ', '2'), 1)
709
+ (('l', 'ك'), 1)
710
+ (('ـ', 'خ'), 1)
711
+ (('ً', 'ك'), 1)
712
+ (('7', 'أ'), 1)
713
+ (('0', 'ك'), 1)
714
+ (('ع', 'ع'), 1)
715
+ (('K', 'j'), 1)
716
+ (('j', 'k'), 1)
717
+ (('4', 'ف'), 1)
718
+ (('0', '_'), 1)
719
+ (('_', '1'), 1)
720
+ (('e', 'ي'), 1)
721
+ (('٢', '٦'), 1)
722
+ (('٢', '٧'), 1)
723
+ (('M', 's'), 1)
724
+ (('و', 'e'), 1)
725
+ (('Z', 'e'), 1)
726
+ (('ة', 'S'), 1)
727
+ (('ع', 'B'), 1)
728
+ (('P', 'L'), 1)
729
+ (('ة', 'D'), 1)
730
+ (('W', 'D'), 1)
731
+ (('D', 'B'), 1)
732
+ (('ر', 'ـ'), 1)
733
+ (('ة', 'ـ'), 1)
734
+ (('m', 'h'), 1)
735
+ (('h', '3'), 1)
736
+ (('B', 'U'), 1)
737
+ (('b', 'j'), 1)
738
+ (('و', '٦'), 1)
739
+ (('ل', '١'), 1)
740
+ (('٧', '٠'), 2)
741
+ (('ً', 'ة'), 2)
742
+ (('ﻻ', 'د'), 2)
743
+ (('<S>', ','), 2)
744
+ (('ٌ', 'خ'), 2)
745
+ (('و', '٢'), 2)
746
+ (('ط', 'ز'), 2)
747
+ (('2', 'أ'), 2)
748
+ (('6', 'ك'), 2)
749
+ (('2', 'م'), 2)
750
+ (('4', 'س'), 2)
751
+ (('E', 'd'), 2)
752
+ (('A', 'P'), 2)
753
+ (('P', 'E'), 2)
754
+ (('ت', '2'), 2)
755
+ (('ن', '2'), 2)
756
+ (('M', 'y'), 2)
757
+ (('K', 'ي'), 2)
758
+ (('3', 'ع'), 2)
759
+ (('4', ','), 2)
760
+ (('A', 'F'), 2)
761
+ (('L', 'L'), 2)
762
+ (('S', 'O'), 2)
763
+ (('K', 'E'), 2)
764
+ (('T', 'B'), 2)
765
+ (('و', 'ﻹ'), 2)
766
+ (('ﻹ', 'ق'), 2)
767
+ (('ﻷ', 'ه'), 2)
768
+ ((',', 'ب'), 2)
769
+ (('ً', 'ج'), 2)
770
+ (('ﻷ', 'ع'), 2)
771
+ (('G', 'H'), 2)
772
+ (('C', 'y'), 2)
773
+ (('ٍ', 'ه'), 2)
774
+ (('"', 'آ'), 2)
775
+ (('ٌ', 'ا'), 2)
776
+ (('د', 'M'), 2)
777
+ (('N', 'u'), 2)
778
+ ((',', '8'), 2)
779
+ (('%', '2'), 2)
780
+ (('%', '1'), 2)
781
+ (('"', '4'), 2)
782
+ (('U', 'P'), 2)
783
+ (('٣', '٥'), 2)
784
+ (('ر', '1'), 2)
785
+ (('2', '\\'), 2)
786
+ (('D', 'D'), 2)
787
+ (('R', 'D'), 2)
788
+ (('ٌ', 'ح'), 2)
789
+ (('0', 'ه'), 2)
790
+ (('s', 'q'), 2)
791
+ (('ٍ', 'و'), 2)
792
+ (('ص', 'ً'), 2)
793
+ (('1', 'B'), 2)
794
+ (('F', '5'), 2)
795
+ (('2', 'ب'), 2)
796
+ (('M', 'L'), 2)
797
+ (('V', 'D'), 2)
798
+ (('ح', 'ً'), 2)
799
+ (('إ', 'ٍ'), 2)
800
+ (('ذ', '!'), 2)
801
+ (('ٍ', 'ة'), 2)
802
+ (('1', '='), 2)
803
+ (('=', '2'), 2)
804
+ (('0', 'ف'), 2)
805
+ (('D', 'N'), 2)
806
+ (('H', 'O'), 2)
807
+ (('H', 'I'), 2)
808
+ (('J', '+'), 2)
809
+ (('و', 'D'), 2)
810
+ (('د', '2'), 2)
811
+ (('l', 'c'), 2)
812
+ (('p', 'd'), 2)
813
+ (('٩', '٨'), 2)
814
+ (('٧', '١'), 2)
815
+ (('D', 'P'), 2)
816
+ (('I', 'H'), 2)
817
+ (('B', 'F'), 2)
818
+ (('ص', '!'), 2)
819
+ (('و', 's'), 2)
820
+ (('0', 'إ'), 2)
821
+ (('7', ','), 2)
822
+ (('ش', '!'), 2)
823
+ (('M', 'c'), 2)
824
+ (('E', '1'), 2)
825
+ (('<S>', ':'), 2)
826
+ (('(', '<E>'), 2)
827
+ (('2', 'ه'), 2)
828
+ (('6', 'ل'), 2)
829
+ (('F', 'L'), 2)
830
+ (('4', 'و'), 2)
831
+ (('0', 'ب'), 2)
832
+ (('|', '<E>'), 2)
833
+ (('s', 'é'), 2)
834
+ (('é', '<E>'), 2)
835
+ (('ً', 'ت'), 2)
836
+ ((',', '2'), 2)
837
+ (('V', 'k'), 2)
838
+ (('k', 't'), 2)
839
+ (('"', 'ز'), 2)
840
+ (('U', 'U'), 2)
841
+ (('ر', '4'), 2)
842
+ (('e', '\\'), 2)
843
+ (('٠', '٩'), 2)
844
+ (('٤', '١'), 2)
845
+ (('y', '\\'), 2)
846
+ (('ٌ', 'ب'), 2)
847
+ (('k', 'j'), 2)
848
+ (('و', 'l'), 2)
849
+ (('V', 'O'), 2)
850
+ (('k', 'f'), 2)
851
+ (('L', 'u'), 2)
852
+ (('y', 'd'), 2)
853
+ (('<S>', '{'), 2)
854
+ (('{', '.'), 2)
855
+ (('F', '3'), 2)
856
+ (('T', 'S'), 2)
857
+ (('و', 'N'), 2)
858
+ (('x', 'x'), 2)
859
+ (('x', 'o'), 2)
860
+ (('n', 'M'), 2)
861
+ (('v', 'r'), 2)
862
+ (('ل', 'A'), 2)
863
+ (('َ', 'ؤ'), 2)
864
+ (('ً', 'ى'), 2)
865
+ (('T', '5'), 2)
866
+ (('ث', '!'), 2)
867
+ (('C', 'K'), 2)
868
+ (('ه', 'ص'), 2)
869
+ (('ﻻ', 'ً'), 2)
870
+ (('ﻹ', 'غ'), 2)
871
+ (('Y', 'P'), 2)
872
+ (('ا', 'ِ'), 2)
873
+ (('E', 't'), 2)
874
+ (('*', '2'), 2)
875
+ (('5', 'س'), 2)
876
+ (('l', 'g'), 2)
877
+ (('j', 'z'), 2)
878
+ (('b', 'c'), 2)
879
+ (('V', '2'), 2)
880
+ (('a', 'a'), 2)
881
+ (('م', ';'), 2)
882
+ (('ن', ';'), 2)
883
+ (('٥', '٦'), 2)
884
+ (('V', 'a'), 2)
885
+ (('ة', '2'), 2)
886
+ (('H', 'B'), 2)
887
+ (('س', 'ز'), 2)
888
+ (('٨', '٧'), 2)
889
+ (('H', 'D'), 2)
890
+ (('e', 'و'), 2)
891
+ (('ي', '*'), 2)
892
+ (('ـ', 'R'), 2)
893
+ (('ٍ', 'ل'), 2)
894
+ (('O', 'X'), 2)
895
+ (('ل', 'M'), 2)
896
+ (('7', 'ع'), 2)
897
+ (('A', 'd'), 2)
898
+ (('G', '4'), 2)
899
+ (('4', 'S'), 2)
900
+ (('ة', 'G'), 2)
901
+ (('y', 'P'), 2)
902
+ (('أ', '\\'), 2)
903
+ (('i', 'q'), 2)
904
+ (('e', 'X'), 2)
905
+ (('M', 'G'), 2)
906
+ (('ذ', 'ش'), 2)
907
+ (('ْ', 'غ'), 2)
908
+ (('<S>', ')'), 2)
909
+ (('L', 'C'), 2)
910
+ (('J', 'U'), 2)
911
+ (('V', 'E'), 2)
912
+ (('N', 'M'), 2)
913
+ (('H', 'A'), 2)
914
+ (('ك', 'I'), 2)
915
+ (('N', 'P'), 2)
916
+ (('6', 'ع'), 2)
917
+ (('S', '3'), 2)
918
+ (('ْ', 'ط'), 2)
919
+ (('خ', 'ً'), 2)
920
+ (('O', 'E'), 2)
921
+ (('P', '5'), 2)
922
+ (('6', 'إ'), 2)
923
+ (('a', '@'), 2)
924
+ (('l', 'ل'), 2)
925
+ (('U', 'C'), 2)
926
+ (('ﻷ', 'ز'), 2)
927
+ (('ُ', '؛'), 2)
928
+ (('y', ','), 2)
929
+ (('ِ', '!'), 2)
930
+ (("'", 'a'), 2)
931
+ (('é', 't'), 2)
932
+ (('ئ', 'ً'), 2)
933
+ (('ٍ', '*'), 2)
934
+ (('و', 'P'), 2)
935
+ (('F', 'N'), 2)
936
+ (('ة', 'N'), 2)
937
+ (('ض', 'آ'), 2)
938
+ (('l', 'v'), 2)
939
+ (('y', 'k'), 2)
940
+ (('ط', 'ْ'), 2)
941
+ (('x', 'c'), 2)
942
+ (('I', 'm'), 2)
943
+ (('إ', 'و'), 2)
944
+ (('v', 'y'), 2)
945
+ (('س', '2'), 2)
946
+ (('ـ', 'D'), 2)
947
+ (('٥', '٧'), 2)
948
+ (('1', 'ه'), 2)
949
+ (('ـ', 'ح'), 2)
950
+ (('ﻹ', 'ج'), 2)
951
+ (('ن', '5'), 2)
952
+ (('O', 'u'), 2)
953
+ (('F', 'M'), 2)
954
+ (('ي', 'B'), 2)
955
+ (('B', '5'), 2)
956
+ (('F', '4'), 2)
957
+ (('٠', '٤'), 2)
958
+ (('ؤ', 'ِ'), 2)
959
+ (('W', 'E'), 2)
960
+ (('م', '3'), 2)
961
+ (('<S>', 'k'), 2)
962
+ (('ٍ', 'م'), 2)
963
+ (('ـ', 'ك'), 2)
964
+ (('و', 'o'), 2)
965
+ (('ة', 'C'), 2)
966
+ (('ى', 'ٌ'), 2)
967
+ (('R', 'M'), 2)
968
+ (('ّ', '\\'), 2)
969
+ (('و', ','), 2)
970
+ (('B', 'y'), 2)
971
+ (('ه', 'خ'), 2)
972
+ (('a', 'ا'), 2)
973
+ (('E', 'U'), 2)
974
+ (('s', '\\'), 2)
975
+ (('*', '6'), 2)
976
+ (('ـ', 'a'), 2)
977
+ (('،', '؟'), 2)
978
+ (('ﻷ', 'ث'), 2)
979
+ (('J', 'S'), 2)
980
+ (('"', 'ذ'), 2)
981
+ (('Q', 'u'), 2)
982
+ (('e', 'B'), 2)
983
+ (('l', 'b'), 2)
984
+ (('ا', '1'), 2)
985
+ (('S', 'C'), 2)
986
+ (('و', 'B'), 2)
987
+ (('و', 'M'), 2)
988
+ (('ً', ';'), 2)
989
+ (('٤', '٨'), 2)
990
+ (('٥', '٨'), 2)
991
+ (('٩', '١'), 2)
992
+ (('5', 'ي'), 2)
993
+ (('Y', 'a'), 2)
994
+ (('ٍ', 'غ'), 2)
995
+ (('ٍ', 'ح'), 2)
996
+ (('ٌ', 'ج'), 2)
997
+ (('ً', 'ع'), 2)
998
+ (('ٍ', 'ب'), 2)
999
+ (('ت', '‘'), 2)
1000
+ (('‘', 'ب'), 2)
1001
+ (('٤', '٥'), 2)
1002
+ (('M', 'r'), 3)
1003
+ (('ﻻ', 'ﻻ'), 3)
1004
+ (('ي', '1'), 3)
1005
+ (('A', 'Y'), 3)
1006
+ (('ة', 'T'), 3)
1007
+ (('+', '<E>'), 3)
1008
+ (('1', 'س'), 3)
1009
+ (('0', 'س'), 3)
1010
+ (('V', 'X'), 3)
1011
+ (('r', 'b'), 3)
1012
+ (('g', 'g'), 3)
1013
+ (('m', 'q'), 3)
1014
+ (('ﺇ', 'س'), 3)
1015
+ (('ﺇ', 'ذ'), 3)
1016
+ (('u', 'y'), 3)
1017
+ (('E', 'B'), 3)
1018
+ (('E', 'A'), 3)
1019
+ (('ؤ', 'ٍ'), 3)
1020
+ (('5', 'م'), 3)
1021
+ (('ن', ','), 3)
1022
+ (('ً', 'أ'), 3)
1023
+ (('ش', 'ـ'), 3)
1024
+ (('ـ', 'ئ'), 3)
1025
+ (('ٌ', 'غ'), 3)
1026
+ (('ؤ', 'ُ'), 3)
1027
+ ((',', '7'), 3)
1028
+ (('"', '7'), 3)
1029
+ (('0', '\\'), 3)
1030
+ (('ـ', 'ق'), 3)
1031
+ (('I', 'R'), 3)
1032
+ (('<S>', '|'), 3)
1033
+ (('|', 'أ'), 3)
1034
+ (('َ', '*'), 3)
1035
+ (('ْ', 'خ'), 3)
1036
+ (('G', 'I'), 3)
1037
+ (('ُ', 'ة'), 3)
1038
+ (('ـ', 'و'), 3)
1039
+ ((',', '3'), 3)
1040
+ (('1', '\\'), 3)
1041
+ (('F', 'A'), 3)
1042
+ (('J', '<E>'), 3)
1043
+ (('ﻻ', 'ج'), 3)
1044
+ (('ٌ', 'ل'), 3)
1045
+ (('ه', 'ـ'), 3)
1046
+ (('A', 'u'), 3)
1047
+ (('t', '’'), 3)
1048
+ (('’', 's'), 3)
1049
+ (('٤', '٦'), 3)
1050
+ (('U', 'M'), 3)
1051
+ (('ه', 'ْ'), 3)
1052
+ (('م', '7'), 3)
1053
+ ((']', '.'), 3)
1054
+ (('*', 'ه'), 3)
1055
+ (('*', 'س'), 3)
1056
+ (('o', 'K'), 3)
1057
+ (('u', 'T'), 3)
1058
+ (('D', 'V'), 3)
1059
+ (('ً', 'ف'), 3)
1060
+ (('1', '+'), 3)
1061
+ (('و', 'ﻷ'), 3)
1062
+ (('ﻹ', 'ب'), 3)
1063
+ (('N', 'K'), 3)
1064
+ (('D', 'E'), 3)
1065
+ (('T', 'C'), 3)
1066
+ (('ـ', 'A'), 3)
1067
+ (('١', '٪'), 3)
1068
+ (('t', 'n'), 3)
1069
+ (('F', 'C'), 3)
1070
+ (('خ', '؛'), 3)
1071
+ (('"', 'ث'), 3)
1072
+ (('n', '’'), 3)
1073
+ (('’', 't'), 3)
1074
+ (('*', 'ن'), 3)
1075
+ (('ً', 'خ'), 3)
1076
+ (('٣', '١'), 3)
1077
+ (('ـ', 'ج'), 3)
1078
+ (('ء', '!'), 3)
1079
+ (('L', 'A'), 3)
1080
+ (('ى', '3'), 3)
1081
+ (('A', 'O'), 3)
1082
+ (('ﻹ', 'ر'), 3)
1083
+ (('<S>', '٨'), 3)
1084
+ (('آ', '<E>'), 3)
1085
+ (('A', 'e'), 3)
1086
+ (('U', 'V'), 3)
1087
+ (('O', 'W'), 3)
1088
+ (('H', '2'), 3)
1089
+ (('٠', '٢'), 3)
1090
+ (('٩', '<E>'), 3)
1091
+ (('6', ','), 3)
1092
+ (('5', ','), 3)
1093
+ (('ط', 'آ'), 3)
1094
+ (('د', 'ـ'), 3)
1095
+ (('G', '8'), 3)
1096
+ (('أ', 'ا'), 3)
1097
+ (('z', '<E>'), 3)
1098
+ (('S', 'l'), 3)
1099
+ (('ة', '1'), 3)
1100
+ (('M', 'W'), 3)
1101
+ (('O', 'U'), 3)
1102
+ (('p', 'm'), 3)
1103
+ (('ﻷ', 'ُ'), 3)
1104
+ (('ﻹ', 'ت'), 3)
1105
+ (('G', 'C'), 3)
1106
+ (('7', '+'), 3)
1107
+ (('ب', '9'), 3)
1108
+ (('L', '1'), 3)
1109
+ (('B', 'J'), 3)
1110
+ (('l', 'm'), 3)
1111
+ (('@', '<E>'), 3)
1112
+ (('B', 'é'), 3)
1113
+ (('é', 'z'), 3)
1114
+ (('g', '\\'), 3)
1115
+ (('ٌ', 'د'), 3)
1116
+ ((',', '6'), 3)
1117
+ (('ـ', 'إ'), 3)
1118
+ (('P', 'M'), 3)
1119
+ (('ل', 'N'), 3)
1120
+ (('ى', '2'), 3)
1121
+ (('O', 'L'), 3)
1122
+ (('F', 'O'), 3)
1123
+ (('l', 'k'), 3)
1124
+ (('م', '1'), 3)
1125
+ (('ّ', '؛'), 3)
1126
+ (('8', 'س'), 3)
1127
+ (('أ', 'ٍ'), 3)
1128
+ (('G', 'A'), 3)
1129
+ (('S', 'w'), 3)
1130
+ (('ﻷ', 'د'), 3)
1131
+ (('ه', ','), 3)
1132
+ (('٩', '٠'), 3)
1133
+ (('L', 'O'), 3)
1134
+ (('N', 'U'), 3)
1135
+ (('<S>', 'Q'), 3)
1136
+ (('ﻹ', 'د'), 3)
1137
+ (('U', 'X'), 3)
1138
+ (('X', 'N'), 3)
1139
+ (('O', 'O'), 3)
1140
+ (('O', 'G'), 3)
1141
+ (('G', 'L'), 3)
1142
+ (('o', 'P'), 3)
1143
+ (('ـ', 'ث'), 3)
1144
+ (('*', 'ر'), 3)
1145
+ (('*', 'ع'), 3)
1146
+ (('}', '{'), 3)
1147
+ (('و', 'W'), 3)
1148
+ (('1', 'و'), 3)
1149
+ (('ْ', 'ئ'), 3)
1150
+ (('A', 'v'), 3)
1151
+ (('ت', 'ـ'), 3)
1152
+ (('ْ', 'إ'), 3)
1153
+ (('e', 'q'), 3)
1154
+ (('a', 'w'), 3)
1155
+ (('K', 'a'), 3)
1156
+ (('K', 'i'), 3)
1157
+ (('2', 'و'), 3)
1158
+ (('O', 'l'), 3)
1159
+ (('ئ', 'ظ'), 3)
1160
+ (('ْ', 'ء'), 3)
1161
+ (('<S>', '}'), 3)
1162
+ (('A', '&'), 3)
1163
+ (('&', 'F'), 3)
1164
+ (('ـ', 'M'), 3)
1165
+ (('"', 's'), 3)
1166
+ (('ً', 'و'), 3)
1167
+ (('٦', '٦'), 3)
1168
+ (('٦', '٧'), 3)
1169
+ (('ن', '6'), 3)
1170
+ (('*', 'د'), 3)
1171
+ (('ﻻ', 'ء'), 3)
1172
+ (('n', '\\'), 3)
1173
+ (('ب', ','), 3)
1174
+ (('ى', ','), 3)
1175
+ (('L', 'S'), 3)
1176
+ (('8', 'م'), 3)
1177
+ (('U', 'T'), 3)
1178
+ (('<S>', 'ﻵ'), 3)
1179
+ (('T', 'P'), 3)
1180
+ (('<S>', 'ؤ'), 3)
1181
+ (('0', 'ا'), 4)
1182
+ (('ً', 'س'), 4)
1183
+ (('و', 'A'), 4)
1184
+ (('y', 'i'), 4)
1185
+ (('س', 'ش'), 4)
1186
+ (('N', 'i'), 4)
1187
+ (('Y', '<E>'), 4)
1188
+ (('t', 'p'), 4)
1189
+ (('ـ', 'س'), 4)
1190
+ (('ز', 'آ'), 4)
1191
+ (('ْ', 'ا'), 4)
1192
+ (('ْ', 'ث'), 4)
1193
+ (('S', 'n'), 4)
1194
+ (('a', 'o'), 4)
1195
+ (('ـ', 'c'), 4)
1196
+ (('آ', 'ح'), 4)
1197
+ (('ض', '!'), 4)
1198
+ (('q', '@'), 4)
1199
+ (('ص', 'ش'), 4)
1200
+ (('I', 'r'), 4)
1201
+ (('٨', '٦'), 4)
1202
+ (('ٌ', 'ن'), 4)
1203
+ (('غ', 'ْ'), 4)
1204
+ (('ﻹ', 'خ'), 4)
1205
+ (('H', 'S'), 4)
1206
+ (('ز', 'ط'), 4)
1207
+ (('ُ', '!'), 4)
1208
+ (('P', 'k'), 4)
1209
+ (('k', 'k'), 4)
1210
+ (('n', 'h'), 4)
1211
+ (('P', 'R'), 4)
1212
+ (('<S>', '٣'), 4)
1213
+ (('G', 'R'), 4)
1214
+ (('ى', '!'), 4)
1215
+ (('A', 'J'), 4)
1216
+ (('l', 'h'), 4)
1217
+ (('I', 't'), 4)
1218
+ (('ﻻ', 'ي'), 4)
1219
+ (('E', 's'), 4)
1220
+ (('L', 'N'), 4)
1221
+ (('M', 'C'), 4)
1222
+ (('<S>', 'ٌ'), 4)
1223
+ (('م', ','), 4)
1224
+ (('O', 'I'), 4)
1225
+ (('و', '!'), 4)
1226
+ (('َ', 'ئ'), 4)
1227
+ (('،', '.'), 4)
1228
+ (('d', 'n'), 4)
1229
+ (('3', ','), 4)
1230
+ (('O', 'M'), 4)
1231
+ (('E', 'W'), 4)
1232
+ (('W', 'S'), 4)
1233
+ (('C', 'T'), 4)
1234
+ (('ـ', 'I'), 4)
1235
+ (('G', 'M'), 4)
1236
+ (('n', 'q'), 4)
1237
+ (('C', 'P'), 4)
1238
+ (('ٌ', 'ت'), 4)
1239
+ (('0', 'ي'), 4)
1240
+ (('و', 'C'), 4)
1241
+ (('M', 'B'), 4)
1242
+ (('ؤ', 'َ'), 4)
1243
+ (('-', '-'), 4)
1244
+ (('٨', '٠'), 4)
1245
+ (('و', '؛'), 4)
1246
+ (('ز', 'ْ'), 4)
1247
+ (('ط', 'ً'), 4)
1248
+ (('<S>', '٦'), 4)
1249
+ (('V', 'o'), 4)
1250
+ (('I', 'M'), 4)
1251
+ (('A', 'K'), 4)
1252
+ (('C', 'u'), 4)
1253
+ (('غ', '\\'), 4)
1254
+ (('H', 'C'), 4)
1255
+ (('w', 'r'), 4)
1256
+ (('ج', '؛'), 4)
1257
+ (('+', '7'), 4)
1258
+ (('S', 'B'), 4)
1259
+ (('s', 'n'), 4)
1260
+ (('م', 'ـ'), 4)
1261
+ (('ة', ';'), 4)
1262
+ (('ل', '9'), 4)
1263
+ (('ـ', 'ع'), 4)
1264
+ (('٠', '٧'), 4)
1265
+ (('ـ', 'W'), 4)
1266
+ (('*', 'ق'), 4)
1267
+ (('ت', ','), 4)
1268
+ (('ٍ', 'س'), 4)
1269
+ (('A', 'G'), 4)
1270
+ (('E', 'L'), 4)
1271
+ (('A', 'A'), 4)
1272
+ (('ز', '؛'), 4)
1273
+ (('E', 'I'), 4)
1274
+ (('t', "'"), 4)
1275
+ (('ْ', 'ح'), 4)
1276
+ (('د', 'ﻻ'), 4)
1277
+ (('ْ', 'ة'), 4)
1278
+ (('S', 'M'), 4)
1279
+ (('C', 'U'), 4)
1280
+ (('ك', 'ً'), 4)
1281
+ (('E', 'O'), 4)
1282
+ (('ح', '!'), 4)
1283
+ (('z', 'l'), 4)
1284
+ (('،', '{'), 4)
1285
+ (('ض', 'ْ'), 4)
1286
+ (('P', 'H'), 4)
1287
+ (('ز', 'ؤ'), 5)
1288
+ (('L', 'U'), 5)
1289
+ (('٠', '٦'), 5)
1290
+ (('o', 'j'), 5)
1291
+ (('E', 'l'), 5)
1292
+ (('j', 'u'), 5)
1293
+ (('ب', '4'), 5)
1294
+ (('،', '،'), 5)
1295
+ (('ـ', 'S'), 5)
1296
+ (('ذ', 'ذ'), 5)
1297
+ (('ث', 'ْ'), 5)
1298
+ (('ن', 'ـ'), 5)
1299
+ (('P', 'i'), 5)
1300
+ (('R', 'u'), 5)
1301
+ (('ة', 'ّ'), 5)
1302
+ (('i', 'x'), 5)
1303
+ (('x', 'e'), 5)
1304
+ (('ي', ','), 5)
1305
+ (('ط', '!'), 5)
1306
+ (('E', 'g'), 5)
1307
+ (('*', 'ف'), 5)
1308
+ (('ً', 'ر'), 5)
1309
+ (('<S>', '%'), 5)
1310
+ (('N', 'O'), 5)
1311
+ (('R', 'I'), 5)
1312
+ (('"', 'ص'), 5)
1313
+ (('L', 'R'), 5)
1314
+ (('ق', 'ً'), 5)
1315
+ (('ً', 'ح'), 5)
1316
+ (('ٌ', 'ّ'), 5)
1317
+ (('٨', '٢'), 5)
1318
+ (('٩', '٢'), 5)
1319
+ (('٩', '٤'), 5)
1320
+ (('ج', 'ْ'), 5)
1321
+ (('َ', 'آ'), 5)
1322
+ (('K', 'B'), 5)
1323
+ (('e', 'ا'), 5)
1324
+ (('ـ', 'ي'), 5)
1325
+ (('O', 'B'), 5)
1326
+ (('B', 'O'), 5)
1327
+ (('ـ', 'P'), 5)
1328
+ (('W', '<E>'), 5)
1329
+ (('F', 'e'), 5)
1330
+ (('ب', '8'), 5)
1331
+ (('N', 'C'), 5)
1332
+ (('٣', '٠'), 5)
1333
+ (('ل', '8'), 5)
1334
+ (('ـ', 'p'), 5)
1335
+ (('ف', 'ً'), 5)
1336
+ (('٢', '٣'), 5)
1337
+ (('9', ','), 5)
1338
+ (('H', '1'), 5)
1339
+ (('ل', ','), 5)
1340
+ (('ؤ', 'ّ'), 5)
1341
+ (('L', 'a'), 5)
1342
+ (('ص', '؛'), 5)
1343
+ (('F', 'l'), 5)
1344
+ (('C', 'r'), 5)
1345
+ (('K', 'e'), 5)
1346
+ (('ٌ', 'م'), 5)
1347
+ (('ﻹ', 'ن'), 5)
1348
+ (('ط', '؛'), 5)
1349
+ (('ﻵ', 'خ'), 5)
1350
+ (('D', 'y'), 5)
1351
+ (('C', 'E'), 5)
1352
+ (('g', 'n'), 5)
1353
+ (('S', 'k'), 5)
1354
+ (('k', 'y'), 5)
1355
+ (('ص', 'ْ'), 5)
1356
+ (('ً', 'ش'), 5)
1357
+ (('T', 'A'), 5)
1358
+ (('ﻹ', 'ط'), 5)
1359
+ (('ي', '2'), 5)
1360
+ (('*', 'ي'), 5)
1361
+ (('3', 'م'), 5)
1362
+ (('.', '}'), 5)
1363
+ (('}', '<E>'), 5)
1364
+ (('٩', '٦'), 6)
1365
+ (('ً', 'م'), 6)
1366
+ (('ً', 'ص'), 6)
1367
+ (('U', '<E>'), 6)
1368
+ (('ـ', 'F'), 6)
1369
+ (('j', 'e'), 6)
1370
+ (('A', 'i'), 6)
1371
+ (('ن', '4'), 6)
1372
+ (('ه', 'ً'), 6)
1373
+ (('S', 'm'), 6)
1374
+ (('؟', '<E>'), 6)
1375
+ (("'", 's'), 6)
1376
+ (('س', 'ً'), 6)
1377
+ (('e', 'k'), 6)
1378
+ (('ﻷ', 'ح'), 6)
1379
+ (('B', 'e'), 6)
1380
+ (('ﻷ', 'ص'), 6)
1381
+ (('A', 'S'), 6)
1382
+ (('ن', '1'), 6)
1383
+ (('g', 's'), 6)
1384
+ (('p', 'y'), 6)
1385
+ (('y', 'b'), 6)
1386
+ (('ٍ', 'ن'), 6)
1387
+ (('ب', '6'), 6)
1388
+ (('ز', 'س'), 6)
1389
+ (('a', 'x'), 6)
1390
+ (('<S>', 'z'), 6)
1391
+ (('z', 'o'), 6)
1392
+ (('4', '\\'), 6)
1393
+ (('D', 'L'), 6)
1394
+ (('ْ', 'ش'), 6)
1395
+ (('E', 'G'), 6)
1396
+ (('%', 'م'), 6)
1397
+ (('١', '٧'), 6)
1398
+ (('2', ','), 6)
1399
+ (('I', 'B'), 6)
1400
+ (('%', '.'), 6)
1401
+ (('5', 'ع'), 6)
1402
+ (('٠', '٨'), 6)
1403
+ (('%', '،'), 6)
1404
+ (('ؤ', 'ْ'), 6)
1405
+ (('ح', '\\'), 6)
1406
+ ((',', '9'), 6)
1407
+ (('A', 'E'), 6)
1408
+ (('R', 'T'), 6)
1409
+ (('N', 'D'), 6)
1410
+ (('A', 'g'), 6)
1411
+ (('س', 'ـ'), 6)
1412
+ (('G', 'l'), 6)
1413
+ (('ـ', 'T'), 6)
1414
+ (('٢', '٥'), 6)
1415
+ (('ق', '!'), 6)
1416
+ (('ـ', 'ب'), 6)
1417
+ (('m', 'y'), 6)
1418
+ (('٦', '٥'), 6)
1419
+ (('ء', 'ى'), 6)
1420
+ (('k', 'o'), 6)
1421
+ (('x', 'a'), 6)
1422
+ (('i', 'k'), 6)
1423
+ (('y', 'c'), 6)
1424
+ (('u', 'z'), 6)
1425
+ (('z', 'z'), 6)
1426
+ (('ر', ','), 6)
1427
+ (('M', '1'), 6)
1428
+ (('B', 'M'), 6)
1429
+ (('ﻹ', 'ي'), 6)
1430
+ (('٠', '٥'), 6)
1431
+ (('R', 'o'), 6)
1432
+ (('ث', '؛'), 6)
1433
+ (('ث', 'س'), 6)
1434
+ (('د', ','), 6)
1435
+ (('<S>', 'İ'), 6)
1436
+ (('İ', 'H'), 6)
1437
+ (('G', 'E'), 6)
1438
+ (('E', 'M'), 6)
1439
+ (('0', 'و'), 6)
1440
+ (('B', '2'), 6)
1441
+ (('U', 'R'), 6)
1442
+ (('O', 'P'), 6)
1443
+ (('h', 'f'), 6)
1444
+ (('a', 'e'), 6)
1445
+ (('K', 'I'), 6)
1446
+ (('٦', '٠'), 7)
1447
+ (('0', 'أ'), 7)
1448
+ (('M', 'P'), 7)
1449
+ (('C', 'l'), 7)
1450
+ (('A', 't'), 7)
1451
+ (('x', 't'), 7)
1452
+ (('S', 'N'), 7)
1453
+ (('م', '2'), 7)
1454
+ (('I', 'D'), 7)
1455
+ (('ج', 'ق'), 7)
1456
+ (('X', '<E>'), 7)
1457
+ (('ث', 'د'), 7)
1458
+ (('t', 'm'), 7)
1459
+ (('x', 'i'), 7)
1460
+ (('n', 'm'), 7)
1461
+ (('ب', '5'), 7)
1462
+ (('٢', '٢'), 7)
1463
+ (('O', 'f'), 7)
1464
+ (('H', 'i'), 7)
1465
+ (('s', 'f'), 7)
1466
+ (('V', 'I'), 7)
1467
+ (('P', 'S'), 7)
1468
+ (('y', 't'), 7)
1469
+ (('ض', '\\'), 7)
1470
+ (('S', 'i'), 7)
1471
+ (('B', 'i'), 7)
1472
+ (('P', 'Y'), 7)
1473
+ (('A', 'f'), 7)
1474
+ (('I', 'E'), 7)
1475
+ (('ا', 'أ'), 7)
1476
+ (('P', 'I'), 7)
1477
+ (('ﻻ', 'ح'), 7)
1478
+ (('ئ', 'ـ'), 7)
1479
+ (('F', 'D'), 7)
1480
+ (('D', 'R'), 7)
1481
+ (('ْ', 'ج'), 7)
1482
+ (('<S>', 'q'), 7)
1483
+ (('o', 'y'), 7)
1484
+ (('L', 'E'), 7)
1485
+ (('}', '،'), 7)
1486
+ (('H', 'H'), 7)
1487
+ (('P', 'P'), 7)
1488
+ (('ظ', 'ٍ'), 7)
1489
+ (('ـ', 'ه'), 7)
1490
+ (('ض', 'أ'), 7)
1491
+ (('D', 'u'), 7)
1492
+ (('E', 'P'), 7)
1493
+ (('ح', 'ؤ'), 7)
1494
+ (('n', 'u'), 7)
1495
+ (('h', 'u'), 7)
1496
+ (('ِ', 'خ'), 7)
1497
+ (('ى', 'ن'), 7)
1498
+ (('ل', '7'), 7)
1499
+ (('ٍ', 'ا'), 7)
1500
+ (('"', 'ق'), 7)
1501
+ (('O', 'b'), 7)
1502
+ (('M', '<E>'), 7)
1503
+ (('ً', 'ق'), 7)
1504
+ (('ـ', 'ا'), 7)
1505
+ (('j', 'j'), 7)
1506
+ (('٩', '٥'), 7)
1507
+ (('P', 'D'), 7)
1508
+ (('ـ', 'م'), 8)
1509
+ (('٩', '٩'), 8)
1510
+ (('A', 'C'), 8)
1511
+ (('D', 'C'), 8)
1512
+ (('ض', '؛'), 8)
1513
+ (('<S>', 'ّ'), 8)
1514
+ (('M', 'u'), 8)
1515
+ (('ْ', 'ق'), 8)
1516
+ (('n', 'v'), 8)
1517
+ (('y', 'm'), 8)
1518
+ (('٢', '١'), 8)
1519
+ (("'", 't'), 8)
1520
+ (('u', 'd'), 8)
1521
+ (('ـ', 'B'), 8)
1522
+ (('H', 'e'), 8)
1523
+ (('ش', 'ْ'), 8)
1524
+ (('N', 'S'), 8)
1525
+ (('n', 'l'), 8)
1526
+ (('ـ', 'ل'), 8)
1527
+ (('u', 'f'), 8)
1528
+ (('Y', 'D'), 8)
1529
+ (('ع', '!'), 8)
1530
+ (('k', 's'), 8)
1531
+ (('ر', 'إ'), 8)
1532
+ (('ف', '!'), 8)
1533
+ (('ص', '\\'), 8)
1534
+ (('ي', 'ـ'), 8)
1535
+ (('M', 'O'), 8)
1536
+ (('S', 'c'), 8)
1537
+ (('V', '<E>'), 8)
1538
+ (('A', 'c'), 8)
1539
+ ((',', '5'), 8)
1540
+ (('T', 'U'), 8)
1541
+ (('P', 'C'), 8)
1542
+ (('T', 'I'), 8)
1543
+ (('*', 'ل'), 8)
1544
+ (('d', 'l'), 8)
1545
+ (('y', 'e'), 8)
1546
+ (('ـ', 'ن'), 8)
1547
+ (('P', 'G'), 8)
1548
+ (('s', 'r'), 8)
1549
+ (('B', 'o'), 8)
1550
+ (('*', 'م'), 8)
1551
+ (('t', 'f'), 8)
1552
+ (('D', 'S'), 8)
1553
+ (('O', 'n'), 8)
1554
+ (('b', 'y'), 9)
1555
+ (('(', '('), 9)
1556
+ ((')', ')'), 9)
1557
+ (('y', 'r'), 9)
1558
+ (('ـ', 'C'), 9)
1559
+ (('b', 'b'), 9)
1560
+ (('؟', '،'), 9)
1561
+ (('A', 'M'), 9)
1562
+ (('ٌ', 'ع'), 9)
1563
+ (('"', 'خ'), 9)
1564
+ (('ط', '\\'), 9)
1565
+ (('T', 'N'), 9)
1566
+ (('A', 'I'), 9)
1567
+ (('ً', 'ّ'), 9)
1568
+ (('ى', 'ٰ'), 9)
1569
+ (('ٰ', '<E>'), 9)
1570
+ (('x', 'y'), 9)
1571
+ (('O', 'p'), 9)
1572
+ (('١', '٦'), 9)
1573
+ (('ﺇ', 'ل'), 9)
1574
+ (('ٍ', 'ي'), 9)
1575
+ (('n', "'"), 9)
1576
+ (('L', '<E>'), 9)
1577
+ (('٤', '٠'), 9)
1578
+ (('"', 'ش'), 9)
1579
+ (('ـ', 'ـ'), 9)
1580
+ (('ّ', 'ئ'), 9)
1581
+ (('e', 'h'), 9)
1582
+ (('ب', '7'), 9)
1583
+ (('C', 'O'), 9)
1584
+ (('*', '<E>'), 9)
1585
+ (('M', '2'), 9)
1586
+ (('F', '1'), 9)
1587
+ (('O', 'K'), 9)
1588
+ (('p', 's'), 9)
1589
+ (('I', 'L'), 9)
1590
+ (('س', '!'), 9)
1591
+ (('*', 'أ'), 9)
1592
+ (('T', 'u'), 9)
1593
+ (('}', '.'), 9)
1594
+ (('R', 'O'), 9)
1595
+ (('s', 'k'), 9)
1596
+ (('t', 'w'), 9)
1597
+ (('n', 'n'), 9)
1598
+ (('<S>', '٤'), 9)
1599
+ (('j', 'b'), 9)
1600
+ (('٥', '٢'), 9)
1601
+ (('h', 'n'), 9)
1602
+ (('v', '<E>'), 9)
1603
+ (('W', 'i'), 9)
1604
+ (('٠', '٣'), 9)
1605
+ (('ً', 'ن'), 9)
1606
+ (('J', 'e'), 9)
1607
+ (('ف', '\\'), 10)
1608
+ (('ظ', 'ٌ'), 10)
1609
+ (('خ', 'ك'), 10)
1610
+ (('٥', '٠'), 10)
1611
+ (('C', 'e'), 10)
1612
+ (('ش', 'ء'), 10)
1613
+ (('ﻷ', 'ي'), 10)
1614
+ (('ئ', 'ُ'), 10)
1615
+ (('C', 'A'), 10)
1616
+ (('ـ', 'ت'), 10)
1617
+ (('G', '<E>'), 10)
1618
+ (('و', 'T'), 10)
1619
+ (('.', '؟'), 10)
1620
+ (('ٌ', 'ر'), 10)
1621
+ (('ل', '3'), 10)
1622
+ (('e', 'y'), 10)
1623
+ (('ء', '\\'), 10)
1624
+ (('غ', 'ك'), 10)
1625
+ (('v', 'o'), 10)
1626
+ (('ذ', 'ً'), 10)
1627
+ (('W', 'h'), 10)
1628
+ (('<S>', 'ٍ'), 10)
1629
+ (('ﻷ', 'ب'), 10)
1630
+ (('ؤ', 'ص'), 10)
1631
+ (('س', '؛'), 10)
1632
+ (('T', 'R'), 10)
1633
+ (('ﻻ', 'ت'), 10)
1634
+ (('ع', 'ً'), 10)
1635
+ (('٨', '<E>'), 10)
1636
+ (('S', 'I'), 10)
1637
+ (('*', 'ب'), 10)
1638
+ (('*', 'إ'), 10)
1639
+ (('b', 's'), 10)
1640
+ (('ش', 'ش'), 10)
1641
+ (('N', 'A'), 10)
1642
+ (('C', 'H'), 10)
1643
+ (('I', 'O'), 10)
1644
+ (('G', 'O'), 10)
1645
+ (('M', 'S'), 10)
1646
+ (('ا', ','), 10)
1647
+ (('ه', 'أ'), 10)
1648
+ (('H', 'K'), 10)
1649
+ (('ا', 'ﻻ'), 10)
1650
+ (('٧', '<E>'), 10)
1651
+ (('E', 'C'), 10)
1652
+ (('ذ', 'ح'), 10)
1653
+ (('ﻹ', 'ع'), 11)
1654
+ (('١', '٥'), 11)
1655
+ (('P', 'h'), 11)
1656
+ (('m', 's'), 11)
1657
+ (('P', 'u'), 11)
1658
+ (('x', 'p'), 11)
1659
+ (('0', 'ع'), 11)
1660
+ (('H', 'a'), 11)
1661
+ (('ظ', 'ك'), 11)
1662
+ (('ً', 'ل'), 11)
1663
+ (('d', 'd'), 11)
1664
+ (('A', 'B'), 11)
1665
+ (('S', 'E'), 11)
1666
+ (('J', 'u'), 11)
1667
+ (('S', 'a'), 11)
1668
+ (('a', 'f'), 11)
1669
+ (('C', 'i'), 11)
1670
+ (('b', '<E>'), 11)
1671
+ (('w', 'h'), 11)
1672
+ (('ر', '2'), 11)
1673
+ (('1', ','), 11)
1674
+ (('ل', '6'), 11)
1675
+ (('خ', 'ْ'), 11)
1676
+ (('A', 'T'), 11)
1677
+ (('s', 'y'), 11)
1678
+ (('١', '٨'), 11)
1679
+ (('h', 'y'), 11)
1680
+ (('ً', '\\'), 11)
1681
+ (('D', 'A'), 11)
1682
+ (('*', 'ت'), 11)
1683
+ (('J', 'a'), 11)
1684
+ ((')', '.'), 11)
1685
+ (('ز', '\\'), 11)
1686
+ (('h', 'r'), 11)
1687
+ (('أ', 'ّ'), 12)
1688
+ (('"', 'د'), 12)
1689
+ (('d', 's'), 12)
1690
+ (('ع', '؛'), 12)
1691
+ (('ﻷ', 'ج'), 12)
1692
+ (('G', 'e'), 12)
1693
+ (('w', 'n'), 12)
1694
+ (('o', 'a'), 12)
1695
+ (('l', 'r'), 12)
1696
+ ((')', '،'), 12)
1697
+ (('ل', '5'), 12)
1698
+ (('ى', '\\'), 12)
1699
+ (('<S>', 'َ'), 12)
1700
+ (('َ', 'إ'), 12)
1701
+ (('p', 'u'), 12)
1702
+ (('T', 'a'), 12)
1703
+ (('G', 'P'), 12)
1704
+ (('y', 'p'), 12)
1705
+ (('G', 'T'), 12)
1706
+ (('E', 'S'), 12)
1707
+ (('ﻷ', 'ك'), 12)
1708
+ (('B', '<E>'), 12)
1709
+ (('T', 'V'), 12)
1710
+ (('ب', '!'), 12)
1711
+ (('ْ', 'و'), 12)
1712
+ (('y', 'n'), 12)
1713
+ (('F', 'u'), 12)
1714
+ (('ﻷ', 'ف'), 12)
1715
+ (('E', 'n'), 12)
1716
+ (('د', 'ْ'), 12)
1717
+ (('l', 'f'), 12)
1718
+ (('ا', 'إ'), 13)
1719
+ (('ء', '؛'), 13)
1720
+ (('A', 'l'), 13)
1721
+ (('ف', '1'), 13)
1722
+ (('ﻷ', 'خ'), 13)
1723
+ (('l', 's'), 13)
1724
+ (('r', 'p'), 13)
1725
+ (('L', 'o'), 13)
1726
+ (('ك', 'ْ'), 13)
1727
+ (('ح', '؛'), 13)
1728
+ (('z', 'i'), 13)
1729
+ (('F', '<E>'), 13)
1730
+ (('g', 't'), 13)
1731
+ (('c', 'c'), 13)
1732
+ (('أ', 'ْ'), 13)
1733
+ (('n', 'y'), 13)
1734
+ (('f', '<E>'), 13)
1735
+ (('I', 'P'), 13)
1736
+ (('A', 'r'), 13)
1737
+ (('u', 'g'), 13)
1738
+ (('O', 'R'), 13)
1739
+ (('C', 'S'), 13)
1740
+ (('ﻻ', 'ز'), 13)
1741
+ (('W', 'A'), 13)
1742
+ (('d', 'r'), 13)
1743
+ (('e', 'o'), 13)
1744
+ (('ا', 'ا'), 13)
1745
+ (('B', 'S'), 13)
1746
+ (('h', 'w'), 13)
1747
+ (('s', 'c'), 13)
1748
+ (('m', 'b'), 13)
1749
+ (('E', 'c'), 13)
1750
+ (('7', 'ف'), 13)
1751
+ (('١', '٢'), 14)
1752
+ (('d', 'm'), 14)
1753
+ (('d', 'u'), 14)
1754
+ (('0', 'م'), 14)
1755
+ (('S', 'h'), 14)
1756
+ (('E', 'x'), 14)
1757
+ (('ﻻ', 'ب'), 14)
1758
+ (('ب', 'ً'), 14)
1759
+ (('U', 'n'), 14)
1760
+ (('j', 'o'), 14)
1761
+ (('i', 'p'), 14)
1762
+ (('َ', 'ظ'), 14)
1763
+ (('ع', '\\'), 14)
1764
+ (('B', 'A'), 14)
1765
+ (('ئ', 'خ'), 14)
1766
+ (('J', 'o'), 14)
1767
+ (('D', 'o'), 14)
1768
+ (('ل', '4'), 14)
1769
+ (('g', 'y'), 14)
1770
+ (('ِ', 'ة'), 14)
1771
+ (('M', 'H'), 14)
1772
+ (('k', 'a'), 14)
1773
+ (('ِ', 'ظ'), 14)
1774
+ (('R', 'P'), 14)
1775
+ (('و', 'ؤ'), 14)
1776
+ (('ج', '\\'), 14)
1777
+ (('"', 'ط'), 14)
1778
+ (('B', 'l'), 14)
1779
+ (('C', 'R'), 14)
1780
+ (('٠', '٪'), 14)
1781
+ (('N', 'H'), 14)
1782
+ (('E', 'a'), 14)
1783
+ (('ْ', 'ف'), 14)
1784
+ (('٥', '<E>'), 14)
1785
+ (('N', 'R'), 14)
1786
+ ((';', '<E>'), 14)
1787
+ (('h', 'm'), 15)
1788
+ (('د', '!'), 15)
1789
+ (('<S>', 'j'), 15)
1790
+ (('ف', '؛'), 15)
1791
+ (('ك', '؛'), 15)
1792
+ (('ا', 'ٌ'), 15)
1793
+ (('ِ', 'أ'), 15)
1794
+ (('ؤ', 'ز'), 15)
1795
+ (('ئ', 'َ'), 15)
1796
+ (('f', 't'), 15)
1797
+ (('f', 'l'), 15)
1798
+ (('T', 'o'), 15)
1799
+ (('س', 'غ'), 15)
1800
+ (('L', 'e'), 15)
1801
+ (('G', 'a'), 15)
1802
+ (('ه', 'ث'), 15)
1803
+ (('ش', '\\'), 15)
1804
+ (('ث', 'خ'), 15)
1805
+ (('W', 'o'), 15)
1806
+ (('c', 'l'), 16)
1807
+ (('٤', '<E>'), 16)
1808
+ (('غ', 'ٌ'), 16)
1809
+ (('ذ', 'ْ'), 16)
1810
+ (('ْ', 'ب'), 16)
1811
+ (('آ', 'ص'), 16)
1812
+ (('<S>', 'ﺇ'), 16)
1813
+ (('ئ', 'ٌ'), 16)
1814
+ (('Z', 'o'), 16)
1815
+ (('<S>', 'ً'), 16)
1816
+ (('T', 'e'), 16)
1817
+ (('z', 'a'), 16)
1818
+ (('أ', 'ِ'), 16)
1819
+ (('ق', '؛'), 16)
1820
+ (('W', 'e'), 16)
1821
+ (('e', 'f'), 16)
1822
+ (('ْ', 'أ'), 16)
1823
+ (('F', 'I'), 16)
1824
+ (('D', 'I'), 16)
1825
+ (('P', 'l'), 16)
1826
+ (('n', 'f'), 16)
1827
+ (('أ', 'ﻻ'), 16)
1828
+ (('b', 'r'), 16)
1829
+ (('C', 'C'), 16)
1830
+ (('A', 'N'), 16)
1831
+ (('E', 'N'), 16)
1832
+ (('<S>', '@'), 17)
1833
+ (('ﻷ', 'ق'), 17)
1834
+ (('م', 'ً'), 17)
1835
+ (('ي', 'ً'), 17)
1836
+ (('\\', '\\'), 17)
1837
+ (('ؤ', 'ة'), 17)
1838
+ (('s', 'l'), 17)
1839
+ (('ب', '3'), 17)
1840
+ (('آ', 'غ'), 17)
1841
+ (('O', 'N'), 17)
1842
+ (('ك', 'ظ'), 17)
1843
+ (('ِ', 'غ'), 17)
1844
+ (('ً', '!'), 17)
1845
+ (('a', 'u'), 17)
1846
+ ((':', '('), 17)
1847
+ (('M', 'E'), 17)
1848
+ (('ف', '2'), 17)
1849
+ (('u', 'i'), 17)
1850
+ (('P', 'A'), 17)
1851
+ (('ض', 'ً'), 17)
1852
+ (('p', 'h'), 17)
1853
+ (('H', '<E>'), 17)
1854
+ (('ـ', 'أ'), 17)
1855
+ (('و', '\\'), 17)
1856
+ (('"', 'ج'), 17)
1857
+ (('H', 'E'), 17)
1858
+ (('ْ', 'ع'), 17)
1859
+ (('١', '٣'), 18)
1860
+ (('C', 'L'), 18)
1861
+ (('َ', 'غ'), 18)
1862
+ (('r', 'v'), 18)
1863
+ (('ت', 'ْ'), 18)
1864
+ (('b', 'u'), 18)
1865
+ (('ْ', 'ي'), 18)
1866
+ (('i', 'z'), 18)
1867
+ (('S', 'p'), 18)
1868
+ (('"', 'ر'), 18)
1869
+ (('V', 'i'), 18)
1870
+ (('U', 'F'), 18)
1871
+ (('A', 's'), 18)
1872
+ (('ك', '!'), 18)
1873
+ (('T', 'H'), 18)
1874
+ (('٪', '<E>'), 18)
1875
+ (('S', 'S'), 18)
1876
+ (('٦', '<E>'), 19)
1877
+ (('G', 'u'), 19)
1878
+ (('غ', 'ث'), 19)
1879
+ (('g', 'o'), 19)
1880
+ (('ُ', 'أ'), 19)
1881
+ (('C', 'B'), 19)
1882
+ (('M', 'I'), 19)
1883
+ (('ئ', 'ٍ'), 19)
1884
+ (('<S>', 'u'), 19)
1885
+ (('ﻹ', 'س'), 19)
1886
+ (('<S>', 'Z'), 19)
1887
+ (('ر', 'ً'), 19)
1888
+ (('D', 'a'), 19)
1889
+ (('ت', '!'), 19)
1890
+ (('H', 'U'), 19)
1891
+ (('T', 'O'), 19)
1892
+ (('a', 'k'), 19)
1893
+ (('D', 'r'), 19)
1894
+ (('L', 'I'), 19)
1895
+ (('١', '٤'), 20)
1896
+ (('N', 'a'), 20)
1897
+ (('t', 'l'), 20)
1898
+ (('"', 'ع'), 20)
1899
+ (('٢', '<E>'), 20)
1900
+ (('u', 'c'), 20)
1901
+ (('ٌ', 'ق'), 20)
1902
+ (('D', '<E>'), 20)
1903
+ (('B', 'u'), 20)
1904
+ (('ِ', 'ئ'), 20)
1905
+ (('I', 'S'), 20)
1906
+ (('f', 'f'), 20)
1907
+ (('#', 't'), 20)
1908
+ (('a', 'v'), 20)
1909
+ (('A', 'n'), 20)
1910
+ (('k', 'i'), 20)
1911
+ (('ا', 'ٍ'), 20)
1912
+ (('ف', 'ْ'), 20)
1913
+ (('F', 'F'), 20)
1914
+ (('T', 'E'), 20)
1915
+ (('E', 'D'), 20)
1916
+ (('f', 'u'), 20)
1917
+ (('q', 'u'), 20)
1918
+ (('ْ', 'ض'), 20)
1919
+ (('ْ', 'ك'), 20)
1920
+ (('"', 'ت'), 21)
1921
+ (('س', 'ْ'), 21)
1922
+ (('U', 'S'), 21)
1923
+ (('ْ', 'س'), 21)
1924
+ (('F', 'r'), 21)
1925
+ (('C', 'h'), 21)
1926
+ (('I', 's'), 21)
1927
+ (('ذ', 'ٌ'), 21)
1928
+ (('ة', ','), 21)
1929
+ (('ّ', 'ظ'), 21)
1930
+ (('ـ', '8'), 21)
1931
+ (('إ', 'ﻻ'), 21)
1932
+ (('ك', '\\'), 21)
1933
+ (('H', 'o'), 21)
1934
+ (('"', 'غ'), 21)
1935
+ (('ظ', 'ع'), 22)
1936
+ (('<S>', 'ﻹ'), 22)
1937
+ (('١', '٠'), 22)
1938
+ (('ه', 'ط'), 22)
1939
+ (('o', 'x'), 22)
1940
+ (('N', 'T'), 22)
1941
+ (('ض', 'ض'), 22)
1942
+ (('ح', 'ْ'), 22)
1943
+ (('ق', 'ْ'), 22)
1944
+ (('P', 'e'), 22)
1945
+ (('d', 'y'), 22)
1946
+ (('g', 'u'), 22)
1947
+ (('ئ', 'غ'), 22)
1948
+ (('ْ', 'ه'), 22)
1949
+ (('ب', 'ْ'), 22)
1950
+ (('ى', '؛'), 22)
1951
+ (('<S>', 'y'), 22)
1952
+ (('O', 'S'), 22)
1953
+ (('غ', 'ج'), 22)
1954
+ (('l', 'u'), 23)
1955
+ (('٣', '<E>'), 23)
1956
+ (('w', 's'), 23)
1957
+ (('p', 'i'), 23)
1958
+ (('M', 'e'), 23)
1959
+ (('ا', 'ْ'), 23)
1960
+ (('ِ', 'ث'), 23)
1961
+ (('ت', 'ً'), 23)
1962
+ (('s', 'm'), 23)
1963
+ (('<S>', '#'), 23)
1964
+ (('ً', '؛'), 23)
1965
+ (('P', 'O'), 23)
1966
+ (('a', 'h'), 24)
1967
+ (('D', 'i'), 24)
1968
+ (('ه', '!'), 24)
1969
+ (('s', 'u'), 24)
1970
+ (('<S>', 'K'), 24)
1971
+ (('ف', 'آ'), 24)
1972
+ (('"', 'ن'), 24)
1973
+ (('ه', '؛'), 24)
1974
+ (('y', 'o'), 24)
1975
+ (('R', '<E>'), 24)
1976
+ (('I', 'T'), 24)
1977
+ (('w', 'w'), 24)
1978
+ (('l', 't'), 25)
1979
+ (('غ', 'ٍ'), 25)
1980
+ (('x', '<E>'), 25)
1981
+ (('P', '<E>'), 25)
1982
+ (('r', 'l'), 25)
1983
+ (('v', 'a'), 25)
1984
+ (('ﻻ', 'ر'), 25)
1985
+ (('R', 'i'), 25)
1986
+ (('p', 'l'), 25)
1987
+ (('ل', '!'), 25)
1988
+ (('ت', '\\'), 25)
1989
+ (('S', 'T'), 25)
1990
+ (('D', 'e'), 25)
1991
+ (('c', 's'), 25)
1992
+ (('١', '٩'), 26)
1993
+ (('ق', '\\'), 26)
1994
+ (('N', 'G'), 26)
1995
+ (('w', 'o'), 26)
1996
+ (('m', 'p'), 26)
1997
+ (('S', 'u'), 26)
1998
+ (('F', 'i'), 26)
1999
+ (('N', 'B'), 26)
2000
+ (('ب', '2'), 27)
2001
+ (('w', 'e'), 27)
2002
+ (('f', 'r'), 27)
2003
+ (('ل', '2'), 27)
2004
+ (('u', '<E>'), 27)
2005
+ (('ب', '1'), 27)
2006
+ (('S', 'e'), 27)
2007
+ (('G', 'o'), 27)
2008
+ (('R', 'E'), 27)
2009
+ (('َ', 'خ'), 27)
2010
+ (('ف', 'ء'), 27)
2011
+ (('U', 'N'), 27)
2012
+ (('u', 'a'), 28)
2013
+ (('M', 'i'), 28)
2014
+ (('و', 'ٌ'), 28)
2015
+ (('B', 'a'), 28)
2016
+ (('e', 'x'), 28)
2017
+ (('t', 'c'), 28)
2018
+ (('و', '9'), 28)
2019
+ (('p', 't'), 28)
2020
+ (('ث', 'ى'), 28)
2021
+ (('ـ', '9'), 28)
2022
+ (('ذ', 'ئ'), 29)
2023
+ (('١', '١'), 29)
2024
+ (('ِ', 'ش'), 29)
2025
+ (('o', 'b'), 29)
2026
+ (('T', 'r'), 29)
2027
+ (('َ', 'ش'), 29)
2028
+ (('ُ', 'ئ'), 29)
2029
+ (('p', 'p'), 29)
2030
+ (('ل', 'ً'), 29)
2031
+ (('c', 'u'), 29)
2032
+ (('١', '<E>'), 30)
2033
+ (('ب', '\\'), 30)
2034
+ (('S', 'y'), 30)
2035
+ (('d', '@'), 30)
2036
+ (('T', 'w'), 30)
2037
+ (('ِ', 'ذ'), 30)
2038
+ (('ﻻ', '<E>'), 30)
2039
+ (('i', 'f'), 30)
2040
+ (('O', '<E>'), 30)
2041
+ (('"', 'ف'), 30)
2042
+ (('o', 'v'), 30)
2043
+ (('m', 'u'), 31)
2044
+ (('c', 'r'), 31)
2045
+ (('C', 'a'), 31)
2046
+ (('F', 'o'), 31)
2047
+ (('<S>', 'ِ'), 31)
2048
+ (('A', 'm'), 31)
2049
+ (('u', 'b'), 31)
2050
+ (('p', '<E>'), 31)
2051
+ (('y', 's'), 31)
2052
+ (('N', 'I'), 31)
2053
+ (('ج', 'ش'), 31)
2054
+ (('س', '\\'), 32)
2055
+ (('g', 'i'), 32)
2056
+ (('s', 'p'), 32)
2057
+ (('"', 'ك'), 32)
2058
+ (('r', 'g'), 32)
2059
+ (('k', 'e'), 32)
2060
+ (('u', 'p'), 32)
2061
+ (('E', '<E>'), 32)
2062
+ (('ء', 'ي'), 32)
2063
+ (('o', 'i'), 32)
2064
+ (('f', 'e'), 32)
2065
+ (('o', 'g'), 32)
2066
+ (('g', 'l'), 32)
2067
+ (('r', 'm'), 32)
2068
+ (('G', 'r'), 33)
2069
+ (('ت', '؛'), 33)
2070
+ (('ـ', '7'), 33)
2071
+ (('i', '<E>'), 33)
2072
+ (('g', 'a'), 33)
2073
+ (('أ', 'ٌ'), 33)
2074
+ (('a', 'b'), 33)
2075
+ (('r', 'u'), 33)
2076
+ (('I', 'C'), 33)
2077
+ (('٠', '<E>'), 34)
2078
+ (('"', 'ح'), 34)
2079
+ (('ك', 'ـ'), 34)
2080
+ (('َ', 'ص'), 34)
2081
+ (('e', 'v'), 34)
2082
+ (('ر', '!'), 34)
2083
+ (('آ', 'ة'), 34)
2084
+ (('e', 'p'), 34)
2085
+ (('m', 'm'), 34)
2086
+ (('"', 'ه'), 34)
2087
+ (('ل', '؛'), 35)
2088
+ (('ّ', 'أ'), 35)
2089
+ (('"', 'ي'), 35)
2090
+ (('َ', 'ز'), 35)
2091
+ (('ه', '\\'), 35)
2092
+ (('b', 'a'), 35)
2093
+ (('e', 'g'), 35)
2094
+ ((':', '{'), 35)
2095
+ (('م', '!'), 36)
2096
+ (('ْ', 'ت'), 36)
2097
+ (('َ', 'ث'), 36)
2098
+ (('<S>', 'V'), 36)
2099
+ (('m', 'o'), 36)
2100
+ (('آ', 'ز'), 37)
2101
+ (('<S>', 'ﻻ'), 37)
2102
+ (('"', 'س'), 37)
2103
+ (('b', 'l'), 37)
2104
+ (('ش', 'ٌ'), 37)
2105
+ (('c', 'y'), 37)
2106
+ (('ب', '؛'), 37)
2107
+ (('َ', 'ط'), 37)
2108
+ (('}', '['), 37)
2109
+ (('<S>', 'O'), 37)
2110
+ (('Y', 'o'), 37)
2111
+ (('ل', '1'), 37)
2112
+ (('ر', 'ْ'), 37)
2113
+ (('*', 'ا'), 37)
2114
+ (('M', 'o'), 38)
2115
+ (('f', 'a'), 38)
2116
+ (('b', 'i'), 38)
2117
+ (('H', 'u'), 38)
2118
+ (('ع', 'ْ'), 38)
2119
+ (('ْ', 'د'), 38)
2120
+ (('غ', 'َ'), 38)
2121
+ (('َ', 'ج'), 38)
2122
+ (('ف', 'ـ'), 38)
2123
+ (('<S>', 'v'), 38)
2124
+ (('u', 'e'), 38)
2125
+ (('N', 'o'), 38)
2126
+ (('0', ','), 38)
2127
+ (('F', 'B'), 39)
2128
+ (('ـ', '6'), 39)
2129
+ (('ﻷ', 'ر'), 39)
2130
+ (('ْ', 'ل'), 39)
2131
+ (('I', 'n'), 39)
2132
+ (('ﻵ', 'ن'), 39)
2133
+ (('r', 'c'), 39)
2134
+ (('ئ', 'ش'), 39)
2135
+ (('خ', 'ٌ'), 40)
2136
+ (('ك', 'ئ'), 40)
2137
+ (('و', 'ْ'), 40)
2138
+ (('<S>', 'Y'), 40)
2139
+ (('r', 'k'), 40)
2140
+ (('َ', 'ذ'), 40)
2141
+ (('D', '@'), 40)
2142
+ (('B', 'r'), 40)
2143
+ (('ؤ', 'ط'), 41)
2144
+ (('ي', '!'), 41)
2145
+ (('S', 'o'), 41)
2146
+ (('ئ', 'ِ'), 41)
2147
+ (('A', 'p'), 41)
2148
+ (('ظ', 'َ'), 41)
2149
+ (('@', 'A'), 41)
2150
+ (('I', 'N'), 41)
2151
+ (('e', 'u'), 41)
2152
+ (('<S>', 'ﻷ'), 42)
2153
+ (('B', 'I'), 42)
2154
+ (('f', 'o'), 42)
2155
+ (('d', 'o'), 42)
2156
+ (('ا', 'ﻵ'), 42)
2157
+ (('n', 'k'), 42)
2158
+ (('r', 'd'), 43)
2159
+ (('l', 'j'), 43)
2160
+ (('F', 'a'), 43)
2161
+ (('ج', 'ى'), 43)
2162
+ (('ش', 'ذ'), 43)
2163
+ (('ء', 'ك'), 43)
2164
+ (('M', 'A'), 43)
2165
+ (('5', '+'), 43)
2166
+ (('ﻷ', 'س'), 44)
2167
+ (('د', 'ً'), 44)
2168
+ (('r', 'r'), 44)
2169
+ (('g', 'r'), 44)
2170
+ (('غ', 'ش'), 45)
2171
+ (('ط', 'ك'), 45)
2172
+ (('ش', 'س'), 45)
2173
+ (('خ', 'ى'), 45)
2174
+ (('َ', 'أ'), 45)
2175
+ (('R', 'e'), 45)
2176
+ ((',', '0'), 45)
2177
+ (('a', 'j'), 46)
2178
+ (('w', 'i'), 46)
2179
+ (('v', 'i'), 46)
2180
+ (('ك', 'آ'), 46)
2181
+ (('l', 'd'), 46)
2182
+ (('<S>', 'J'), 46)
2183
+ (('ا', 'ﻹ'), 46)
2184
+ (('R', 'S'), 46)
2185
+ (('د', '؛'), 47)
2186
+ (('ه', 'ٌ'), 47)
2187
+ (('َ', 'ى'), 47)
2188
+ (('ﻷ', 'و'), 47)
2189
+ (('"', 'و'), 48)
2190
+ (('ٍ', 'ّ'), 48)
2191
+ (('غ', 'ِ'), 48)
2192
+ (('o', 'p'), 48)
2193
+ (('l', 'y'), 48)
2194
+ (('ر', '؛'), 48)
2195
+ (('a', 'p'), 48)
2196
+ (('و', '8'), 49)
2197
+ (('ْ', 'ن'), 49)
2198
+ (('ـ', '5'), 49)
2199
+ (('ا', '!'), 49)
2200
+ (('ِ', 'ت'), 49)
2201
+ (('e', 'b'), 49)
2202
+ (('K', 'K'), 49)
2203
+ (('و', '7'), 49)
2204
+ (('س', 'ذ'), 49)
2205
+ (('<S>', 'r'), 49)
2206
+ (('T', 'i'), 49)
2207
+ (('+', '1'), 49)
2208
+ (('آ', 'ج'), 50)
2209
+ (('@', 'a'), 50)
2210
+ (('ُ', 'ا'), 50)
2211
+ (('ج', 'ٌ'), 50)
2212
+ (('z', 'e'), 50)
2213
+ (('O', 'k'), 50)
2214
+ (('i', 'v'), 50)
2215
+ (('e', 'i'), 50)
2216
+ (('"', 'ب'), 51)
2217
+ (('P', 'r'), 51)
2218
+ (('h', 't'), 51)
2219
+ (('<S>', 'U'), 51)
2220
+ (('ْ', 'ر'), 51)
2221
+ (('o', 'w'), 52)
2222
+ (('t', 'u'), 52)
2223
+ (('ّ', 'ش'), 52)
2224
+ (('A', 'D'), 52)
2225
+ (('ظ', 'ب'), 52)
2226
+ (('ز', 'ٌ'), 52)
2227
+ (('C', 'I'), 53)
2228
+ (('w', 'a'), 53)
2229
+ (('P', 'K'), 53)
2230
+ (('م', '\\'), 53)
2231
+ (('خ', 'ٍ'), 53)
2232
+ (('ِ', 'ص'), 53)
2233
+ (('5', '3'), 53)
2234
+ (('ّ', 'غ'), 54)
2235
+ (('o', 'f'), 54)
2236
+ (('ه', 'ف'), 54)
2237
+ (('<S>', 'e'), 54)
2238
+ (('t', 's'), 54)
2239
+ (('ْ', 'م'), 54)
2240
+ (('a', 'y'), 54)
2241
+ (('<S>', '١'), 55)
2242
+ (('C', 'N'), 55)
2243
+ (('ط', 'خ'), 55)
2244
+ (('P', 'a'), 55)
2245
+ (('ِ', 'ا'), 55)
2246
+ (('a', 'z'), 55)
2247
+ (('B', 'B'), 55)
2248
+ (('أ', 'أ'), 55)
2249
+ (('ل', '\\'), 55)
2250
+ (('N', 'N'), 56)
2251
+ (('<S>', 'g'), 56)
2252
+ (('؟', '؟'), 56)
2253
+ (('r', 'n'), 56)
2254
+ (('r', 'y'), 56)
2255
+ (('7', '1'), 56)
2256
+ (('u', 'l'), 56)
2257
+ (('f', 'i'), 57)
2258
+ (('T', 'h'), 57)
2259
+ (('ض', 'ك'), 57)
2260
+ (('I', 'A'), 57)
2261
+ (('و', '6'), 57)
2262
+ (('d', 'a'), 57)
2263
+ (('A', 'R'), 57)
2264
+ (('"', 'إ'), 58)
2265
+ (('c', 'k'), 58)
2266
+ (('i', 'r'), 58)
2267
+ (('o', 'd'), 58)
2268
+ (('s', 'a'), 59)
2269
+ (('c', '<E>'), 59)
2270
+ (('p', 'r'), 59)
2271
+ (('ي', 'ِ'), 59)
2272
+ (('ك', 'ؤ'), 60)
2273
+ (('h', 'o'), 60)
2274
+ (('b', 'o'), 60)
2275
+ (('W', 'a'), 60)
2276
+ (('ء', 'م'), 60)
2277
+ (('<S>', 'o'), 61)
2278
+ (('ك', 'ٌ'), 61)
2279
+ (('ن', '!'), 62)
2280
+ (('ِ', 'ز'), 62)
2281
+ (('ئ', 'ث'), 62)
2282
+ (('م', '؛'), 62)
2283
+ (('I', '<E>'), 62)
2284
+ (('إ', 'ِ'), 62)
2285
+ (('i', 'b'), 62)
2286
+ (('"', 'أ'), 63)
2287
+ (('ّ', 'خ'), 63)
2288
+ (('ِ', 'س'), 63)
2289
+ (('غ', 'ّ'), 63)
2290
+ (('h', 'a'), 63)
2291
+ (('4', '4'), 64)
2292
+ (('<S>', 'i'), 64)
2293
+ (('<S>', 'h'), 64)
2294
+ (('t', 't'), 65)
2295
+ (('ؤ', 'ب'), 65)
2296
+ (('<S>', '0'), 65)
2297
+ (('8', '3'), 66)
2298
+ (('٠', '١'), 66)
2299
+ (('ه', 'آ'), 66)
2300
+ (('ـ', '4'), 66)
2301
+ (('ِ', 'ج'), 66)
2302
+ (('n', 'o'), 67)
2303
+ (('د', '\\'), 67)
2304
+ (('l', 'o'), 67)
2305
+ (('P', 'o'), 67)
2306
+ (('M', 'a'), 67)
2307
+ (('و', '4'), 67)
2308
+ (('g', 'h'), 67)
2309
+ (('ى', 'ً'), 67)
2310
+ (('3', '9'), 68)
2311
+ (('أ', 'ً'), 68)
2312
+ (('K', '<E>'), 68)
2313
+ (('C', 'o'), 68)
2314
+ (('ي', 'ْ'), 69)
2315
+ (('و', '5'), 69)
2316
+ (('S', 'A'), 69)
2317
+ (('8', '4'), 69)
2318
+ (('؟', '.'), 70)
2319
+ (('ث', 'ٌ'), 70)
2320
+ (('E', 'E'), 70)
2321
+ (('ذ', 'َ'), 71)
2322
+ (('ش', 'ٍ'), 72)
2323
+ (('L', 'i'), 72)
2324
+ (('ل', 'ء'), 72)
2325
+ (('6', '1'), 72)
2326
+ (('َ', 'س'), 72)
2327
+ (('L', 'J'), 72)
2328
+ (('J', 'A'), 72)
2329
+ (('A', 'Z'), 72)
2330
+ (('ي', '؛'), 73)
2331
+ (('٠', '٠'), 73)
2332
+ (('ﻷ', 'م'), 73)
2333
+ (('4', '1'), 73)
2334
+ (('<S>', 'd'), 73)
2335
+ (('Z', 'E'), 73)
2336
+ (('د', 'ز'), 74)
2337
+ (('ر', '\\'), 74)
2338
+ (('4', '3'), 74)
2339
+ (('ط', 'ج'), 74)
2340
+ (('ّ', 'ً'), 75)
2341
+ (('5', '7'), 75)
2342
+ (('ش', 'َ'), 75)
2343
+ (('"', 'ل'), 75)
2344
+ (('o', 't'), 75)
2345
+ (('ك', 'ض'), 75)
2346
+ (('ث', 'ع'), 76)
2347
+ (('س', 'آ'), 76)
2348
+ (('a', 'i'), 76)
2349
+ (('u', 'm'), 76)
2350
+ (('o', 'k'), 76)
2351
+ (('ز', 'غ'), 76)
2352
+ (('s', 'h'), 76)
2353
+ (('S', 't'), 76)
2354
+ (('o', 'c'), 77)
2355
+ (('o', '<E>'), 77)
2356
+ (('5', '8'), 77)
2357
+ (('j', 'a'), 78)
2358
+ (('N', '<E>'), 78)
2359
+ (('4', '9'), 79)
2360
+ (('e', 'w'), 79)
2361
+ (('4', '%'), 79)
2362
+ (('ه', 'ٍ'), 79)
2363
+ (('<S>', 'b'), 79)
2364
+ (('m', 'i'), 79)
2365
+ (('<S>', 'E'), 80)
2366
+ (('6', '%'), 80)
2367
+ (('7', '4'), 80)
2368
+ (('e', 'm'), 80)
2369
+ (('A', 'L'), 80)
2370
+ (('3', '8'), 81)
2371
+ (('َ', 'ض'), 81)
2372
+ (('ـ', '3'), 81)
2373
+ (('ن', 'ً'), 82)
2374
+ (('7', '6'), 82)
2375
+ (('p', 'a'), 82)
2376
+ (('7', '7'), 82)
2377
+ (('n', 'c'), 83)
2378
+ (('ا', '\\'), 83)
2379
+ (('ه', 'س'), 83)
2380
+ (('N', 'e'), 83)
2381
+ (('S', '<E>'), 83)
2382
+ (('ض', 'ٌ'), 84)
2383
+ (('<S>', 'n'), 84)
2384
+ (('u', 't'), 84)
2385
+ (('<S>', 'l'), 84)
2386
+ (('غ', 'ص'), 84)
2387
+ (('e', 'c'), 84)
2388
+ ((',', '<E>'), 84)
2389
+ (('E', 'T'), 84)
2390
+ (('ِ', 'ط'), 84)
2391
+ (('E', 'R'), 84)
2392
+ (('i', 'd'), 85)
2393
+ (('ء', 'ُ'), 85)
2394
+ (('N', 'E'), 85)
2395
+ (('7', '2'), 86)
2396
+ (('ج', 'آ'), 86)
2397
+ (('a', 'g'), 86)
2398
+ (('ِ', 'و'), 87)
2399
+ (('o', 's'), 87)
2400
+ (('6', '6'), 87)
2401
+ (('ة', '!'), 88)
2402
+ (('c', 't'), 89)
2403
+ (('i', 'e'), 89)
2404
+ (('ِ', 'ّ'), 89)
2405
+ (('a', 'd'), 90)
2406
+ (('d', 'i'), 90)
2407
+ (('c', 'h'), 90)
2408
+ (('ِ', 'ض'), 91)
2409
+ (('ن', 'ْ'), 91)
2410
+ (('ل', 'ْ'), 91)
2411
+ (('w', '<E>'), 92)
2412
+ (('s', 'i'), 92)
2413
+ (('s', 'o'), 92)
2414
+ (('6', '3'), 92)
2415
+ (('و', 'ِ'), 92)
2416
+ (('<S>', 'R'), 92)
2417
+ (('ُ', 'ّ'), 92)
2418
+ (('6', '8'), 92)
2419
+ (('ز', 'َ'), 93)
2420
+ (('ف', 'ث'), 93)
2421
+ (('g', 'e'), 93)
2422
+ (('6', '9'), 93)
2423
+ (('ث', 'ِ'), 94)
2424
+ (('8', '7'), 94)
2425
+ (('h', 'i'), 94)
2426
+ (('u', 's'), 95)
2427
+ (('a', 'm'), 95)
2428
+ (('ذ', 'ٍ'), 95)
2429
+ (('i', 'm'), 95)
2430
+ (('خ', 'َ'), 95)
2431
+ (('7', '%'), 96)
2432
+ (('ط', 'ء'), 96)
2433
+ (('9', '%'), 96)
2434
+ (('5', '6'), 96)
2435
+ (('4', '6'), 96)
2436
+ (('5', '9'), 96)
2437
+ (('5', '4'), 97)
2438
+ (('a', 's'), 97)
2439
+ (('3', '4'), 97)
2440
+ (('<S>', 'I'), 97)
2441
+ (('B', 'C'), 98)
2442
+ (('e', 'l'), 99)
2443
+ (('آ', 'ش'), 99)
2444
+ (('i', 'g'), 99)
2445
+ (('b', 'e'), 99)
2446
+ (('ك', 'ٍ'), 99)
2447
+ (('7', '8'), 100)
2448
+ (('س', 'ٌ'), 100)
2449
+ (('3', '1'), 100)
2450
+ (('و', '3'), 100)
2451
+ (('8', '1'), 100)
2452
+ (('6', '2'), 101)
2453
+ (('ن', '؛'), 101)
2454
+ (('َ', 'ك'), 101)
2455
+ (('ث', 'ٍ'), 101)
2456
+ (('R', 'A'), 101)
2457
+ (('ط', 'ٌ'), 102)
2458
+ (('غ', 'ُ'), 102)
2459
+ (('<S>', 'ُ'), 102)
2460
+ (('3', '7'), 103)
2461
+ (('n', 'i'), 103)
2462
+ (('p', 'o'), 103)
2463
+ (('<S>', 'w'), 103)
2464
+ (('َ', 'ة'), 103)
2465
+ (('8', '%'), 104)
2466
+ (('c', 'i'), 104)
2467
+ (('م', 'ْ'), 104)
2468
+ (('ك', 'غ'), 105)
2469
+ (('<S>', 'L'), 105)
2470
+ (('ا', '؛'), 105)
2471
+ (('ِ', 'ح'), 105)
2472
+ (('6', '4'), 105)
2473
+ (('ك', 'ص'), 105)
2474
+ (('و', 'ٍ'), 106)
2475
+ (('<S>', 'm'), 106)
2476
+ (('3', '%'), 106)
2477
+ (('ص', 'َ'), 106)
2478
+ (('o', 'o'), 106)
2479
+ (('ؤ', 'ذ'), 106)
2480
+ (('<S>', 'H'), 106)
2481
+ (('u', 'n'), 106)
2482
+ (('َ', 'و'), 107)
2483
+ (('ق', 'ز'), 107)
2484
+ (('r', 's'), 107)
2485
+ (('ص', 'ٌ'), 107)
2486
+ (('p', 'e'), 107)
2487
+ (('ذ', 'ِ'), 108)
2488
+ (('ُ', 'ي'), 108)
2489
+ (('ز', 'ِ'), 108)
2490
+ (('ك', 'ى'), 109)
2491
+ (('ج', 'ك'), 109)
2492
+ (('ئ', 'ض'), 109)
2493
+ (('i', 'l'), 110)
2494
+ (('s', 's'), 111)
2495
+ (('<S>', 'W'), 111)
2496
+ (('3', '2'), 112)
2497
+ (('<S>', 'D'), 112)
2498
+ (('v', 'e'), 112)
2499
+ (('<S>', '٢'), 113)
2500
+ (('e', 'e'), 113)
2501
+ (('٢', '٠'), 114)
2502
+ (('ن', '\\'), 114)
2503
+ (('8', '8'), 115)
2504
+ (('c', 'a'), 115)
2505
+ (('ض', 'ئ'), 116)
2506
+ (('t', 'y'), 116)
2507
+ (('l', 'l'), 116)
2508
+ (('أ', 'ئ'), 118)
2509
+ (('4', '2'), 119)
2510
+ (('خ', 'ّ'), 120)
2511
+ (('ز', 'ٍ'), 120)
2512
+ (('ؤ', 'ن'), 121)
2513
+ (('l', 'a'), 121)
2514
+ (('h', '<E>'), 121)
2515
+ (('4', '7'), 122)
2516
+ (('e', 'd'), 122)
2517
+ (('ﻷ', 'ن'), 122)
2518
+ (('آ', 'ك'), 122)
2519
+ (('8', '2'), 122)
2520
+ (('<S>', 'f'), 123)
2521
+ (('ط', 'َ'), 123)
2522
+ (('T', '<E>'), 123)
2523
+ (('ظ', 'ّ'), 125)
2524
+ (('ص', 'ك'), 125)
2525
+ (('t', 'o'), 126)
2526
+ (('n', 'a'), 126)
2527
+ (('ّ', 'ص'), 126)
2528
+ (('"', 'م'), 127)
2529
+ (('3', '3'), 127)
2530
+ (('s', 'e'), 129)
2531
+ (('8', '9'), 129)
2532
+ (('1', '%'), 129)
2533
+ (('5', '5'), 131)
2534
+ (('n', 's'), 131)
2535
+ (('u', 'r'), 131)
2536
+ (('ك', 'ط'), 131)
2537
+ (('C', '<E>'), 131)
2538
+ (('8', '6'), 131)
2539
+ (('<S>', 'G'), 132)
2540
+ (('5', '1'), 132)
2541
+ (('e', 'a'), 132)
2542
+ (('o', 'l'), 132)
2543
+ (('2', '9'), 134)
2544
+ (('ج', 'ٍ'), 135)
2545
+ (('ـ', '2'), 136)
2546
+ (('ش', 'ظ'), 137)
2547
+ (('o', 'm'), 138)
2548
+ (('<S>', '*'), 139)
2549
+ (('c', 'o'), 140)
2550
+ (('2', '%'), 140)
2551
+ (('ك', 'خ'), 141)
2552
+ (('7', '3'), 141)
2553
+ (('ِ', 'ع'), 141)
2554
+ (('ز', 'ى'), 142)
2555
+ (('5', '2'), 142)
2556
+ (('ا', 'ّ'), 143)
2557
+ (('ط', 'ِ'), 143)
2558
+ (('ه', 'َ'), 143)
2559
+ (('ل', 'ؤ'), 144)
2560
+ (('َ', 'ي'), 144)
2561
+ (('8', '5'), 145)
2562
+ (('3', '6'), 146)
2563
+ (('i', 'a'), 148)
2564
+ (('ِ', 'ه'), 148)
2565
+ (('m', '<E>'), 148)
2566
+ (('7', '9'), 148)
2567
+ (('ش', 'ِ'), 149)
2568
+ (('d', 'e'), 149)
2569
+ (('ه', 'ّ'), 150)
2570
+ (('ّ', 'ج'), 150)
2571
+ (('k', '<E>'), 150)
2572
+ (('خ', 'خ'), 150)
2573
+ (('و', 'ﻻ'), 151)
2574
+ (('َ', 'ح'), 151)
2575
+ (('e', 't'), 152)
2576
+ (('r', 't'), 152)
2577
+ (('<S>', 't'), 152)
2578
+ (('ر', 'ذ'), 153)
2579
+ (('ّ', 'ٌ'), 153)
2580
+ (('ب', 'ى'), 153)
2581
+ (('ظ', 'ِ'), 156)
2582
+ (('ذ', 'ع'), 156)
2583
+ (('ض', 'ّ'), 157)
2584
+ (('ئ', 'ص'), 157)
2585
+ (('و', '1'), 157)
2586
+ (('ج', 'َ'), 157)
2587
+ (('<S>', 's'), 158)
2588
+ (('t', 'r'), 158)
2589
+ (('<S>', 'p'), 158)
2590
+ (('َ', 'ق'), 159)
2591
+ (('ح', 'ٌ'), 161)
2592
+ (('ة', '؛'), 163)
2593
+ (('غ', 'ى'), 163)
2594
+ (('َ', 'ف'), 165)
2595
+ (('ّ', 'ط'), 166)
2596
+ (('ض', 'َ'), 167)
2597
+ (('ط', 'ّ'), 168)
2598
+ (('ق', 'ج'), 168)
2599
+ (('ق', 'ظ'), 169)
2600
+ (('ّ', 'ث'), 170)
2601
+ (('ئ', 'ذ'), 170)
2602
+ (('ي', '\\'), 171)
2603
+ (('g', '<E>'), 172)
2604
+ (('َ', 'ه'), 173)
2605
+ (('t', 'a'), 173)
2606
+ (('إ', 'ظ'), 174)
2607
+ (('9', '3'), 174)
2608
+ (('ؤ', 'ى'), 174)
2609
+ (('t', 'h'), 174)
2610
+ (('خ', 'ِ'), 177)
2611
+ (('ِ', 'ك'), 178)
2612
+ (('د', 'ج'), 178)
2613
+ (('m', 'a'), 179)
2614
+ (('غ', 'ه'), 179)
2615
+ (('2', '8'), 179)
2616
+ (('ث', 'غ'), 180)
2617
+ (('<S>', 'B'), 180)
2618
+ (('6', '5'), 180)
2619
+ (('ث', 'َ'), 181)
2620
+ (('ظ', 'ُ'), 181)
2621
+ (('n', 'd'), 181)
2622
+ (('ً', 'ا'), 182)
2623
+ (('<S>', 'a'), 182)
2624
+ (('ذ', 'ى'), 182)
2625
+ (('د', 'غ'), 183)
2626
+ (('ف', 'ؤ'), 184)
2627
+ (('خ', 'ج'), 184)
2628
+ (('<S>', 'c'), 186)
2629
+ (('n', 'g'), 187)
2630
+ (('؟', '!'), 187)
2631
+ (('c', 'e'), 188)
2632
+ (('ء', 'ن'), 188)
2633
+ (('2', '6'), 189)
2634
+ (('ز', 'ُ'), 190)
2635
+ (('l', 'i'), 190)
2636
+ (('2', '7'), 190)
2637
+ (('ِ', 'ق'), 190)
2638
+ (('h', 'e'), 193)
2639
+ (('ط', 'ٍ'), 193)
2640
+ (('ذ', 'ّ'), 194)
2641
+ (('ة', '\\'), 195)
2642
+ (('o', 'u'), 196)
2643
+ (('a', 'c'), 196)
2644
+ (('ر', 'ء'), 196)
2645
+ (('n', 'e'), 197)
2646
+ (('ء', 'َ'), 197)
2647
+ (('ّ', 'س'), 199)
2648
+ (('ج', 'ِ'), 199)
2649
+ (('ش', 'ّ'), 200)
2650
+ (('ا', 'َ'), 200)
2651
+ (('4', '5'), 201)
2652
+ (('ِ', 'ف'), 201)
2653
+ (('آ', 'د'), 202)
2654
+ (('ث', 'أ'), 202)
2655
+ (('A', '<E>'), 202)
2656
+ (('<S>', 'F'), 203)
2657
+ (('ث', 'ك'), 205)
2658
+ (('0', '2'), 205)
2659
+ (('د', 'ؤ'), 207)
2660
+ (('i', 'c'), 208)
2661
+ (('ط', 'د'), 208)
2662
+ (('َ', 'ع'), 210)
2663
+ (('ب', 'ظ'), 211)
2664
+ (('أ', 'َ'), 211)
2665
+ (('ط', 'ؤ'), 213)
2666
+ (('ه', 'ظ'), 213)
2667
+ (('l', 'e'), 213)
2668
+ (('ذ', 'ف'), 214)
2669
+ (('m', 'e'), 214)
2670
+ (('9', '1'), 214)
2671
+ (('r', 'o'), 215)
2672
+ (('ق', 'ح'), 216)
2673
+ (('َ', 'د'), 218)
2674
+ (('ب', 'ء'), 218)
2675
+ (('ـ', '1'), 219)
2676
+ (('a', '<E>'), 220)
2677
+ (('ز', 'أ'), 220)
2678
+ (('0', '4'), 222)
2679
+ (('ط', 'ش'), 224)
2680
+ (('!', '!'), 224)
2681
+ (('i', 'o'), 226)
2682
+ (('i', 's'), 226)
2683
+ (('7', '5'), 226)
2684
+ (('ّ', 'ز'), 227)
2685
+ (('ط', 'غ'), 227)
2686
+ (('ص', 'ٍ'), 230)
2687
+ (('آ', 'و'), 231)
2688
+ (('ْ', '<E>'), 231)
2689
+ (('<S>', 'T'), 232)
2690
+ (('ن', 'ث'), 233)
2691
+ (('ّ', 'ٍ'), 233)
2692
+ (('ش', 'آ'), 233)
2693
+ (('ي', 'ٌ'), 233)
2694
+ (('e', 's'), 234)
2695
+ (('r', 'i'), 235)
2696
+ (('2', '3'), 235)
2697
+ (('ؤ', 'ج'), 236)
2698
+ (('ح', 'ح'), 237)
2699
+ (('س', 'ٍ'), 241)
2700
+ (('،', '<E>'), 242)
2701
+ (('ق', 'ٌ'), 245)
2702
+ (('.', '،'), 245)
2703
+ (('r', 'e'), 246)
2704
+ (('9', '2'), 250)
2705
+ (('n', 't'), 250)
2706
+ (('<S>', 'M'), 251)
2707
+ (('<S>', 'N'), 252)
2708
+ (('ح', 'ٍ'), 252)
2709
+ (('ن', 'ٌ'), 253)
2710
+ (('ه', 'ق'), 254)
2711
+ (('<S>', 'A'), 254)
2712
+ (('ُ', 'ظ'), 254)
2713
+ (('ت', 'ّ'), 255)
2714
+ (('ث', 'ث'), 256)
2715
+ (('ع', 'ّ'), 256)
2716
+ (('o', 'r'), 261)
2717
+ (('َ', 'ب'), 261)
2718
+ (('ِ', 'ي'), 262)
2719
+ (('ض', 'ُ'), 265)
2720
+ (('ك', 'إ'), 267)
2721
+ (('d', '<E>'), 270)
2722
+ (('د', 'ش'), 270)
2723
+ (('و', '2'), 271)
2724
+ (('ي', 'ٍ'), 274)
2725
+ (('ض', 'ٍ'), 275)
2726
+ (('"', 'ا'), 276)
2727
+ (('ح', 'ِ'), 277)
2728
+ (('l', '<E>'), 278)
2729
+ (('e', 'n'), 279)
2730
+ (('و', 'َ'), 281)
2731
+ (('r', 'a'), 283)
2732
+ (('ا', 'ﻷ'), 284)
2733
+ (('a', 'r'), 284)
2734
+ (('ح', 'ّ'), 285)
2735
+ (('ث', 'ف'), 285)
2736
+ (('i', 't'), 287)
2737
+ (('ز', 'خ'), 287)
2738
+ (('ّ', 'ض'), 288)
2739
+ (('0', '7'), 288)
2740
+ (('ذ', 'ق'), 289)
2741
+ (('ب', 'ؤ'), 291)
2742
+ (('آ', 'ف'), 292)
2743
+ (('ص', 'ِ'), 293)
2744
+ (('ئ', 'ط'), 294)
2745
+ (('ف', 'ٌ'), 295)
2746
+ (('<S>', 'S'), 296)
2747
+ (('ق', 'ك'), 298)
2748
+ (('ح', 'َ'), 298)
2749
+ (('3', '5'), 300)
2750
+ (('r', '<E>'), 304)
2751
+ (('<S>', 'C'), 305)
2752
+ (('ر', 'آ'), 307)
2753
+ (('s', 't'), 311)
2754
+ (('ع', 'ٌ'), 312)
2755
+ (('ا', 'ُ'), 314)
2756
+ (('ف', 'ّ'), 315)
2757
+ (('ج', 'ف'), 315)
2758
+ (('و', 'ئ'), 317)
2759
+ (('َ', 'ا'), 320)
2760
+ (('a', 't'), 322)
2761
+ (('َ', 'ر'), 327)
2762
+ (('ي', 'ى'), 330)
2763
+ (('ء', 'ِ'), 331)
2764
+ (('ذ', 'م'), 332)
2765
+ (('ئ', 'س'), 332)
2766
+ (('<S>', 'P'), 333)
2767
+ (('ط', 'س'), 333)
2768
+ (('ّ', 'ك'), 337)
2769
+ (('آ', 'ي'), 337)
2770
+ (('ي', 'َ'), 339)
2771
+ (('ت', 'آ'), 343)
2772
+ (('ص', 'ق'), 344)
2773
+ (('إ', 'ك'), 347)
2774
+ (('6', '7'), 348)
2775
+ (('t', 'e'), 349)
2776
+ (('a', 'l'), 350)
2777
+ (('ُ', 'ؤ'), 353)
2778
+ (('ك', 'ج'), 355)
2779
+ (('a', 'n'), 356)
2780
+ (('ذ', 'خ'), 357)
2781
+ (('y', '<E>'), 359)
2782
+ (('0', '9'), 366)
2783
+ (('0', '8'), 366)
2784
+ (('ط', 'ُ'), 369)
2785
+ (('و', 'ُ'), 371)
2786
+ (('ج', 'ج'), 373)
2787
+ (('n', '<E>'), 379)
2788
+ (('ة', 'َ'), 381)
2789
+ (('2', '4'), 381)
2790
+ (('0', '5'), 382)
2791
+ (('t', 'i'), 383)
2792
+ (('ط', 'ح'), 384)
2793
+ (('َ', 'ّ'), 384)
2794
+ (('ؤ', 'ر'), 389)
2795
+ (('ك', 'ق'), 389)
2796
+ (('غ', 'ف'), 390)
2797
+ (('ج', 'ث'), 391)
2798
+ (('س', 'ِ'), 391)
2799
+ (('<S>', '8'), 392)
2800
+ (('i', 'n'), 396)
2801
+ (('ض', 'ج'), 397)
2802
+ (('4', '8'), 399)
2803
+ (('<S>', '9'), 400)
2804
+ (('0', '6'), 407)
2805
+ (('آ', 'ب'), 413)
2806
+ (('إ', 'ه'), 414)
2807
+ (('ب', 'ٌ'), 418)
2808
+ (('ُ', 'ذ'), 419)
2809
+ (('ّ', 'و'), 421)
2810
+ (('9', '5'), 422)
2811
+ (('َ', 'م'), 424)
2812
+ (('ء', 'ٌ'), 425)
2813
+ (('ص', 'ُ'), 426)
2814
+ (('5', '%'), 427)
2815
+ (('ض', 'ِ'), 427)
2816
+ (('<S>', '7'), 432)
2817
+ (('ء', 'و'), 433)
2818
+ (('ّ', 'ى'), 434)
2819
+ (('ن', 'ئ'), 437)
2820
+ (('ؤ', '<E>'), 442)
2821
+ (('ب', 'ـ'), 445)
2822
+ (('o', 'n'), 446)
2823
+ (('آ', 'ه'), 448)
2824
+ (('ذ', 'ُ'), 448)
2825
+ (('ق', 'ّ'), 452)
2826
+ (('<S>', '6'), 454)
2827
+ (('ص', 'ّ'), 454)
2828
+ (('خ', 'ه'), 456)
2829
+ (('ظ', 'ت'), 465)
2830
+ (('ُ', 'ز'), 465)
2831
+ (('s', '<E>'), 467)
2832
+ (('9', '4'), 474)
2833
+ (('م', 'ٌ'), 476)
2834
+ (('t', '<E>'), 478)
2835
+ (('ص', 'خ'), 478)
2836
+ (('ئ', 'ز'), 479)
2837
+ (('ز', 'ك'), 482)
2838
+ (('د', 'ِ'), 484)
2839
+ (('ز', 'ج'), 487)
2840
+ (('ز', 'ف'), 491)
2841
+ (('1', '8'), 497)
2842
+ (('ز', 'ز'), 498)
2843
+ (('9', '0'), 508)
2844
+ (('أ', 'ى'), 511)
2845
+ (('9', '7'), 517)
2846
+ (('!', '<E>'), 519)
2847
+ (('ء', 'ٍ'), 520)
2848
+ (('2', '2'), 522)
2849
+ (('ظ', 'ى'), 523)
2850
+ (('ف', 'ِ'), 532)
2851
+ (('ث', 'ّ'), 534)
2852
+ (('ت', 'ئ'), 534)
2853
+ (('ن', 'ِ'), 538)
2854
+ (('ّ', 'ف'), 543)
2855
+ (('e', 'r'), 548)
2856
+ (('َ', 'ت'), 556)
2857
+ (('خ', 'ة'), 557)
2858
+ (('آ', 'ذ'), 569)
2859
+ (('ِ', 'م'), 570)
2860
+ (('ش', 'ئ'), 571)
2861
+ (('<S>', '4'), 572)
2862
+ (('ق', 'َ'), 576)
2863
+ (('ّ', 'ع'), 591)
2864
+ (('ث', 'ُ'), 591)
2865
+ (('آ', 'ث'), 593)
2866
+ (('ك', 'ح'), 597)
2867
+ (('م', 'آ'), 599)
2868
+ (('ُ', 'ض'), 599)
2869
+ (('ِ', 'ر'), 604)
2870
+ (('ُ', 'ث'), 606)
2871
+ (('9', '6'), 609)
2872
+ (('ّ', 'ب'), 610)
2873
+ (('ن', 'ؤ'), 612)
2874
+ (('ع', 'َ'), 618)
2875
+ (('ب', 'ئ'), 622)
2876
+ (('ج', 'ّ'), 624)
2877
+ (('ق', 'ٍ'), 628)
2878
+ (('خ', 'ز'), 635)
2879
+ (('ك', 'ع'), 640)
2880
+ (('خ', 'ُ'), 641)
2881
+ (('ش', 'ُ'), 642)
2882
+ (('ص', 'ت'), 645)
2883
+ (('ّ', 'ح'), 648)
2884
+ (('ب', 'ِ'), 648)
2885
+ (('9', '8'), 656)
2886
+ (('س', 'ّ'), 659)
2887
+ (('ِ', 'د'), 675)
2888
+ (('ز', 'ئ'), 677)
2889
+ (('ع', 'ٍ'), 679)
2890
+ (('َ', 'ل'), 682)
2891
+ (('0', '3'), 686)
2892
+ (('ُ', 'غ'), 688)
2893
+ (('ذ', 'ة'), 688)
2894
+ (('1', '7'), 692)
2895
+ (('ع', 'ِ'), 701)
2896
+ (('2', '1'), 707)
2897
+ (('د', 'ٌ'), 708)
2898
+ (('ة', 'ُ'), 709)
2899
+ (('<S>', '5'), 719)
2900
+ (('ّ', 'ي'), 721)
2901
+ (('8', '0'), 724)
2902
+ (('ء', 'ل'), 728)
2903
+ (('ئ', 'ح'), 729)
2904
+ (('ف', 'ُ'), 730)
2905
+ (('ف', 'َ'), 731)
2906
+ (('د', 'ح'), 735)
2907
+ (('1', '6'), 740)
2908
+ (('ف', 'ٍ'), 746)
2909
+ (('س', 'َ'), 752)
2910
+ (('e', '<E>'), 762)
2911
+ (('آ', 'ت'), 764)
2912
+ (('ب', 'آ'), 769)
2913
+ (('آ', 'س'), 769)
2914
+ (('ئ', 'ك'), 770)
2915
+ (('9', '9'), 771)
2916
+ (('ر', 'ِ'), 775)
2917
+ (('ل', 'ٌ'), 787)
2918
+ (('خ', 'ن'), 792)
2919
+ (('7', '0'), 794)
2920
+ (('ّ', 'ق'), 801)
2921
+ (('ث', 'ه'), 802)
2922
+ (('ف', 'خ'), 810)
2923
+ (('ؤ', 'ق'), 821)
2924
+ (('ت', 'ٌ'), 823)
2925
+ (('ج', 'ُ'), 823)
2926
+ (('ّ', 'ُ'), 837)
2927
+ (('ب', 'ٍ'), 838)
2928
+ (('ن', 'ٍ'), 848)
2929
+ (('<S>', '3'), 850)
2930
+ (('ب', 'ز'), 851)
2931
+ (('ب', 'َ'), 852)
2932
+ (('أ', 'ؤ'), 859)
2933
+ (('7', '<E>'), 860)
2934
+ (('ء', 'ه'), 861)
2935
+ (('ه', 'ش'), 863)
2936
+ (('آ', 'ر'), 864)
2937
+ (('ش', 'ى'), 868)
2938
+ (('ت', 'َ'), 887)
2939
+ (('ؤ', 'ه'), 891)
2940
+ (('ف', 'ف'), 919)
2941
+ (('ِ', 'ن'), 919)
2942
+ (('؛', '<E>'), 923)
2943
+ (('9', '<E>'), 927)
2944
+ (('س', 'ئ'), 929)
2945
+ (('ِ', 'ب'), 929)
2946
+ (('ك', 'ِ'), 937)
2947
+ (('6', '0'), 943)
2948
+ (('ز', 'ق'), 953)
2949
+ (('8', '<E>'), 955)
2950
+ (('ل', 'ئ'), 956)
2951
+ (('ض', 'خ'), 958)
2952
+ (('ِ', 'ل'), 959)
2953
+ (('د', 'َ'), 961)
2954
+ (('ب', 'ّ'), 973)
2955
+ (('س', 'خ'), 973)
2956
+ (('ّ', 'ن'), 986)
2957
+ (('ح', 'ى'), 992)
2958
+ (('ظ', 'ف'), 994)
2959
+ (('2', '5'), 995)
2960
+ (('و', 'آ'), 999)
2961
+ (('ك', 'ّ'), 1002)
2962
+ (('4', '0'), 1014)
2963
+ (('ّ', 'د'), 1022)
2964
+ (('ئ', 'و'), 1030)
2965
+ (('ج', 'غ'), 1033)
2966
+ (('ر', 'َ'), 1034)
2967
+ (('ل', 'ِ'), 1041)
2968
+ (('ـ', '<E>'), 1058)
2969
+ (('ز', 'ح'), 1060)
2970
+ (('ّ', 'ِ'), 1078)
2971
+ (('<S>', '\\'), 1087)
2972
+ (('ُ', 'و'), 1094)
2973
+ (('ز', 'ّ'), 1101)
2974
+ (('1', '5'), 1118)
2975
+ (('ؤ', 'خ'), 1128)
2976
+ (('س', 'ى'), 1128)
2977
+ (('1', '3'), 1129)
2978
+ (('ُ', 'ط'), 1131)
2979
+ (('د', 'ُ'), 1132)
2980
+ (('ط', 'ى'), 1147)
2981
+ (('"', '<E>'), 1158)
2982
+ (('غ', 'ذ'), 1159)
2983
+ (('ء', 'ً'), 1164)
2984
+ (('5', '<E>'), 1166)
2985
+ (('6', '<E>'), 1178)
2986
+ (('د', 'ء'), 1179)
2987
+ (('إ', 'ث'), 1189)
2988
+ (('م', 'ٍ'), 1191)
2989
+ (('ج', 'أ'), 1194)
2990
+ (('ج', 'ذ'), 1198)
2991
+ (('غ', 'س'), 1200)
2992
+ (('ر', 'ٌ'), 1212)
2993
+ (('إ', 'ز'), 1220)
2994
+ (('ذ', 'ت'), 1223)
2995
+ (('ي', 'ظ'), 1236)
2996
+ (('ُ', 'ه'), 1247)
2997
+ (('ذ', 'ج'), 1252)
2998
+ (('ر', 'ُ'), 1252)
2999
+ (('ه', 'ى'), 1253)
3000
+ (('إ', 'غ'), 1254)
3001
+ (('م', 'ِ'), 1259)
3002
+ (('ؤ', 'ش'), 1264)
3003
+ (('ه', 'ه'), 1268)
3004
+ (('ر', 'خ'), 1273)
3005
+ (('ئ', 'ع'), 1276)
3006
+ (('ّ', '��'), 1282)
3007
+ (('ق', 'ِ'), 1285)
3008
+ (('ف', 'ئ'), 1296)
3009
+ (('ك', 'ك'), 1302)
3010
+ (('ب', 'ُ'), 1321)
3011
+ (('ح', 'ط'), 1329)
3012
+ (('ح', 'ُ'), 1330)
3013
+ (('ط', 'ئ'), 1333)
3014
+ (('إ', 'ت'), 1333)
3015
+ (('2', '<E>'), 1363)
3016
+ (('ّ', 'م'), 1418)
3017
+ (('ش', 'ج'), 1424)
3018
+ (('ز', 'ت'), 1431)
3019
+ (('خ', 'ش'), 1432)
3020
+ (('ُ', 'ج'), 1450)
3021
+ (('0', '%'), 1457)
3022
+ (('1', '4'), 1459)
3023
+ (('4', '<E>'), 1463)
3024
+ (('غ', 'ن'), 1463)
3025
+ (('ط', 'ط'), 1470)
3026
+ (('و', 'ّ'), 1480)
3027
+ (('ص', 'ى'), 1488)
3028
+ (('1', '2'), 1492)
3029
+ (('ل', 'ُ'), 1500)
3030
+ (('ؤ', 'م'), 1504)
3031
+ (('.', '<E>'), 1538)
3032
+ (('ز', 'د'), 1542)
3033
+ (('ُ', 'ص'), 1549)
3034
+ (('ص', 'ص'), 1557)
3035
+ (('ا', 'ظ'), 1563)
3036
+ (('أ', 'ظ'), 1565)
3037
+ (('ف', 'ى'), 1576)
3038
+ (('ن', 'ل'), 1588)
3039
+ (('ُ', 'ك'), 1606)
3040
+ (('ل', 'َ'), 1646)
3041
+ (('ش', 'غ'), 1647)
3042
+ (('ط', 'أ'), 1649)
3043
+ (('3', '0'), 1651)
3044
+ (('ق', 'ُ'), 1655)
3045
+ (('ح', 'ذ'), 1659)
3046
+ (('أ', 'ذ'), 1664)
3047
+ (('5', '0'), 1671)
3048
+ (('ض', 'ن'), 1686)
3049
+ (('ت', 'ِ'), 1689)
3050
+ (('ه', 'ض'), 1707)
3051
+ (('ع', 'ُ'), 1709)
3052
+ (('ُ', 'ف'), 1724)
3053
+ (('3', '<E>'), 1728)
3054
+ (('ء', 'ة'), 1732)
3055
+ (('ب', 'ف'), 1740)
3056
+ (('ر', 'ٍ'), 1754)
3057
+ (('أ', 'ة'), 1768)
3058
+ (('ض', 'ط'), 1778)
3059
+ (('<S>', '.'), 1783)
3060
+ (('د', 'ٍ'), 1801)
3061
+ (('أ', 'ض'), 1809)
3062
+ (('ُ', 'خ'), 1813)
3063
+ (('ء', 'ت'), 1824)
3064
+ (('آ', 'م'), 1833)
3065
+ (('ع', 'ذ'), 1841)
3066
+ (('ف', 'غ'), 1846)
3067
+ (('ص', 'غ'), 1847)
3068
+ (('ق', 'ذ'), 1848)
3069
+ (('ض', 'ف'), 1848)
3070
+ (('ش', 'ؤ'), 1860)
3071
+ (('ص', 'ه'), 1862)
3072
+ (('ن', 'أ'), 1869)
3073
+ (('ئ', 'ق'), 1871)
3074
+ (('ض', 'ى'), 1872)
3075
+ (('ّ', 'ل'), 1883)
3076
+ (('خ', 'ض'), 1884)
3077
+ (('ل', 'ـ'), 1886)
3078
+ (('ف', 'ز'), 1905)
3079
+ (('ا', 'ؤ'), 1914)
3080
+ (('غ', 'ض'), 1916)
3081
+ (('ش', 'ط'), 1939)
3082
+ (('ة', 'ِ'), 1941)
3083
+ (('ّ', 'ه'), 1952)
3084
+ (('ر', 'ث'), 1957)
3085
+ (('ئ', 'ج'), 1969)
3086
+ (('ك', 'َ'), 1976)
3087
+ (('ط', 'ت'), 1997)
3088
+ (('ب', 'ث'), 2000)
3089
+ (('ظ', 'ن'), 2002)
3090
+ (('ص', 'ط'), 2002)
3091
+ (('ط', 'م'), 2014)
3092
+ (('ؤ', 'ث'), 2025)
3093
+ (('ُ', 'ش'), 2047)
3094
+ (('د', 'ئ'), 2061)
3095
+ (('ُ', 'ب'), 2062)
3096
+ (('ّ', 'ر'), 2072)
3097
+ (('ّ', 'ت'), 2073)
3098
+ (('ع', 'ى'), 2078)
3099
+ (('ف', 'ذ'), 2084)
3100
+ (('ب', 'ج'), 2090)
3101
+ (('ذ', 'و'), 2091)
3102
+ (('1', '1'), 2093)
3103
+ (('1', '<E>'), 2093)
3104
+ (('ز', 'ه'), 2097)
3105
+ (('ش', 'ة'), 2102)
3106
+ (('ذ', 'ب'), 2150)
3107
+ (('ث', 'ت'), 2150)
3108
+ (('م', 'ذ'), 2188)
3109
+ (('غ', 'ب'), 2192)
3110
+ (('س', 'ُ'), 2193)
3111
+ (('إ', 'ف'), 2195)
3112
+ (('ه', 'ك'), 2198)
3113
+ (('َ', 'ن'), 2204)
3114
+ (('خ', 'س'), 2229)
3115
+ (('ُ', 'د'), 2247)
3116
+ (('ض', 'ت'), 2263)
3117
+ (('ح', 'ش'), 2267)
3118
+ (('ف', 'م'), 2269)
3119
+ (('ؤ', 'د'), 2290)
3120
+ (('ع', 'ث'), 2300)
3121
+ (('ر', 'ّ'), 2319)
3122
+ (('ف', 'ب'), 2320)
3123
+ (('ت', 'ة'), 2321)
3124
+ (('%', '<E>'), 2329)
3125
+ (('ش', 'ح'), 2344)
3126
+ (('ف', 'أ'), 2345)
3127
+ (('ث', 'ب'), 2352)
3128
+ (('\\', '"'), 2371)
3129
+ (('غ', 'ت'), 2389)
3130
+ (('ك', 'ش'), 2407)
3131
+ (('ف', 'د'), 2412)
3132
+ (('1', '0'), 2441)
3133
+ (('ّ', 'َ'), 2483)
3134
+ (('ُ', 'ت'), 2485)
3135
+ (('ظ', 'و'), 2558)
3136
+ (('ع', 'ج'), 2567)
3137
+ (('م', 'أ'), 2576)
3138
+ (('ّ', 'ا'), 2591)
3139
+ (('ؤ', 'ك'), 2594)
3140
+ (('ل', 'ٍ'), 2616)
3141
+ (('ئ', 'ن'), 2625)
3142
+ (('و', 'ظ'), 2656)
3143
+ (('ب', 'خ'), 2659)
3144
+ (('م', 'ظ'), 2720)
3145
+ (('م', 'ّ'), 2793)
3146
+ (('ة', 'ٌ'), 2804)
3147
+ (('د', 'ّ'), 2815)
3148
+ (('م', 'ئ'), 2839)
3149
+ (('ج', 'س'), 2850)
3150
+ (('ف', 'ط'), 2898)
3151
+ (('ع', 'ص'), 2909)
3152
+ (('ّ', 'ة'), 2939)
3153
+ (('إ', 'ض'), 2941)
3154
+ (('ب', 'ذ'), 2950)
3155
+ (('ي', 'غ'), 2969)
3156
+ (('أ', 'غ'), 2972)
3157
+ (('ع', 'ظ'), 2991)
3158
+ (('م', 'ى'), 2993)
3159
+ (('ت', 'ؤ'), 3043)
3160
+ (('ل', 'ظ'), 3062)
3161
+ (('م', 'َ'), 3066)
3162
+ (('ك', 'ه'), 3087)
3163
+ (('ج', 'ح'), 3127)
3164
+ (('ُ', 'ح'), 3144)
3165
+ (('ك', 'أ'), 3153)
3166
+ (('ن', 'َ'), 3155)
3167
+ (('د', 'ب'), 3182)
3168
+ (('خ', 'ف'), 3185)
3169
+ (('ك', 'ُ'), 3197)
3170
+ (('1', '9'), 3255)
3171
+ (('ز', 'ن'), 3263)
3172
+ (('ر', 'ز'), 3266)
3173
+ (('ب', 'ض'), 3284)
3174
+ (('س', 'ح'), 3287)
3175
+ (('إ', 'ش'), 3325)
3176
+ (('ر', 'ؤ'), 3332)
3177
+ (('ف', 'ش'), 3361)
3178
+ (('ف', 'ح'), 3361)
3179
+ (('غ', 'ة'), 3365)
3180
+ (('ئ', 'ت'), 3366)
3181
+ (('ئ', 'د'), 3420)
3182
+ (('ض', 'ب'), 3424)
3183
+ (('ت', 'ذ'), 3484)
3184
+ (('غ', 'د'), 3495)
3185
+ (('ض', 'غ'), 3501)
3186
+ (('إ', 'ب'), 3509)
3187
+ (('ئ', 'ب'), 3515)
3188
+ (('خ', 'م'), 3526)
3189
+ (('ئ', '<E>'), 3526)
3190
+ (('و', 'ء'), 3530)
3191
+ (('ن', 'ُ'), 3545)
3192
+ (('ُ', 'ق'), 3567)
3193
+ (('ح', 'ه'), 3597)
3194
+ (('ت', 'ٍ'), 3604)
3195
+ (('م', 'غ'), 3696)
3196
+ (('ط', 'ه'), 3758)
3197
+ (('ف', 'ج'), 3793)
3198
+ (('غ', '<E>'), 3793)
3199
+ (('ر', 'ش'), 3816)
3200
+ (('ن', 'خ'), 3825)
3201
+ (('ق', 'ق'), 3840)
3202
+ (('ش', 'ل'), 3852)
3203
+ (('غ', 'و'), 3873)
3204
+ (('ؤ', 'ي'), 3879)
3205
+ (('ش', 'ف'), 3891)
3206
+ (('ح', 'ج'), 3920)
3207
+ (('أ', 'ُ'), 3926)
3208
+ (('ه', 'ز'), 3934)
3209
+ (('ج', 'ئ'), 3959)
3210
+ (('ض', 'ه'), 3960)
3211
+ (('ظ', 'ه'), 3992)
3212
+ (('إ', 'ص'), 3995)
3213
+ (('ئ', 'ه'), 4048)
3214
+ (('ك', 'ف'), 4102)
3215
+ (('ح', 'ض'), 4125)
3216
+ (('ُ', 'س'), 4184)
3217
+ (('ذ', 'ر'), 4271)
3218
+ (('ن', 'غ'), 4279)
3219
+ (('ت', 'ث'), 4369)
3220
+ (('ز', 'ع'), 4381)
3221
+ (('<S>', 'ظ'), 4412)
3222
+ (('ُ', 'ع'), 4483)
3223
+ (('0', '1'), 4485)
3224
+ (('ظ', '<E>'), 4517)
3225
+ (('غ', 'ط'), 4522)
3226
+ (('ب', 'ص'), 4542)
3227
+ (('ن', 'ض'), 4546)
3228
+ (('م', 'ض'), 4547)
3229
+ (('ش', 'أ'), 4569)
3230
+ (('ق', 'ش'), 4595)
3231
+ (('ه', 'ت'), 4621)
3232
+ (('ي', 'ؤ'), 4708)
3233
+ (('ه', 'ِ'), 4720)
3234
+ (('ُ', 'ل'), 4736)
3235
+ (('ش', 'ق'), 4765)
3236
+ (('ي', 'أ'), 4776)
3237
+ (('ي', 'ذ'), 4835)
3238
+ (('ُ', 'م'), 4878)
3239
+ (('و', 'ذ'), 4918)
3240
+ (('ا', 'غ'), 4919)
3241
+ (('ر', 'ل'), 4920)
3242
+ (('ق', 'س'), 4940)
3243
+ (('ُ', 'ر'), 4994)
3244
+ (('ق', 'ى'), 4999)
3245
+ (('ح', 'ث'), 5153)
3246
+ (('ع', 'ف'), 5226)
3247
+ (('آ', 'ل'), 5229)
3248
+ (('ث', 'ن'), 5267)
3249
+ (('ك', 'د'), 5293)
3250
+ (('ق', 'م'), 5297)
3251
+ (('ث', 'ة'), 5336)
3252
+ (('ف', 'إ'), 5357)
3253
+ (('ص', 'م'), 5359)
3254
+ (('ز', 'ء'), 5388)
3255
+ (('ف', 'ص'), 5454)
3256
+ (('غ', 'م'), 5480)
3257
+ (('ر', 'ط'), 5481)
3258
+ (('ر', 'ص'), 5498)
3259
+ (('ت', 'ظ'), 5600)
3260
+ (('ل', 'ّ'), 5615)
3261
+ (('م', 'ز'), 5625)
3262
+ (('ش', 'ن'), 5628)
3263
+ (('ؤ', 'ت'), 5652)
3264
+ (('<S>', '1'), 5661)
3265
+ (('ب', 'غ'), 5667)
3266
+ (('ظ', 'ة'), 5721)
3267
+ (('0', '<E>'), 5799)
3268
+ (('إ', 'ج'), 5801)
3269
+ (('د', 'ق'), 5820)
3270
+ (('ء', 'ا'), 5857)
3271
+ (('ث', 'ق'), 5862)
3272
+ (('ك', 'ز'), 5865)
3273
+ (('ق', 'ه'), 5884)
3274
+ (('ئ', 'ف'), 5895)
3275
+ (('و', 'خ'), 5900)
3276
+ (('ظ', 'ل'), 5933)
3277
+ (('و', 'ش'), 5950)
3278
+ (('إ', 'خ'), 5966)
3279
+ (('ز', 'ل'), 5971)
3280
+ (('إ', 'ح'), 5974)
3281
+ (('ع', 'ك'), 5986)
3282
+ (('س', 'ج'), 6024)
3283
+ (('ز', 'و'), 6031)
3284
+ (('ط', 'ف'), 6054)
3285
+ (('ط', 'ع'), 6160)
3286
+ (('ي', 'ّ'), 6176)
3287
+ (('ي', 'ئ'), 6237)
3288
+ (('ر', 'ر'), 6295)
3289
+ (('و', 'غ'), 6332)
3290
+ (('ن', 'ز'), 6372)
3291
+ (('ز', 'ر'), 6406)
3292
+ (('ُ', 'ن'), 6469)
3293
+ (('س', 'ق'), 6501)
3294
+ (('ب', 'إ'), 6567)
3295
+ (('ه', 'ج'), 6590)
3296
+ (('ة', 'ٍ'), 6623)
3297
+ (('غ', 'ز'), 6644)
3298
+ (('ص', 'ع'), 6654)
3299
+ (('ه', 'ؤ'), 6727)
3300
+ (('ت', 'ض'), 6768)
3301
+ (('و', 'و'), 6778)
3302
+ (('ك', 'س'), 6779)
3303
+ (('ش', 'د'), 6799)
3304
+ (('أ', 'ث'), 6825)
3305
+ (('ش', 'م'), 6872)
3306
+ (('ح', 'ظ'), 6988)
3307
+ (('ت', 'ز'), 7028)
3308
+ (('إ', 'ط'), 7082)
3309
+ (('ر', 'غ'), 7084)
3310
+ (('ض', 'ل'), 7133)
3311
+ (('ع', 'ط'), 7211)
3312
+ (('ق', 'ن'), 7218)
3313
+ (('ش', 'و'), 7225)
3314
+ (('ئ', 'ة'), 7237)
3315
+ (('ف', 'ن'), 7304)
3316
+ (('ف', 'ظ'), 7348)
3317
+ (('ش', 'ت'), 7377)
3318
+ (('ع', 'ز'), 7394)
3319
+ (('خ', 'ذ'), 7444)
3320
+ (('ه', 'ب'), 7480)
3321
+ (('ؤ', 'س'), 7494)
3322
+ (('ه', 'ُ'), 7495)
3323
+ (('0', '0'), 7547)
3324
+ (('إ', 'م'), 7623)
3325
+ (('ئ', 'ا'), 7670)
3326
+ (('ن', 'ى'), 7698)
3327
+ (('ح', 'ب'), 7739)
3328
+ (('غ', 'ل'), 7772)
3329
+ (('ض', 'د'), 7784)
3330
+ (('س', 'ف'), 7960)
3331
+ (('ؤ', 'ا'), 7968)
3332
+ (('ش', 'ب'), 8009)
3333
+ (('ب', 'ب'), 8034)
3334
+ (('ص', 'ن'), 8060)
3335
+ (('س', 'س'), 8098)
3336
+ (('ؤ', 'ل'), 8136)
3337
+ (('ذ', 'ن'), 8179)
3338
+ (('إ', 'ق'), 8218)
3339
+ (('ي', 'ص'), 8261)
3340
+ (('ت', 'ُ'), 8273)
3341
+ (('ش', 'خ'), 8274)
3342
+ (('ل', 'ز'), 8372)
3343
+ (('ح', 'ف'), 8387)
3344
+ (('ك', 'ذ'), 8461)
3345
+ (('ة', 'ً'), 8543)
3346
+ (('س', 'د'), 8544)
3347
+ (('ز', 'ة'), 8595)
3348
+ (('أ', 'ز'), 8651)
3349
+ (('<S>', '2'), 8681)
3350
+ (('ئ', 'ر'), 8693)
3351
+ (('إ', 'د'), 8811)
3352
+ (('ا', 'ة'), 8813)
3353
+ (('ي', 'ء'), 8858)
3354
+ (('أ', 'د'), 8966)
3355
+ (('ذ', 'ك'), 9058)
3356
+ (('ن', 'ّ'), 9126)
3357
+ (('2', '0'), 9160)
3358
+ (('ض', 'م'), 9356)
3359
+ (('ن', 'ر'), 9385)
3360
+ (('ر', 'م'), 9447)
3361
+ (('خ', 'د'), 9479)
3362
+ (('ّ', '<E>'), 9557)
3363
+ (('ن', 'ك'), 9601)
3364
+ (('ؤ', 'و'), 9708)
3365
+ (('د', 'أ'), 9736)
3366
+ (('د', 'ى'), 9792)
3367
+ (('خ', '<E>'), 9804)
3368
+ (('ج', 'ع'), 9921)
3369
+ (('ئ', 'م'), 9929)
3370
+ (('ظ', 'م'), 9998)
3371
+ (('ٌ', '<E>'), 10118)
3372
+ (('ن', 'ش'), 10201)
3373
+ (('ي', 'ز'), 10309)
3374
+ (('ن', 'ج'), 10322)
3375
+ (('أ', 'ف'), 10380)
3376
+ (('م', 'ف'), 10394)
3377
+ (('ب', 'ط'), 10669)
3378
+ (('د', 'س'), 10679)
3379
+ (('ا', 'ث'), 10905)
3380
+ (('أ', '<E>'), 10914)
3381
+ (('ن', 'ذ'), 10948)
3382
+ (('أ', 'ط'), 11118)
3383
+ (('ج', 'ة'), 11149)
3384
+ (('خ', 'ب'), 11164)
3385
+ (('ئ', 'ل'), 11320)
3386
+ (('م', 'ط'), 11322)
3387
+ (('د', 'ت'), 11332)
3388
+ (('ص', 'ة'), 11346)
3389
+ (('ف', 'ك'), 11505)
3390
+ (('ع', 'ق'), 11530)
3391
+ (('ي', 'ُ'), 11621)
3392
+ (('ظ', 'ي'), 11625)
3393
+ (('إ', 'ر'), 11629)
3394
+ (('ع', 'ش'), 11886)
3395
+ (('ص', 'ب'), 11901)
3396
+ (('ه', 'ة'), 11952)
3397
+ (('ض', 'ر'), 12023)
3398
+ (('خ', 'و'), 12144)
3399
+ (('ُ', '<E>'), 12179)
3400
+ (('ض', 'ة'), 12196)
3401
+ (('ب', 'س'), 12323)
3402
+ (('و', 'ة'), 12328)
3403
+ (('ث', 'م'), 12405)
3404
+ (('ل', 'ض'), 12444)
3405
+ (('ف', 'ض'), 12460)
3406
+ (('ض', 'ح'), 12604)
3407
+ (('آ', 'خ'), 12607)
3408
+ (('<S>', 'ز'), 12793)
3409
+ (('س', 'ه'), 12806)
3410
+ (('ت', 'غ'), 12851)
3411
+ (('خ', 'ص'), 12860)
3412
+ (('ح', 'ص'), 12947)
3413
+ (('د', 'ل'), 13047)
3414
+ (('ق', 'ص'), 13118)
3415
+ (('ر', 'أ'), 13137)
3416
+ (('س', 'أ'), 13303)
3417
+ (('ي', 'ث'), 13464)
3418
+ (('أ', 'ش'), 13475)
3419
+ (('و', 'ث'), 13560)
3420
+ (('ع', 'ه'), 13853)
3421
+ (('أ', 'ج'), 13864)
3422
+ (('س', 'ؤ'), 14026)
3423
+ (('ن', 'م'), 14052)
3424
+ (('ِ', '<E>'), 14058)
3425
+ (('ز', 'ب'), 14088)
3426
+ (('ن', 'ن'), 14177)
3427
+ (('ب', 'ك'), 14201)
3428
+ (('ن', 'ص'), 14270)
3429
+ (('و', 'ى'), 14357)
3430
+ (('ص', 'ح'), 14359)
3431
+ (('<S>', 'آ'), 14452)
3432
+ (('س', 'ع'), 14583)
3433
+ (('د', 'ف'), 14603)
3434
+ (('َ', '<E>'), 14616)
3435
+ (('غ', 'ا'), 14672)
3436
+ (('أ', 'ص'), 14751)
3437
+ (('د', 'د'), 14762)
3438
+ (('م', 'ُ'), 14799)
3439
+ (('ص', '<E>'), 14824)
3440
+ (('أ', 'ب'), 15010)
3441
+ (('أ', 'ه'), 15175)
3442
+ (('ح', 'س'), 15188)
3443
+ (('ر', 'ع'), 15191)
3444
+ (('م', 'خ'), 15210)
3445
+ (('<S>', 'ث'), 15459)
3446
+ (('د', 'خ'), 15478)
3447
+ (('ظ', 'ر'), 15479)
3448
+ (('ص', 'د'), 15513)
3449
+ (('ز', 'م'), 15569)
3450
+ (('د', 'ك'), 15578)
3451
+ (('غ', 'ر'), 15620)
3452
+ (('ش', 'ه'), 15654)
3453
+ (('ص', 'ف'), 15880)
3454
+ (('و', 'إ'), 15939)
3455
+ (('ت', 'أ'), 16004)
3456
+ (('إ', 'ع'), 16144)
3457
+ (('س', 'ة'), 16161)
3458
+ (('ي', 'خ'), 16323)
3459
+ (('ج', 'ز'), 16508)
3460
+ (('ج', 'ت'), 16576)
3461
+ (('ر', 'ن'), 16688)
3462
+ (('ع', 'س'), 16957)
3463
+ (('خ', 'ت'), 17025)
3464
+ (('ص', 'ي'), 17227)
3465
+ (('ف', 'و'), 17520)
3466
+ (('ا', 'ش'), 17541)
3467
+ (('ح', 'ز'), 17658)
3468
+ (('أ', 'ت'), 17679)
3469
+ (('ث', 'ا'), 17690)
3470
+ (('ي', 'ط'), 17882)
3471
+ (('م', 'ب'), 17893)
3472
+ (('ض', 'ع'), 18010)
3473
+ (('م', 'ؤ'), 18425)
3474
+ (('ن', 'ب'), 18431)
3475
+ (('و', 'ز'), 18436)
3476
+ (('أ', 'ق'), 18459)
3477
+ (('و', 'ص'), 18519)
3478
+ (('خ', 'ي'), 18533)
3479
+ (('ا', 'ز'), 18554)
3480
+ (('ط', 'و'), 18604)
3481
+ (('ج', 'ب'), 18634)
3482
+ (('ك', 'ة'), 18679)
3483
+ (('<S>', 'ض'), 18711)
3484
+ (('ق', 'ض'), 18858)
3485
+ (('م', 'م'), 18993)
3486
+ (('ج', 'ن'), 19040)
3487
+ (('ل', 'غ'), 19152)
3488
+ (('ض', 'و'), 19220)
3489
+ (('د', 'ه'), 19424)
3490
+ (('ث', 'و'), 19707)
3491
+ (('ف', 'س'), 19743)
3492
+ (('ف', 'ه'), 19809)
3493
+ (('ث', 'ر'), 19933)
3494
+ (('ق', 'ع'), 20168)
3495
+ (('ر', 'ق'), 20201)
3496
+ (('ب', 'ش'), 20332)
3497
+ (('ط', 'ب'), 20382)
3498
+ (('ط', 'ل'), 20506)
3499
+ (('ب', 'ت'), 20624)
3500
+ (('و', 'ط'), 20665)
3501
+ (('ط', 'ة'), 20720)
3502
+ (('خ', 'ط'), 20802)
3503
+ (('ت', 'ش'), 20973)
3504
+ (('أ', 'ل'), 21143)
3505
+ (('ق', 'ف'), 21299)
3506
+ (('ا', 'ذ'), 21425)
3507
+ (('ع', 'ض'), 21672)
3508
+ (('ر', 'س'), 21742)
3509
+ (('ه', 'ر'), 21889)
3510
+ (('ا', 'خ'), 21946)
3511
+ (('د', 'ع'), 21954)
3512
+ (('د', 'ن'), 21964)
3513
+ (('ر', 'ح'), 21972)
3514
+ (('ف', 'ة'), 22072)
3515
+ (('ط', 'ن'), 22454)
3516
+ (('س', 'ط'), 22558)
3517
+ (('ف', 'ل'), 22824)
3518
+ (('ك', 'ب'), 22832)
3519
+ (('ر', 'د'), 22931)
3520
+ (('ط', 'ق'), 23156)
3521
+ (('ت', 'ط'), 23284)
3522
+ (('و', 'ك'), 23946)
3523
+ (('ج', 'ل'), 23987)
3524
+ (('ح', 'ن'), 24093)
3525
+ (('أ', 'ح'), 24127)
3526
+ (('ن', 'ط'), 24371)
3527
+ (('م', 'ث'), 24387)
3528
+ (('ٍ', '<E>'), 24392)
3529
+ (('ز', '<E>'), 24411)
3530
+ (('ب', 'ح'), 24711)
3531
+ (('ث', 'ل'), 24720)
3532
+ (('د', 'ث'), 24840)
3533
+ (('ت', 'ى'), 24872)
3534
+ (('س', 'ك'), 24881)
3535
+ (('إ', 'ي'), 24902)
3536
+ (('س', 'ن'), 24904)
3537
+ (('ف', 'ت'), 24951)
3538
+ (('ت', 'ت'), 25133)
3539
+ (('ت', 'د'), 25341)
3540
+ (('ب', 'و'), 25868)
3541
+ (('ح', 'ة'), 25977)
3542
+ (('ف', 'ع'), 26010)
3543
+ (('و', 'ح'), 26020)
3544
+ (('ص', 'و'), 26136)
3545
+ (('ذ', '<E>'), 26231)
3546
+ (('إ', 'ذ'), 26290)
3547
+ (('ر', 'ى'), 26407)
3548
+ (('ب', 'ق'), 26441)
3549
+ (('ش', 'ع'), 26695)
3550
+ (('ت', 'س'), 26714)
3551
+ (('ا', 'ض'), 26759)
3552
+ (('ف', 'ق'), 26779)
3553
+ (('ق', 'ط'), 26779)
3554
+ (('ت', 'ج'), 27226)
3555
+ (('ش', '<E>'), 27490)
3556
+ (('ي', 'ش'), 27623)
3557
+ (('ك', 'ت'), 27644)
3558
+ (('ن', 'ة'), 27960)
3559
+ (('ل', 'ث'), 28106)
3560
+ (('ا', 'ص'), 28260)
3561
+ (('ج', 'ر'), 28317)
3562
+ (('ن', 'ق'), 28348)
3563
+ (('أ', 'ك'), 28705)
3564
+ (('ش', 'ي'), 28875)
3565
+ (('ز', 'ا'), 28910)
3566
+ (('.', '.'), 28976)
3567
+ (('أ', 'ع'), 29157)
3568
+ (('ز', 'ي'), 29283)
3569
+ (('<S>', 'غ'), 29459)
3570
+ (('ب', 'أ'), 29538)
3571
+ (('أ', 'ر'), 29622)
3572
+ (('ر', 'ئ'), 29675)
3573
+ (('م', 'ه'), 29689)
3574
+ (('ر', 'ت'), 29693)
3575
+ (('ف', 'ر'), 29838)
3576
+ (('ي', 'ض'), 30040)
3577
+ (('ل', 'ص'), 30060)
3578
+ (('ج', 'ه'), 30160)
3579
+ (('ر', 'ج'), 30238)
3580
+ (('ر', 'ض'), 30338)
3581
+ (('ن', 'ح'), 30408)
3582
+ (('ر', 'ه'), 30469)
3583
+ (('ب', 'م'), 30765)
3584
+ (('ك', 'ث'), 30772)
3585
+ (('ت', 'خ'), 30833)
3586
+ (('ه', 'ل'), 31036)
3587
+ (('ن', 'ع'), 31572)
3588
+ (('غ', 'ي'), 31657)
3589
+ (('ح', 'م'), 31773)
3590
+ (('م', 'ق'), 31801)
3591
+ (('ب', 'ن'), 32221)
3592
+ (('ه', 'د'), 32300)
3593
+ (('ت', 'ص'), 32328)
3594
+ (('ج', '<E>'), 32543)
3595
+ (('ع', 'ة'), 32599)
3596
+ (('س', 'ر'), 32626)
3597
+ (('ث', 'ي'), 32683)
3598
+ (('آ', 'ن'), 32829)
3599
+ (('ج', 'و'), 32843)
3600
+ (('ل', 'ط'), 32919)
3601
+ (('ت', 'ك'), 32976)
3602
+ (('ظ', 'ا'), 33045)
3603
+ (('ض', 'ي'), 33149)
3604
+ (('<S>', 'ذ'), 33287)
3605
+ (('ب', 'ة'), 33424)
3606
+ (('ع', 'و'), 33495)
3607
+ (('ن', 'ف'), 33672)
3608
+ (('ي', 'ح'), 33786)
3609
+ (('س', 'م'), 34067)
3610
+ (('ر', 'ف'), 34284)
3611
+ (('ت', 'ب'), 34299)
3612
+ (('ق', 'ب'), 34340)
3613
+ (('ن', 'د'), 34453)
3614
+ (('ا', 'ط'), 35083)
3615
+ (('ح', 'ك'), 35341)
3616
+ (('أ', 'خ'), 35493)
3617
+ (('م', 'ص'), 35852)
3618
+ (('د', 'ر'), 36168)
3619
+ (('م', 'ش'), 36172)
3620
+ (('و', 'س'), 36188)
3621
+ (('ح', 'ل'), 36471)
3622
+ (('ل', 'خ'), 36946)
3623
+ (('ذ', 'ل'), 36955)
3624
+ (('ي', 'ج'), 37266)
3625
+ (('و', 'ض'), 37266)
3626
+ (('ت', 'ف'), 37270)
3627
+ (('ي', 'ك'), 37422)
3628
+ (('ق', 'ت'), 37743)
3629
+ (('إ', 'س'), 37850)
3630
+ (('س', 'ب'), 38092)
3631
+ (('ص', 'ل'), 38111)
3632
+ (('ح', 'و'), 38192)
3633
+ (('و', 'ف'), 38613)
3634
+ (('ا', 'و'), 38644)
3635
+ (('و', 'أ'), 38715)
3636
+ (('ب', 'ه'), 38825)
3637
+ (('ح', 'ق'), 38868)
3638
+ (('م', 'د'), 39013)
3639
+ (('و', 'ت'), 39136)
3640
+ (('ي', 'ف'), 39182)
3641
+ (('ل', 'آ'), 39202)
3642
+ (('<S>', 'ص'), 39393)
3643
+ (('م', 'ج'), 39469)
3644
+ (('ج', 'د'), 39745)
3645
+ (('خ', 'ر'), 39911)
3646
+ (('م', 'ك'), 40078)
3647
+ (('ا', 'ج'), 40268)
3648
+ (('و', 'ج'), 40320)
3649
+ (('ج', 'م'), 40408)
3650
+ (('إ', 'ن'), 40466)
3651
+ (('ق', 'ل'), 40656)
3652
+ (('ش', 'ا'), 40906)
3653
+ (('ق', 'ر'), 40919)
3654
+ (('خ', 'ا'), 41482)
3655
+ (('ش', 'ك'), 41649)
3656
+ (('ط', '<E>'), 42320)
3657
+ (('و', '<E>'), 42433)
3658
+ (('ج', 'ي'), 42534)
3659
+ (('ث', '<E>'), 43681)
3660
+ (('ذ', 'ي'), 43712)
3661
+ (('ص', 'ا'), 43846)
3662
+ (('ح', 'ي'), 43908)
3663
+ (('ا', 'ه'), 43988)
3664
+ (('ن', 'س'), 44469)
3665
+ (('ط', 'ر'), 44987)
3666
+ (('ت', 'ن'), 45094)
3667
+ (('ض', '<E>'), 45379)
3668
+ (('ح', 'ر'), 45480)
3669
+ (('ت', 'ل'), 45750)
3670
+ (('ص', 'ر'), 46081)
3671
+ (('ي', 'ي'), 46091)
3672
+ (('ش', 'ر'), 46188)
3673
+ (('و', 'ه'), 46196)
3674
+ (('<S>', 'ط'), 46216)
3675
+ (('ا', 'ي'), 46933)
3676
+ (('م', 'ح'), 47374)
3677
+ (('ي', 'ب'), 47524)
3678
+ (('ن', 'و'), 47835)
3679
+ (('و', 'ع'), 47875)
3680
+ (('ل', 'ر'), 48024)
3681
+ (('ط', 'ا'), 48280)
3682
+ (('ل', 'ذ'), 48903)
3683
+ (('د', 'م'), 49380)
3684
+ (('ض', 'ا'), 49679)
3685
+ (('ب', 'د'), 50073)
3686
+ (('ع', 'ت'), 50729)
3687
+ (('ع', 'ب'), 50805)
3688
+ (('ط', 'ي'), 51057)
3689
+ (('ع', 'ي'), 52209)
3690
+ (('ن', 'ظ'), 53133)
3691
+ (('<S>', 'خ'), 53365)
3692
+ (('ه', 'ي'), 53604)
3693
+ (('ج', 'ا'), 53658)
3694
+ (('ح', 'ت'), 53841)
3695
+ (('أ', 'س'), 54316)
3696
+ (('ق', 'ة'), 54342)
3697
+ (('ا', 'ح'), 54562)
3698
+ (('ك', 'م'), 54906)
3699
+ (('ب', 'ل'), 55309)
3700
+ (('ئ', 'ي'), 55689)
3701
+ (('خ', 'ل'), 56881)
3702
+ (('و', 'ي'), 56950)
3703
+ (('ي', 'ت'), 57657)
3704
+ (('و', 'ق'), 57684)
3705
+ (('<S>', 'ش'), 57806)
3706
+ (('ت', 'ا'), 57812)
3707
+ (('ف', 'ا'), 58040)
3708
+ (('ي', 'ه'), 58488)
3709
+ (('ي', 'و'), 58570)
3710
+ (('ك', 'ر'), 59020)
3711
+ (('ا', 'ف'), 59112)
3712
+ (('م', 'ت'), 59179)
3713
+ (('و', 'د'), 59183)
3714
+ (('ر', 'و'), 59594)
3715
+ (('ب', 'ر'), 60301)
3716
+ (('و', 'ب'), 60340)
3717
+ (('ل', 'ش'), 60378)
3718
+ (('س', 'ل'), 61565)
3719
+ (('ت', 'ع'), 62993)
3720
+ (('ح', '<E>'), 63626)
3721
+ (('<S>', 'ر'), 64517)
3722
+ (('ك', 'ي'), 65122)
3723
+ (('أ', 'ي'), 65175)
3724
+ (('س', 'و'), 66058)
3725
+ (('ه', 'ن'), 66302)
3726
+ (('ت', 'ه'), 67130)
3727
+ (('ك', 'و'), 67356)
3728
+ (('ع', 'م'), 67489)
3729
+ (('ت', 'ر'), 67963)
3730
+ (('ه', 'و'), 68091)
3731
+ (('ق', 'د'), 68346)
3732
+ (('ل', 'ج'), 69024)
3733
+ (('م', 'س'), 69605)
3734
+ (('ي', 'ل'), 70100)
3735
+ (('ي', 'ق'), 70752)
3736
+ (('ل', 'ف'), 71580)
3737
+ (('ق', 'ي'), 72602)
3738
+ (('ع', 'ر'), 72634)
3739
+ (('ب', 'ع'), 72750)
3740
+ (('ا', 'ك'), 72913)
3741
+ (('م', 'ة'), 73480)
3742
+ (('ع', 'د'), 74875)
3743
+ (('د', 'ة'), 75299)
3744
+ (('م', 'ر'), 76022)
3745
+ (('ل', 'ب'), 76739)
3746
+ (('ح', 'ا'), 77321)
3747
+ (('م', 'ل'), 77825)
3748
+ (('ت', 'و'), 78496)
3749
+ (('ت', 'م'), 78718)
3750
+ (('ر', 'ك'), 78794)
3751
+ (('ك', 'ل'), 79941)
3752
+ (('ق', 'و'), 81791)
3753
+ (('ا', 'ئ'), 83557)
3754
+ (('ر', 'ب'), 83560)
3755
+ (('ا', 'ع'), 83722)
3756
+ (('ل', 'إ'), 84132)
3757
+ (('ي', 'س'), 84224)
3758
+ (('<S>', 'ج'), 84599)
3759
+ (('ل', 'ه'), 84895)
3760
+ (('ك', 'ن'), 84940)
3761
+ (('ت', 'ق'), 85161)
3762
+ (('<S>', 'د'), 85340)
3763
+ (('س', 'ا'), 86745)
3764
+ (('ا', 'ق'), 87217)
3765
+ (('ح', 'د'), 87927)
3766
+ (('ت', 'ي'), 87951)
3767
+ (('ت', 'ح'), 89745)
3768
+ (('ذ', 'ه'), 90369)
3769
+ (('ا', 'ء'), 90648)
3770
+ (('ا', 'ب'), 90665)
3771
+ (('ه', 'م'), 90771)
3772
+ (('أ', 'و'), 90838)
3773
+ (('ل', 'ة'), 90953)
3774
+ (('م', 'و'), 92022)
3775
+ (('أ', 'م'), 92504)
3776
+ (('ء', '<E>'), 95712)
3777
+ (('إ', 'ل'), 95971)
3778
+ (('ن', 'ت'), 96142)
3779
+ (('ي', 'م'), 97145)
3780
+ (('ر', 'ة'), 97758)
3781
+ (('ا', 'د'), 99903)
3782
+ (('ن', 'ه'), 100313)
3783
+ (('ل', 'ن'), 102168)
3784
+ (('د', 'و'), 102497)
3785
+ (('س', '<E>'), 105303)
3786
+ (('ل', 'د'), 105941)
3787
+ (('ك', 'ا'), 107186)
3788
+ (('ل', 'و'), 107946)
3789
+ (('ق', '<E>'), 108013)
3790
+ (('<S>', 'ق'), 108078)
3791
+ (('ل', 'ق'), 109826)
3792
+ (('ا', 'ً'), 111118)
3793
+ (('و', 'م'), 113858)
3794
+ (('ي', 'ع'), 114463)
3795
+ (('م', 'ي'), 115027)
3796
+ (('ق', 'ا'), 115281)
3797
+ (('<S>', 'ف'), 116005)
3798
+ (('د', 'ا'), 119116)
3799
+ (('ي', 'د'), 119543)
3800
+ (('ل', 'ل'), 120398)
3801
+ (('ً', '<E>'), 121043)
3802
+ (('م', 'ع'), 123365)
3803
+ (('س', 'ت'), 125455)
3804
+ (('ع', 'ا'), 125797)
3805
+ (('ف', '<E>'), 126587)
3806
+ (('د', 'ي'), 128414)
3807
+ (('ا', 'س'), 130671)
3808
+ (('ذ', 'ا'), 135404)
3809
+ (('ل', 'ع'), 136992)
3810
+ (('ع', '<E>'), 138692)
3811
+ (('ب', 'ي'), 139421)
3812
+ (('ل', 'ح'), 140871)
3813
+ (('<S>', 'ح'), 143769)
3814
+ (('<S>', 'س'), 145621)
3815
+ (('و', 'ن'), 145791)
3816
+ (('ك', '<E>'), 145973)
3817
+ (('و', 'ر'), 151656)
3818
+ (('ع', 'ن'), 152434)
3819
+ (('ل', 'ك'), 152840)
3820
+ (('<S>', 'ك'), 153311)
3821
+ (('ل', 'س'), 159552)
3822
+ (('<S>', 'ن'), 159620)
3823
+ (('ا', 'م'), 168238)
3824
+ (('ه', 'ذ'), 174878)
3825
+ (('ب', '<E>'), 178581)
3826
+ (('ب', 'ا'), 179758)
3827
+ (('ي', 'ر'), 181296)
3828
+ (('س', 'ي'), 183088)
3829
+ (('ا', 'ر'), 185782)
3830
+ (('ه', 'ا'), 191033)
3831
+ (('ن', 'ي'), 191744)
3832
+ (('ل', 'ى'), 199006)
3833
+ (('ل', 'ت'), 199594)
3834
+ (('ر', 'ي'), 201186)
3835
+ (('<S>', 'إ'), 202492)
3836
+ (('ل', 'أ'), 203564)
3837
+ (('ع', 'ل'), 206365)
3838
+ (('ي', 'ا'), 215250)
3839
+ (('ي', 'ن'), 222906)
3840
+ (('<S>', 'ه'), 225399)
3841
+ (('و', 'ل'), 228429)
3842
+ (('ر', 'ا'), 242341)
3843
+ (('ا', 'ن'), 255891)
3844
+ (('ا', 'ت'), 259781)
3845
+ (('ل', 'ي'), 265994)
3846
+ (('ن', 'ا'), 266138)
3847
+ (('ه', '<E>'), 271383)
3848
+ (('<S>', 'ع'), 272858)
3849
+ (('أ', 'ن'), 279001)
3850
+ (('د', '<E>'), 289189)
3851
+ (('و', 'ا'), 293819)
3852
+ (('<S>', 'ل'), 299706)
3853
+ (('م', 'ا'), 303138)
3854
+ (('ى', '<E>'), 305259)
3855
+ (('م', 'ن'), 319586)
3856
+ (('<S>', 'ت'), 320590)
3857
+ (('ي', 'ة'), 329484)
3858
+ (('ل', 'ا'), 338940)
3859
+ (('<S>', 'ي'), 340253)
3860
+ (('م', '<E>'), 345988)
3861
+ (('ف', 'ي'), 346841)
3862
+ (('ت', '<E>'), 352473)
3863
+ (('ر', '<E>'), 360868)
3864
+ (('<S>', 'ب'), 361427)
3865
+ (('<S>', 'أ'), 376708)
3866
+ (('<S>', 'م'), 385040)
3867
+ (('ل', '<E>'), 387044)
3868
+ (('ل', 'م'), 402476)
3869
+ (('ي', '<E>'), 512357)
3870
+ (('<S>', 'و'), 588627)
3871
+ (('ن', '<E>'), 593836)
3872
+ (('ا', '<E>'), 709880)
3873
+ (('ة', '<E>'), 1007705)
3874
+ (('<S>', 'ا'), 1881650)
3875
+ (('ا', 'ل'), 2153155)
check_bnb_install.py ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import bitsandbytes as bnb
2
+ import torch
3
+
4
+ p = torch.nn.Parameter(torch.rand(10,10).cuda())
5
+ a = torch.rand(10,10).cuda()
6
+
7
+ p1 = p.data.sum().item()
8
+
9
+ adam = bnb.optim.Adam([p])
10
+
11
+ out = a*p
12
+ loss = out.sum()
13
+ loss.backward()
14
+ adam.step()
15
+
16
+ p2 = p.data.sum().item()
17
+
18
+ assert p1 != p2
19
+ print('SUCCESS!')
20
+ print('Installation was successful!')
check_bnb_install.py.1 ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import bitsandbytes as bnb
2
+ import torch
3
+
4
+ p = torch.nn.Parameter(torch.rand(10,10).cuda())
5
+ a = torch.rand(10,10).cuda()
6
+
7
+ p1 = p.data.sum().item()
8
+
9
+ adam = bnb.optim.Adam([p])
10
+
11
+ out = a*p
12
+ loss = out.sum()
13
+ loss.backward()
14
+ adam.step()
15
+
16
+ p2 = p.data.sum().item()
17
+
18
+ assert p1 != p2
19
+ print('SUCCESS!')
20
+ print('Installation was successful!')
config.json ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "openai/whisper-small",
3
+ "activation_dropout": 0.0,
4
+ "activation_function": "gelu",
5
+ "architectures": [
6
+ "WhisperForConditionalGeneration"
7
+ ],
8
+ "attention_dropout": 0.0,
9
+ "begin_suppress_tokens": [
10
+ 220,
11
+ 50257
12
+ ],
13
+ "bos_token_id": 50257,
14
+ "d_model": 768,
15
+ "decoder_attention_heads": 12,
16
+ "decoder_ffn_dim": 3072,
17
+ "decoder_layerdrop": 0.0,
18
+ "decoder_layers": 12,
19
+ "decoder_start_token_id": 50258,
20
+ "dropout": 0.0,
21
+ "encoder_attention_heads": 12,
22
+ "encoder_ffn_dim": 3072,
23
+ "encoder_layerdrop": 0.0,
24
+ "encoder_layers": 12,
25
+ "eos_token_id": 50257,
26
+ "forced_decoder_ids": null,
27
+ "init_std": 0.02,
28
+ "is_encoder_decoder": true,
29
+ "max_length": 448,
30
+ "max_source_positions": 1500,
31
+ "max_target_positions": 448,
32
+ "model_type": "whisper",
33
+ "num_hidden_layers": 12,
34
+ "num_mel_bins": 80,
35
+ "pad_token_id": 50257,
36
+ "scale_embedding": false,
37
+ "torch_dtype": "float32",
38
+ "transformers_version": "4.26.0.dev0",
39
+ "use_cache": false,
40
+ "vocab_size": 51865
41
+ }
ds_config.json ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "fp16": {
3
+ "enabled": "auto",
4
+ "loss_scale": 0,
5
+ "loss_scale_window": 1000,
6
+ "initial_scale_power": 16,
7
+ "hysteresis": 2,
8
+ "min_loss_scale": 1
9
+ },
10
+
11
+ "optimizer": {
12
+ "type": "AdamW",
13
+ "params": {
14
+ "lr": "auto",
15
+ "betas": "auto",
16
+ "eps": "auto",
17
+ "weight_decay": "auto"
18
+ }
19
+ },
20
+
21
+ "scheduler": {
22
+ "type": "WarmupLR",
23
+ "params": {
24
+ "warmup_min_lr": "auto",
25
+ "warmup_max_lr": "auto",
26
+ "warmup_num_steps": "auto"
27
+ }
28
+ },
29
+
30
+ "zero_optimization": {
31
+ "stage": 2,
32
+ "offload_optimizer": {
33
+ "device": "cpu",
34
+ "pin_memory": true
35
+ },
36
+ "allgather_partitions": true,
37
+ "allgather_bucket_size": 2e8,
38
+ "overlap_comm": true,
39
+ "reduce_scatter": true,
40
+ "reduce_bucket_size": 2e8,
41
+ "contiguous_gradients": true
42
+ },
43
+
44
+ "gradient_accumulation_steps": "auto",
45
+ "gradient_clipping": "auto",
46
+ "train_batch_size": "auto",
47
+ "train_micro_batch_size_per_gpu": "auto"
48
+ }
eval_results.json ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "epoch": 1.44,
3
+ "eval_loss": 0.9784936308860779,
4
+ "eval_runtime": 1959.8449,
5
+ "eval_samples_per_second": 2.885,
6
+ "eval_steps_per_second": 0.361,
7
+ "eval_wer": 20.95505699346784
8
+ }
evaluate_models.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import librosa
3
+ from datasets import load_dataset, Audio
4
+ from transformers import WhisperProcessor, WhisperFeatureExtractor, WhisperTokenizer, WhisperForConditionalGeneration
5
+ from huggingface_hub import login
6
+ import argparse
7
+ from evaluate import load
8
+
9
+ my_parser = argparse.ArgumentParser()
10
+ # my_parser.add_argument("--pal", "-paths_as_labels", action="store_true")
11
+
12
+ my_parser.add_argument("--model_name", "-model_name", type=str, action="store", default = "openai/whisper-tiny")
13
+ my_parser.add_argument("--hf_token", "-hf_token", type=str, action="store")
14
+ my_parser.add_argument("--dataset_name", "-dataset_name", type=str, action="store", default = "google/fleurs")
15
+ my_parser.add_argument("--split", "-split", type=str, action="store", default = "test")
16
+ my_parser.add_argument("--subset", "-subset", type=str, action="store")
17
+
18
+ args = my_parser.parse_args()
19
+ try:
20
+ login(args.hf_token)
21
+ except:
22
+ raise(f"Can't login please set --hf_token {args.hf_token}")
23
+
24
+
25
+ dataset_name = args.dataset_name
26
+ model_name = args.model_name
27
+ subset = args.subset
28
+ text_column = "sentence"
29
+ if dataset_name == "google/fleurs":
30
+ text_column = "transcription"
31
+
32
+ print(f"Evaluating {args.model_name} on {args.dataset_name} [{subset}]")
33
+
34
+
35
+ feature_extractor = WhisperFeatureExtractor.from_pretrained(model_name)
36
+ model = WhisperForConditionalGeneration.from_pretrained(model_name)
37
+
38
+ test_dataset = load_dataset(dataset_name, subset, split=args.split, use_auth_token=True)
39
+ processor = WhisperProcessor.from_pretrained(model_name, language="Arabic", task="transcribe")
40
+ tokenizer = WhisperTokenizer.from_pretrained(model_name, language="Arabic", task="transcribe")
41
+ test_dataset = test_dataset.cast_column("audio", Audio(sampling_rate=16000))
42
+
43
+ # Preprocessing the datasets.
44
+ def prepare_dataset(batch):
45
+ # load and resample audio data from 48 to 16kHz
46
+ audio = batch["audio"]
47
+
48
+ # compute log-Mel input features from input audio array
49
+ batch["input_features"] = feature_extractor(audio["array"], sampling_rate=audio["sampling_rate"]).input_features[0]
50
+
51
+ # encode target text to label ids
52
+ batch["labels"] = tokenizer(batch[text_column]).input_ids
53
+ return batch
54
+
55
+ test_dataset = test_dataset.map(prepare_dataset)
56
+
57
+ model = model.to("cuda")
58
+ model.config.forced_decoder_ids = processor.get_decoder_prompt_ids(language = "ar", task = "transcribe")
59
+
60
+ def map_to_result(batch):
61
+
62
+ with torch.no_grad():
63
+ input_values = torch.tensor(batch["input_features"], device="cuda").unsqueeze(0)
64
+ pred_ids = model.generate(input_values)
65
+
66
+ batch["pred_str"] = processor.batch_decode(pred_ids, skip_special_tokens = True)[0]
67
+ batch["text"] = processor.decode(batch["labels"], skip_special_tokens = True)
68
+
69
+ return batch
70
+ results = test_dataset.map(map_to_result)
71
+
72
+ wer = load("wer")
73
+ print("Test WER: {:.3f}".format(wer.compute(predictions=results["pred_str"], references=results["text"])))
fine-tune-whisper-non-streaming.ipynb ADDED
@@ -0,0 +1,1322 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "id": "75b58048-7d14-4fc6-8085-1fc08c81b4a6",
6
+ "metadata": {
7
+ "id": "75b58048-7d14-4fc6-8085-1fc08c81b4a6"
8
+ },
9
+ "source": [
10
+ "# Fine-Tune Whisper For Multilingual ASR with 🤗 Transformers"
11
+ ]
12
+ },
13
+ {
14
+ "cell_type": "code",
15
+ "execution_count": 1,
16
+ "id": "adbcd467-b895-4db4-aab7-21a5fa73d1d5",
17
+ "metadata": {},
18
+ "outputs": [
19
+ {
20
+ "ename": "ModuleNotFoundError",
21
+ "evalue": "No module named 'datasets'",
22
+ "output_type": "error",
23
+ "traceback": [
24
+ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
25
+ "\u001b[0;31mModuleNotFoundError\u001b[0m Traceback (most recent call last)",
26
+ "\u001b[0;32m<ipython-input-1-ae2b6beea833>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m\u001b[0m\n\u001b[1;32m 5\u001b[0m \u001b[0;32mfrom\u001b[0m \u001b[0mtyping\u001b[0m \u001b[0;32mimport\u001b[0m \u001b[0mAny\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mDict\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mList\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mOptional\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mUnion\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 6\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 7\u001b[0;31m \u001b[0;32mimport\u001b[0m \u001b[0mdatasets\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 8\u001b[0m \u001b[0;32mimport\u001b[0m \u001b[0mtorch\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 9\u001b[0m \u001b[0;32mfrom\u001b[0m \u001b[0mdatasets\u001b[0m \u001b[0;32mimport\u001b[0m \u001b[0mDatasetDict\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mIterableDatasetDict\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0minterleave_datasets\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mload_dataset\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
27
+ "\u001b[0;31mModuleNotFoundError\u001b[0m: No module named 'datasets'"
28
+ ]
29
+ }
30
+ ],
31
+ "source": [
32
+ "import logging\n",
33
+ "import os\n",
34
+ "import sys\n",
35
+ "from dataclasses import dataclass, field\n",
36
+ "from typing import Any, Dict, List, Optional, Union\n",
37
+ "\n",
38
+ "import datasets\n",
39
+ "import torch\n",
40
+ "from datasets import DatasetDict, IterableDatasetDict, interleave_datasets, load_dataset\n",
41
+ "from torch.utils.data import IterableDataset\n",
42
+ "\n",
43
+ "def load_multiple_streaming_datasets(\n",
44
+ " dataset_names: List,\n",
45
+ " dataset_config_names: List,\n",
46
+ " splits: Optional[List] = None,\n",
47
+ " text_column_names: Optional[List] = None,\n",
48
+ " sampling_rate: Optional[int] = 16000,\n",
49
+ " stopping_strategy: Optional[str] = \"first_exhausted\",\n",
50
+ " **kwargs\n",
51
+ ") -> IterableDataset:\n",
52
+ "\n",
53
+ " if len(dataset_names) != len(dataset_config_names):\n",
54
+ " raise ValueError(\n",
55
+ " f\"Ensure one config is passed for each dataset, got {len(dataset_names)} datasets and\"\n",
56
+ " f\" {len(dataset_config_names)} configs.\"\n",
57
+ " )\n",
58
+ "\n",
59
+ " if splits is not None and len(splits) != len(dataset_names):\n",
60
+ " raise ValueError(\n",
61
+ " f\"Ensure one split is passed for each dataset, got {len(dataset_names)} datasets and {len(splits)} splits.\"\n",
62
+ " )\n",
63
+ "\n",
64
+ " if text_column_names is not None and len(text_column_names) != len(dataset_names):\n",
65
+ " raise ValueError(\n",
66
+ " f\"Ensure one text column name is passed for each dataset, got {len(dataset_names)} datasets and\"\n",
67
+ " f\" {len(text_column_names)} text column names.\"\n",
68
+ " )\n",
69
+ "\n",
70
+ " splits = splits if splits is not None else [\"train\" for i in range(len(dataset_names))]\n",
71
+ " text_column_names = (\n",
72
+ " text_column_names if text_column_names is not None else [\"text\" for i in range(len(dataset_names))]\n",
73
+ " )\n",
74
+ "\n",
75
+ " all_datasets = []\n",
76
+ " # iterate over the datasets we want to interleave\n",
77
+ " for i, dataset_name in enumerate(dataset_names):\n",
78
+ " dataset = load_dataset(dataset_name, dataset_config_names[i], split=splits[i], streaming=True, **kwargs)\n",
79
+ " # resample to specified sampling rate\n",
80
+ " dataset = dataset.cast_column(\"audio\", Audio(sampling_rate))\n",
81
+ " # normalise columns to [\"audio\", \"sentence\"]\n",
82
+ " if text_column_names[i] != \"sentence\":\n",
83
+ " dataset = dataset.rename_column(text_column_names[i], \"sentence\")\n",
84
+ " dataset = dataset.remove_columns(set(dataset.features.keys()) - set([\"audio\", \"sentence\"]))\n",
85
+ " all_datasets.append(dataset)\n",
86
+ "\n",
87
+ " interleaved_dataset = interleave_datasets(all_datasets, stopping_strategy=stopping_strategy)\n",
88
+ " return interleaved_dataset\n",
89
+ "\n",
90
+ "\n",
91
+ "\n",
92
+ "dataset_names = [\"mozilla-foundation/common_voice_11_0\", \"arbml/mgb2_speech\", ]\n",
93
+ "dataset_config_names = [\"ar\", \"ar\", ]\n",
94
+ "text_column_names = [\"sentence\", \"text\",]\n",
95
+ "splits = [\"train\",\"train\"]\n",
96
+ "\n",
97
+ "ds = load_multiple_streaming_datasets(\n",
98
+ " dataset_names,\n",
99
+ " dataset_config_names=dataset_config_names,\n",
100
+ " text_column_names=text_column_names,\n",
101
+ " use_auth_token=True\n",
102
+ " )\n"
103
+ ]
104
+ },
105
+ {
106
+ "cell_type": "code",
107
+ "execution_count": null,
108
+ "id": "edf35b20-4872-4e14-bc5c-cc4e1a4eec37",
109
+ "metadata": {},
110
+ "outputs": [],
111
+ "source": []
112
+ },
113
+ {
114
+ "cell_type": "markdown",
115
+ "id": "fbfa8ad5-4cdc-4512-9058-836cbbf65e1a",
116
+ "metadata": {
117
+ "id": "fbfa8ad5-4cdc-4512-9058-836cbbf65e1a"
118
+ },
119
+ "source": [
120
+ "In this Colab, we present a step-by-step guide on how to fine-tune Whisper \n",
121
+ "for any multilingual ASR dataset using Hugging Face 🤗 Transformers. This is a \n",
122
+ "more \"hands-on\" version of the accompanying [blog post](https://huggingface.co/blog/fine-tune-whisper). \n",
123
+ "For a more in-depth explanation of Whisper, the Common Voice dataset and the theory behind fine-tuning, the reader is advised to refer to the blog post."
124
+ ]
125
+ },
126
+ {
127
+ "cell_type": "markdown",
128
+ "id": "afe0d503-ae4e-4aa7-9af4-dbcba52db41e",
129
+ "metadata": {
130
+ "id": "afe0d503-ae4e-4aa7-9af4-dbcba52db41e"
131
+ },
132
+ "source": [
133
+ "## Introduction"
134
+ ]
135
+ },
136
+ {
137
+ "cell_type": "markdown",
138
+ "id": "9ae91ed4-9c3e-4ade-938e-f4c2dcfbfdc0",
139
+ "metadata": {
140
+ "id": "9ae91ed4-9c3e-4ade-938e-f4c2dcfbfdc0"
141
+ },
142
+ "source": [
143
+ "Whisper is a pre-trained model for automatic speech recognition (ASR) \n",
144
+ "published in [September 2022](https://openai.com/blog/whisper/) by the authors \n",
145
+ "Alec Radford et al. from OpenAI. Unlike many of its predecessors, such as \n",
146
+ "[Wav2Vec 2.0](https://arxiv.org/abs/2006.11477), which are pre-trained \n",
147
+ "on un-labelled audio data, Whisper is pre-trained on a vast quantity of \n",
148
+ "**labelled** audio-transcription data, 680,000 hours to be precise. \n",
149
+ "This is an order of magnitude more data than the un-labelled audio data used \n",
150
+ "to train Wav2Vec 2.0 (60,000 hours). What is more, 117,000 hours of this \n",
151
+ "pre-training data is multilingual ASR data. This results in checkpoints \n",
152
+ "that can be applied to over 96 languages, many of which are considered \n",
153
+ "_low-resource_.\n",
154
+ "\n",
155
+ "When scaled to 680,000 hours of labelled pre-training data, Whisper models \n",
156
+ "demonstrate a strong ability to generalise to many datasets and domains.\n",
157
+ "The pre-trained checkpoints achieve competitive results to state-of-the-art \n",
158
+ "ASR systems, with near 3% word error rate (WER) on the test-clean subset of \n",
159
+ "LibriSpeech ASR and a new state-of-the-art on TED-LIUM with 4.7% WER (_c.f._ \n",
160
+ "Table 8 of the [Whisper paper](https://cdn.openai.com/papers/whisper.pdf)).\n",
161
+ "The extensive multilingual ASR knowledge acquired by Whisper during pre-training \n",
162
+ "can be leveraged for other low-resource languages; through fine-tuning, the \n",
163
+ "pre-trained checkpoints can be adapted for specific datasets and languages \n",
164
+ "to further improve upon these results. We'll show just how Whisper can be fine-tuned \n",
165
+ "for low-resource languages in this Colab."
166
+ ]
167
+ },
168
+ {
169
+ "cell_type": "markdown",
170
+ "id": "e59b91d6-be24-4b5e-bb38-4977ea143a72",
171
+ "metadata": {
172
+ "id": "e59b91d6-be24-4b5e-bb38-4977ea143a72"
173
+ },
174
+ "source": [
175
+ "<figure>\n",
176
+ "<img src=\"https://raw.githubusercontent.com/sanchit-gandhi/notebooks/main/whisper_architecture.svg\" alt=\"Trulli\" style=\"width:100%\">\n",
177
+ "<figcaption align = \"center\"><b>Figure 1:</b> Whisper model. The architecture \n",
178
+ "follows the standard Transformer-based encoder-decoder model. A \n",
179
+ "log-Mel spectrogram is input to the encoder. The last encoder \n",
180
+ "hidden states are input to the decoder via cross-attention mechanisms. The \n",
181
+ "decoder autoregressively predicts text tokens, jointly conditional on the \n",
182
+ "encoder hidden states and previously predicted tokens. Figure source: \n",
183
+ "<a href=\"https://openai.com/blog/whisper/\">OpenAI Whisper Blog</a>.</figcaption>\n",
184
+ "</figure>"
185
+ ]
186
+ },
187
+ {
188
+ "cell_type": "markdown",
189
+ "id": "21b6316e-8a55-4549-a154-66d3da2ab74a",
190
+ "metadata": {
191
+ "id": "21b6316e-8a55-4549-a154-66d3da2ab74a"
192
+ },
193
+ "source": [
194
+ "The Whisper checkpoints come in five configurations of varying model sizes.\n",
195
+ "The smallest four are trained on either English-only or multilingual data.\n",
196
+ "The largest checkpoint is multilingual only. All nine of the pre-trained checkpoints \n",
197
+ "are available on the [Hugging Face Hub](https://huggingface.co/models?search=openai/whisper). The \n",
198
+ "checkpoints are summarised in the following table with links to the models on the Hub:\n",
199
+ "\n",
200
+ "| Size | Layers | Width | Heads | Parameters | English-only | Multilingual |\n",
201
+ "|--------|--------|-------|-------|------------|------------------------------------------------------|---------------------------------------------------|\n",
202
+ "| tiny | 4 | 384 | 6 | 39 M | [✓](https://huggingface.co/openai/whisper-tiny.en) | [✓](https://huggingface.co/openai/whisper-tiny.) |\n",
203
+ "| base | 6 | 512 | 8 | 74 M | [✓](https://huggingface.co/openai/whisper-base.en) | [✓](https://huggingface.co/openai/whisper-base) |\n",
204
+ "| small | 12 | 768 | 12 | 244 M | [✓](https://huggingface.co/openai/whisper-small.en) | [✓](https://huggingface.co/openai/whisper-small) |\n",
205
+ "| medium | 24 | 1024 | 16 | 769 M | [✓](https://huggingface.co/openai/whisper-medium.en) | [✓](https://huggingface.co/openai/whisper-medium) |\n",
206
+ "| large | 32 | 1280 | 20 | 1550 M | x | [✓](https://huggingface.co/openai/whisper-large) |\n",
207
+ "\n",
208
+ "For demonstration purposes, we'll fine-tune the multilingual version of the \n",
209
+ "[`\"small\"`](https://huggingface.co/openai/whisper-small) checkpoint with 244M params (~= 1GB). \n",
210
+ "As for our data, we'll train and evaluate our system on a low-resource language \n",
211
+ "taken from the [Common Voice](https://huggingface.co/datasets/mozilla-foundation/common_voice_11_0)\n",
212
+ "dataset. We'll show that with as little as 8 hours of fine-tuning data, we can achieve \n",
213
+ "strong performance in this language."
214
+ ]
215
+ },
216
+ {
217
+ "cell_type": "markdown",
218
+ "id": "3a680dfc-cbba-4f6c-8a1f-e1a5ff3f123a",
219
+ "metadata": {
220
+ "id": "3a680dfc-cbba-4f6c-8a1f-e1a5ff3f123a"
221
+ },
222
+ "source": [
223
+ "------------------------------------------------------------------------\n",
224
+ "\n",
225
+ "\\\\({}^1\\\\) The name Whisper follows from the acronym “WSPSR”, which stands for “Web-scale Supervised Pre-training for Speech Recognition”."
226
+ ]
227
+ },
228
+ {
229
+ "cell_type": "markdown",
230
+ "id": "b219c9dd-39b6-4a95-b2a1-3f547a1e7bc0",
231
+ "metadata": {
232
+ "id": "b219c9dd-39b6-4a95-b2a1-3f547a1e7bc0"
233
+ },
234
+ "source": [
235
+ "## Load Dataset"
236
+ ]
237
+ },
238
+ {
239
+ "cell_type": "markdown",
240
+ "id": "674429c5-0ab4-4adf-975b-621bb69eca38",
241
+ "metadata": {
242
+ "id": "674429c5-0ab4-4adf-975b-621bb69eca38"
243
+ },
244
+ "source": [
245
+ "Using 🤗 Datasets, downloading and preparing data is extremely simple. \n",
246
+ "We can download and prepare the Common Voice splits in just one line of code. \n",
247
+ "\n",
248
+ "First, ensure you have accepted the terms of use on the Hugging Face Hub: [mozilla-foundation/common_voice_11_0](https://huggingface.co/datasets/mozilla-foundation/common_voice_11_0). Once you have accepted the terms, you will have full access to the dataset and be able to download the data locally.\n",
249
+ "\n",
250
+ "Since Arabic is very low-resource, we'll combine the `train` and `validation` \n",
251
+ "splits to give approximately 8 hours of training data. We'll use the 4 hours \n",
252
+ "of `test` data as our held-out test set:"
253
+ ]
254
+ },
255
+ {
256
+ "cell_type": "code",
257
+ "execution_count": null,
258
+ "id": "5de15d70",
259
+ "metadata": {},
260
+ "outputs": [],
261
+ "source": [
262
+ "model_name = \"openai/whisper-small\""
263
+ ]
264
+ },
265
+ {
266
+ "cell_type": "code",
267
+ "execution_count": null,
268
+ "id": "a2787582-554f-44ce-9f38-4180a5ed6b44",
269
+ "metadata": {
270
+ "id": "a2787582-554f-44ce-9f38-4180a5ed6b44"
271
+ },
272
+ "outputs": [],
273
+ "source": [
274
+ "from datasets import load_dataset, DatasetDict\n",
275
+ "\n",
276
+ "common_voice = DatasetDict()\n",
277
+ "\n",
278
+ "common_voice[\"train\"] = load_dataset(\"mozilla-foundation/common_voice_11_0\", \"ar\", split=\"train+validation\", use_auth_token=True)\n",
279
+ "common_voice[\"test\"] = load_dataset(\"mozilla-foundation/common_voice_11_0\", \"ar\", split=\"test\", use_auth_token=True)\n",
280
+ "\n",
281
+ "print(common_voice)"
282
+ ]
283
+ },
284
+ {
285
+ "cell_type": "markdown",
286
+ "id": "d5c7c3d6-7197-41e7-a088-49b753c1681f",
287
+ "metadata": {
288
+ "id": "d5c7c3d6-7197-41e7-a088-49b753c1681f"
289
+ },
290
+ "source": [
291
+ "Most ASR datasets only provide input audio samples (`audio`) and the \n",
292
+ "corresponding transcribed text (`sentence`). Common Voice contains additional \n",
293
+ "metadata information, such as `accent` and `locale`, which we can disregard for ASR.\n",
294
+ "Keeping the notebook as general as possible, we only consider the input audio and\n",
295
+ "transcribed text for fine-tuning, discarding the additional metadata information:"
296
+ ]
297
+ },
298
+ {
299
+ "cell_type": "code",
300
+ "execution_count": null,
301
+ "id": "20ba635d-518c-47ac-97ee-3cad25f1e0ce",
302
+ "metadata": {
303
+ "id": "20ba635d-518c-47ac-97ee-3cad25f1e0ce"
304
+ },
305
+ "outputs": [],
306
+ "source": [
307
+ "common_voice = common_voice.remove_columns([\"accent\", \"age\", \"client_id\", \"down_votes\", \"gender\", \"locale\", \"path\", \"segment\", \"up_votes\"])\n",
308
+ "\n",
309
+ "print(common_voice)"
310
+ ]
311
+ },
312
+ {
313
+ "cell_type": "markdown",
314
+ "id": "2d63b2d2-f68a-4d74-b7f1-5127f6d16605",
315
+ "metadata": {
316
+ "id": "2d63b2d2-f68a-4d74-b7f1-5127f6d16605"
317
+ },
318
+ "source": [
319
+ "## Prepare Feature Extractor, Tokenizer and Data"
320
+ ]
321
+ },
322
+ {
323
+ "cell_type": "markdown",
324
+ "id": "601c3099-1026-439e-93e2-5635b3ba5a73",
325
+ "metadata": {
326
+ "id": "601c3099-1026-439e-93e2-5635b3ba5a73"
327
+ },
328
+ "source": [
329
+ "The ASR pipeline can be de-composed into three stages: \n",
330
+ "1) A feature extractor which pre-processes the raw audio-inputs\n",
331
+ "2) The model which performs the sequence-to-sequence mapping \n",
332
+ "3) A tokenizer which post-processes the model outputs to text format\n",
333
+ "\n",
334
+ "In 🤗 Transformers, the Whisper model has an associated feature extractor and tokenizer, \n",
335
+ "called [WhisperFeatureExtractor](https://huggingface.co/docs/transformers/main/model_doc/whisper#transformers.WhisperFeatureExtractor)\n",
336
+ "and [WhisperTokenizer](https://huggingface.co/docs/transformers/main/model_doc/whisper#transformers.WhisperTokenizer) \n",
337
+ "respectively.\n",
338
+ "\n",
339
+ "We'll go through details for setting-up the feature extractor and tokenizer one-by-one!"
340
+ ]
341
+ },
342
+ {
343
+ "cell_type": "markdown",
344
+ "id": "560332eb-3558-41a1-b500-e83a9f695f84",
345
+ "metadata": {
346
+ "id": "560332eb-3558-41a1-b500-e83a9f695f84"
347
+ },
348
+ "source": [
349
+ "### Load WhisperFeatureExtractor"
350
+ ]
351
+ },
352
+ {
353
+ "cell_type": "markdown",
354
+ "id": "32ec8068-0bd7-412d-b662-0edb9d1e7365",
355
+ "metadata": {
356
+ "id": "32ec8068-0bd7-412d-b662-0edb9d1e7365"
357
+ },
358
+ "source": [
359
+ "The Whisper feature extractor performs two operations:\n",
360
+ "1. Pads / truncates the audio inputs to 30s: any audio inputs shorter than 30s are padded to 30s with silence (zeros), and those longer that 30s are truncated to 30s\n",
361
+ "2. Converts the audio inputs to _log-Mel spectrogram_ input features, a visual representation of the audio and the form of the input expected by the Whisper model"
362
+ ]
363
+ },
364
+ {
365
+ "cell_type": "markdown",
366
+ "id": "589d9ec1-d12b-4b64-93f7-04c63997da19",
367
+ "metadata": {
368
+ "id": "589d9ec1-d12b-4b64-93f7-04c63997da19"
369
+ },
370
+ "source": [
371
+ "<figure>\n",
372
+ "<img src=\"https://raw.githubusercontent.com/sanchit-gandhi/notebooks/main/spectrogram.jpg\" alt=\"Trulli\" style=\"width:100%\">\n",
373
+ "<figcaption align = \"center\"><b>Figure 2:</b> Conversion of sampled audio array to log-Mel spectrogram.\n",
374
+ "Left: sampled 1-dimensional audio signal. Right: corresponding log-Mel spectrogram. Figure source:\n",
375
+ "<a href=\"https://ai.googleblog.com/2019/04/specaugment-new-data-augmentation.html\">Google SpecAugment Blog</a>.\n",
376
+ "</figcaption>"
377
+ ]
378
+ },
379
+ {
380
+ "cell_type": "markdown",
381
+ "id": "b2ef54d5-b946-4c1d-9fdc-adc5d01b46aa",
382
+ "metadata": {
383
+ "id": "b2ef54d5-b946-4c1d-9fdc-adc5d01b46aa"
384
+ },
385
+ "source": [
386
+ "We'll load the feature extractor from the pre-trained checkpoint with the default values:"
387
+ ]
388
+ },
389
+ {
390
+ "cell_type": "code",
391
+ "execution_count": null,
392
+ "id": "bc77d7bb-f9e2-47f5-b663-30f7a4321ce5",
393
+ "metadata": {
394
+ "id": "bc77d7bb-f9e2-47f5-b663-30f7a4321ce5"
395
+ },
396
+ "outputs": [],
397
+ "source": [
398
+ "from transformers import WhisperFeatureExtractor\n",
399
+ "\n",
400
+ "feature_extractor = WhisperFeatureExtractor.from_pretrained(model_name)"
401
+ ]
402
+ },
403
+ {
404
+ "cell_type": "markdown",
405
+ "id": "93748af7-b917-4ecf-a0c8-7d89077ff9cb",
406
+ "metadata": {
407
+ "id": "93748af7-b917-4ecf-a0c8-7d89077ff9cb"
408
+ },
409
+ "source": [
410
+ "### Load WhisperTokenizer"
411
+ ]
412
+ },
413
+ {
414
+ "cell_type": "markdown",
415
+ "id": "2bc82609-a9fb-447a-a2af-99597c864029",
416
+ "metadata": {
417
+ "id": "2bc82609-a9fb-447a-a2af-99597c864029"
418
+ },
419
+ "source": [
420
+ "The Whisper model outputs a sequence of _token ids_. The tokenizer maps each of these token ids to their corresponding text string. For Arabic, we can load the pre-trained tokenizer and use it for fine-tuning without any further modifications. We simply have to \n",
421
+ "specify the target language and the task. These arguments inform the \n",
422
+ "tokenizer to prefix the language and task tokens to the start of encoded \n",
423
+ "label sequences:"
424
+ ]
425
+ },
426
+ {
427
+ "cell_type": "code",
428
+ "execution_count": null,
429
+ "id": "c7b07f9b-ae0e-4f89-98f0-0c50d432eab6",
430
+ "metadata": {
431
+ "id": "c7b07f9b-ae0e-4f89-98f0-0c50d432eab6",
432
+ "outputId": "5c004b44-86e7-4e00-88be-39e0af5eed69"
433
+ },
434
+ "outputs": [
435
+ {
436
+ "data": {
437
+ "application/vnd.jupyter.widget-view+json": {
438
+ "model_id": "90d056e20b3e4f14ae0199a1a4ab1bb0",
439
+ "version_major": 2,
440
+ "version_minor": 0
441
+ },
442
+ "text/plain": [
443
+ "Downloading: 0%| | 0.00/829 [00:00<?, ?B/s]"
444
+ ]
445
+ },
446
+ "metadata": {},
447
+ "output_type": "display_data"
448
+ },
449
+ {
450
+ "data": {
451
+ "application/vnd.jupyter.widget-view+json": {
452
+ "model_id": "d82a88daec0e4f14add691b7b903064c",
453
+ "version_major": 2,
454
+ "version_minor": 0
455
+ },
456
+ "text/plain": [
457
+ "Downloading: 0%| | 0.00/1.04M [00:00<?, ?B/s]"
458
+ ]
459
+ },
460
+ "metadata": {},
461
+ "output_type": "display_data"
462
+ },
463
+ {
464
+ "data": {
465
+ "application/vnd.jupyter.widget-view+json": {
466
+ "model_id": "350acdb0f40e454099fa901e66de55f0",
467
+ "version_major": 2,
468
+ "version_minor": 0
469
+ },
470
+ "text/plain": [
471
+ "Downloading: 0%| | 0.00/494k [00:00<?, ?B/s]"
472
+ ]
473
+ },
474
+ "metadata": {},
475
+ "output_type": "display_data"
476
+ },
477
+ {
478
+ "data": {
479
+ "application/vnd.jupyter.widget-view+json": {
480
+ "model_id": "2e6a82a462cc411d90fa1bea4ee60790",
481
+ "version_major": 2,
482
+ "version_minor": 0
483
+ },
484
+ "text/plain": [
485
+ "Downloading: 0%| | 0.00/52.7k [00:00<?, ?B/s]"
486
+ ]
487
+ },
488
+ "metadata": {},
489
+ "output_type": "display_data"
490
+ },
491
+ {
492
+ "data": {
493
+ "application/vnd.jupyter.widget-view+json": {
494
+ "model_id": "c74bfee0198b4817832ea86e8e88d96c",
495
+ "version_major": 2,
496
+ "version_minor": 0
497
+ },
498
+ "text/plain": [
499
+ "Downloading: 0%| | 0.00/2.11k [00:00<?, ?B/s]"
500
+ ]
501
+ },
502
+ "metadata": {},
503
+ "output_type": "display_data"
504
+ },
505
+ {
506
+ "data": {
507
+ "application/vnd.jupyter.widget-view+json": {
508
+ "model_id": "04fb2d81eff646068e10475a08ae42f4",
509
+ "version_major": 2,
510
+ "version_minor": 0
511
+ },
512
+ "text/plain": [
513
+ "Downloading: 0%| | 0.00/2.06k [00:00<?, ?B/s]"
514
+ ]
515
+ },
516
+ "metadata": {},
517
+ "output_type": "display_data"
518
+ }
519
+ ],
520
+ "source": [
521
+ "from transformers import WhisperTokenizer\n",
522
+ "\n",
523
+ "tokenizer = WhisperTokenizer.from_pretrained(\"openai/whisper-small\", language=\"Arabic\", task=\"transcribe\")"
524
+ ]
525
+ },
526
+ {
527
+ "cell_type": "markdown",
528
+ "id": "d2ef23f3-f4a8-483a-a2dc-080a7496cb1b",
529
+ "metadata": {
530
+ "id": "d2ef23f3-f4a8-483a-a2dc-080a7496cb1b"
531
+ },
532
+ "source": [
533
+ "### Combine To Create A WhisperProcessor"
534
+ ]
535
+ },
536
+ {
537
+ "cell_type": "markdown",
538
+ "id": "5ff67654-5a29-4bb8-a69d-0228946c6f8d",
539
+ "metadata": {
540
+ "id": "5ff67654-5a29-4bb8-a69d-0228946c6f8d"
541
+ },
542
+ "source": [
543
+ "To simplify using the feature extractor and tokenizer, we can _wrap_ \n",
544
+ "both into a single `WhisperProcessor` class. This processor object \n",
545
+ "inherits from the `WhisperFeatureExtractor` and `WhisperProcessor`, \n",
546
+ "and can be used on the audio inputs and model predictions as required. \n",
547
+ "In doing so, we only need to keep track of two objects during training: \n",
548
+ "the `processor` and the `model`:"
549
+ ]
550
+ },
551
+ {
552
+ "cell_type": "code",
553
+ "execution_count": null,
554
+ "id": "77d9f0c5-8607-4642-a8ac-c3ab2e223ea6",
555
+ "metadata": {
556
+ "id": "77d9f0c5-8607-4642-a8ac-c3ab2e223ea6"
557
+ },
558
+ "outputs": [],
559
+ "source": [
560
+ "from transformers import WhisperProcessor\n",
561
+ "\n",
562
+ "processor = WhisperProcessor.from_pretrained(model_name, language=\"Arabic\", task=\"transcribe\")"
563
+ ]
564
+ },
565
+ {
566
+ "cell_type": "markdown",
567
+ "id": "381acd09-0b0f-4d04-9eb3-f028ac0e5f2c",
568
+ "metadata": {
569
+ "id": "381acd09-0b0f-4d04-9eb3-f028ac0e5f2c"
570
+ },
571
+ "source": [
572
+ "### Prepare Data"
573
+ ]
574
+ },
575
+ {
576
+ "cell_type": "markdown",
577
+ "id": "9649bf01-2e8a-45e5-8fca-441c13637b8f",
578
+ "metadata": {
579
+ "id": "9649bf01-2e8a-45e5-8fca-441c13637b8f"
580
+ },
581
+ "source": [
582
+ "Let's print the first example of the Common Voice dataset to see \n",
583
+ "what form the data is in:"
584
+ ]
585
+ },
586
+ {
587
+ "cell_type": "code",
588
+ "execution_count": null,
589
+ "id": "6e6b0ec5-0c94-4e2c-ae24-c791be1b2255",
590
+ "metadata": {
591
+ "id": "6e6b0ec5-0c94-4e2c-ae24-c791be1b2255"
592
+ },
593
+ "outputs": [],
594
+ "source": [
595
+ "print(common_voice[\"train\"][0])"
596
+ ]
597
+ },
598
+ {
599
+ "cell_type": "markdown",
600
+ "id": "5a679f05-063d-41b3-9b58-4fc9c6ccf4fd",
601
+ "metadata": {
602
+ "id": "5a679f05-063d-41b3-9b58-4fc9c6ccf4fd"
603
+ },
604
+ "source": [
605
+ "Since \n",
606
+ "our input audio is sampled at 48kHz, we need to _downsample_ it to \n",
607
+ "16kHz prior to passing it to the Whisper feature extractor, 16kHz being the sampling rate expected by the Whisper model. \n",
608
+ "\n",
609
+ "We'll set the audio inputs to the correct sampling rate using dataset's \n",
610
+ "[`cast_column`](https://huggingface.co/docs/datasets/package_reference/main_classes.html?highlight=cast_column#datasets.DatasetDict.cast_column)\n",
611
+ "method. This operation does not change the audio in-place, \n",
612
+ "but rather signals to `datasets` to resample audio samples _on the fly_ the \n",
613
+ "first time that they are loaded:"
614
+ ]
615
+ },
616
+ {
617
+ "cell_type": "code",
618
+ "execution_count": null,
619
+ "id": "f12e2e57-156f-417b-8cfb-69221cc198e8",
620
+ "metadata": {
621
+ "id": "f12e2e57-156f-417b-8cfb-69221cc198e8"
622
+ },
623
+ "outputs": [],
624
+ "source": [
625
+ "from datasets import Audio\n",
626
+ "\n",
627
+ "common_voice = common_voice.cast_column(\"audio\", Audio(sampling_rate=16000))"
628
+ ]
629
+ },
630
+ {
631
+ "cell_type": "markdown",
632
+ "id": "00382a3e-abec-4cdd-a54c-d1aaa3ea4707",
633
+ "metadata": {
634
+ "id": "00382a3e-abec-4cdd-a54c-d1aaa3ea4707"
635
+ },
636
+ "source": [
637
+ "Re-loading the first audio sample in the Common Voice dataset will resample \n",
638
+ "it to the desired sampling rate:"
639
+ ]
640
+ },
641
+ {
642
+ "cell_type": "code",
643
+ "execution_count": null,
644
+ "id": "87122d71-289a-466a-afcf-fa354b18946b",
645
+ "metadata": {
646
+ "id": "87122d71-289a-466a-afcf-fa354b18946b"
647
+ },
648
+ "outputs": [],
649
+ "source": [
650
+ "print(common_voice[\"train\"][0])"
651
+ ]
652
+ },
653
+ {
654
+ "cell_type": "markdown",
655
+ "id": "3df7378a-a4c0-45d7-8d07-defbd1062ab6",
656
+ "metadata": {},
657
+ "source": [
658
+ "We'll define our pre-processing strategy. We advise that you **do not** lower-case the transcriptions or remove punctuation unless mixing different datasets. This will enable you to fine-tune Whisper models that can predict punctuation and casing. Later, you will see how we can evaluate the predictions without punctuation or casing, so that the models benefit from the WER improvement obtained by normalising the transcriptions while still predicting fully formatted transcriptions."
659
+ ]
660
+ },
661
+ {
662
+ "cell_type": "code",
663
+ "execution_count": null,
664
+ "id": "d041650e-1c48-4439-87b3-5b6f4a514107",
665
+ "metadata": {},
666
+ "outputs": [],
667
+ "source": [
668
+ "from transformers.models.whisper.english_normalizer import BasicTextNormalizer\n",
669
+ "\n",
670
+ "do_lower_case = False\n",
671
+ "do_remove_punctuation = False\n",
672
+ "\n",
673
+ "normalizer = BasicTextNormalizer()"
674
+ ]
675
+ },
676
+ {
677
+ "cell_type": "markdown",
678
+ "id": "89e12c2e-2f14-479b-987b-f0c75c881095",
679
+ "metadata": {},
680
+ "source": [
681
+ "Now we can write a function to prepare our data ready for the model:\n",
682
+ "1. We load and resample the audio data by calling `batch[\"audio\"]`. As explained above, 🤗 Datasets performs any necessary resampling operations on the fly.\n",
683
+ "2. We use the feature extractor to compute the log-Mel spectrogram input features from our 1-dimensional audio array.\n",
684
+ "3. We perform any optional pre-processing (lower-case or remove punctuation).\n",
685
+ "4. We encode the transcriptions to label ids through the use of the tokenizer."
686
+ ]
687
+ },
688
+ {
689
+ "cell_type": "code",
690
+ "execution_count": null,
691
+ "id": "c085911c-a10a-41ef-8874-306e0503e9bb",
692
+ "metadata": {},
693
+ "outputs": [],
694
+ "source": [
695
+ "def prepare_dataset(batch):\n",
696
+ " # load and (possibly) resample audio data to 16kHz\n",
697
+ " audio = batch[\"audio\"]\n",
698
+ "\n",
699
+ " # compute log-Mel input features from input audio array \n",
700
+ " batch[\"input_features\"] = processor.feature_extractor(audio[\"array\"], sampling_rate=audio[\"sampling_rate\"]).input_features[0]\n",
701
+ " # compute input length of audio sample in seconds\n",
702
+ " batch[\"input_length\"] = len(audio[\"array\"]) / audio[\"sampling_rate\"]\n",
703
+ " \n",
704
+ " # optional pre-processing steps\n",
705
+ " transcription = batch[\"sentence\"]\n",
706
+ " if do_lower_case:\n",
707
+ " transcription = transcription.lower()\n",
708
+ " if do_remove_punctuation:\n",
709
+ " transcription = normalizer(transcription).strip()\n",
710
+ " \n",
711
+ " # encode target text to label ids\n",
712
+ " batch[\"labels\"] = processor.tokenizer(transcription).input_ids\n",
713
+ " return batch"
714
+ ]
715
+ },
716
+ {
717
+ "cell_type": "markdown",
718
+ "id": "8c960965-9fb6-466f-9dbd-c9d43e71d9d0",
719
+ "metadata": {
720
+ "id": "70b319fb-2439-4ef6-a70d-a47bf41c4a13"
721
+ },
722
+ "source": [
723
+ "We can apply the data preparation function to all of our training examples using dataset's `.map` method. The argument `num_proc` specifies how many CPU cores to use. Setting `num_proc` > 1 will enable multiprocessing. If the `.map` method hangs with multiprocessing, set `num_proc=1` and process the dataset sequentially."
724
+ ]
725
+ },
726
+ {
727
+ "cell_type": "code",
728
+ "execution_count": null,
729
+ "id": "7b73ab39-ffaf-4b9e-86e5-782963c6134b",
730
+ "metadata": {
731
+ "id": "7b73ab39-ffaf-4b9e-86e5-782963c6134b"
732
+ },
733
+ "outputs": [],
734
+ "source": [
735
+ "common_voice = common_voice.map(prepare_dataset, remove_columns=common_voice.column_names[\"train\"], num_proc=2)"
736
+ ]
737
+ },
738
+ {
739
+ "cell_type": "markdown",
740
+ "id": "54ce0fdb-7218-4a4d-b175-383980fec0df",
741
+ "metadata": {},
742
+ "source": [
743
+ "Finally, we filter any training data with audio samples longer than 30s. These samples would otherwise be truncated by the Whisper feature-extractor which could affect the stability of training. We define a function that returns `True` for samples that are less than 30s, and `False` for those that are longer:"
744
+ ]
745
+ },
746
+ {
747
+ "cell_type": "code",
748
+ "execution_count": null,
749
+ "id": "01cb25ef-4bb0-4325-9461-f59198acadf6",
750
+ "metadata": {},
751
+ "outputs": [],
752
+ "source": [
753
+ "max_input_length = 30.0\n",
754
+ "\n",
755
+ "def is_audio_in_length_range(length):\n",
756
+ " return length < max_input_length"
757
+ ]
758
+ },
759
+ {
760
+ "cell_type": "markdown",
761
+ "id": "30e676a8-7ca8-4850-8c5d-5b2b00d13fba",
762
+ "metadata": {},
763
+ "source": [
764
+ "We apply our filter function to all samples of our training dataset through 🤗 Datasets' `.filter` method:"
765
+ ]
766
+ },
767
+ {
768
+ "cell_type": "code",
769
+ "execution_count": null,
770
+ "id": "333f7f6e-6053-4d3b-8924-c733c79b82ac",
771
+ "metadata": {},
772
+ "outputs": [],
773
+ "source": [
774
+ "common_voice[\"train\"] = common_voice[\"train\"].filter(\n",
775
+ " is_audio_in_length_range,\n",
776
+ " input_columns=[\"input_length\"],\n",
777
+ ")"
778
+ ]
779
+ },
780
+ {
781
+ "cell_type": "markdown",
782
+ "id": "263a5a58-0239-4a25-b0df-c625fc9c5810",
783
+ "metadata": {
784
+ "id": "263a5a58-0239-4a25-b0df-c625fc9c5810"
785
+ },
786
+ "source": [
787
+ "## Training and Evaluation"
788
+ ]
789
+ },
790
+ {
791
+ "cell_type": "markdown",
792
+ "id": "a693e768-c5a6-453f-89a1-b601dcf7daf7",
793
+ "metadata": {
794
+ "id": "a693e768-c5a6-453f-89a1-b601dcf7daf7"
795
+ },
796
+ "source": [
797
+ "Now that we've prepared our data, we're ready to dive into the training pipeline. \n",
798
+ "The [🤗 Trainer](https://huggingface.co/transformers/master/main_classes/trainer.html?highlight=trainer)\n",
799
+ "will do much of the heavy lifting for us. All we have to do is:\n",
800
+ "\n",
801
+ "- Define a data collator: the data collator takes our pre-processed data and prepares PyTorch tensors ready for the model.\n",
802
+ "\n",
803
+ "- Evaluation metrics: during evaluation, we want to evaluate the model using the [word error rate (WER)](https://huggingface.co/metrics/wer) metric. We need to define a `compute_metrics` function that handles this computation.\n",
804
+ "\n",
805
+ "- Load a pre-trained checkpoint: we need to load a pre-trained checkpoint and configure it correctly for training.\n",
806
+ "\n",
807
+ "- Define the training configuration: this will be used by the 🤗 Trainer to define the training schedule.\n",
808
+ "\n",
809
+ "Once we've fine-tuned the model, we will evaluate it on the test data to verify that we have correctly trained it \n",
810
+ "to transcribe speech in Arabic."
811
+ ]
812
+ },
813
+ {
814
+ "cell_type": "markdown",
815
+ "id": "8d230e6d-624c-400a-bbf5-fa660881df25",
816
+ "metadata": {
817
+ "id": "8d230e6d-624c-400a-bbf5-fa660881df25"
818
+ },
819
+ "source": [
820
+ "### Define a Data Collator"
821
+ ]
822
+ },
823
+ {
824
+ "cell_type": "markdown",
825
+ "id": "04def221-0637-4a69-b242-d3f0c1d0ee78",
826
+ "metadata": {
827
+ "id": "04def221-0637-4a69-b242-d3f0c1d0ee78"
828
+ },
829
+ "source": [
830
+ "The data collator for a sequence-to-sequence speech model is unique in the sense that it \n",
831
+ "treats the `input_features` and `labels` independently: the `input_features` must be \n",
832
+ "handled by the feature extractor and the `labels` by the tokenizer.\n",
833
+ "\n",
834
+ "The `input_features` are already padded to 30s and converted to a log-Mel spectrogram \n",
835
+ "of fixed dimension by action of the feature extractor, so all we have to do is convert the `input_features`\n",
836
+ "to batched PyTorch tensors. We do this using the feature extractor's `.pad` method with `return_tensors=pt`.\n",
837
+ "\n",
838
+ "The `labels` on the other hand are un-padded. We first pad the sequences\n",
839
+ "to the maximum length in the batch using the tokenizer's `.pad` method. The padding tokens \n",
840
+ "are then replaced by `-100` so that these tokens are **not** taken into account when \n",
841
+ "computing the loss. We then cut the BOS token from the start of the label sequence as we \n",
842
+ "append it later during training.\n",
843
+ "\n",
844
+ "We can leverage the `WhisperProcessor` we defined earlier to perform both the \n",
845
+ "feature extractor and the tokenizer operations:"
846
+ ]
847
+ },
848
+ {
849
+ "cell_type": "code",
850
+ "execution_count": null,
851
+ "id": "8326221e-ec13-4731-bb4e-51e5fc1486c5",
852
+ "metadata": {
853
+ "id": "8326221e-ec13-4731-bb4e-51e5fc1486c5"
854
+ },
855
+ "outputs": [],
856
+ "source": [
857
+ "import torch\n",
858
+ "\n",
859
+ "from dataclasses import dataclass\n",
860
+ "from typing import Any, Dict, List, Union\n",
861
+ "\n",
862
+ "@dataclass\n",
863
+ "class DataCollatorSpeechSeq2SeqWithPadding:\n",
864
+ " processor: Any\n",
865
+ "\n",
866
+ " def __call__(self, features: List[Dict[str, Union[List[int], torch.Tensor]]]) -> Dict[str, torch.Tensor]:\n",
867
+ " # split inputs and labels since they have to be of different lengths and need different padding methods\n",
868
+ " # first treat the audio inputs by simply returning torch tensors\n",
869
+ " input_features = [{\"input_features\": feature[\"input_features\"]} for feature in features]\n",
870
+ " batch = self.processor.feature_extractor.pad(input_features, return_tensors=\"pt\")\n",
871
+ "\n",
872
+ " # get the tokenized label sequences\n",
873
+ " label_features = [{\"input_ids\": feature[\"labels\"]} for feature in features]\n",
874
+ " # pad the labels to max length\n",
875
+ " labels_batch = self.processor.tokenizer.pad(label_features, return_tensors=\"pt\")\n",
876
+ "\n",
877
+ " # replace padding with -100 to ignore loss correctly\n",
878
+ " labels = labels_batch[\"input_ids\"].masked_fill(labels_batch.attention_mask.ne(1), -100)\n",
879
+ "\n",
880
+ " # if bos token is appended in previous tokenization step,\n",
881
+ " # cut bos token here as it's append later anyways\n",
882
+ " if (labels[:, 0] == self.processor.tokenizer.bos_token_id).all().cpu().item():\n",
883
+ " labels = labels[:, 1:]\n",
884
+ "\n",
885
+ " batch[\"labels\"] = labels\n",
886
+ "\n",
887
+ " return batch"
888
+ ]
889
+ },
890
+ {
891
+ "cell_type": "markdown",
892
+ "id": "3cae7dbf-8a50-456e-a3a8-7fd005390f86",
893
+ "metadata": {
894
+ "id": "3cae7dbf-8a50-456e-a3a8-7fd005390f86"
895
+ },
896
+ "source": [
897
+ "Let's initialise the data collator we've just defined:"
898
+ ]
899
+ },
900
+ {
901
+ "cell_type": "code",
902
+ "execution_count": null,
903
+ "id": "fc834702-c0d3-4a96-b101-7b87be32bf42",
904
+ "metadata": {
905
+ "id": "fc834702-c0d3-4a96-b101-7b87be32bf42"
906
+ },
907
+ "outputs": [],
908
+ "source": [
909
+ "data_collator = DataCollatorSpeechSeq2SeqWithPadding(processor=processor)"
910
+ ]
911
+ },
912
+ {
913
+ "cell_type": "markdown",
914
+ "id": "d62bb2ab-750a-45e7-82e9-61d6f4805698",
915
+ "metadata": {
916
+ "id": "d62bb2ab-750a-45e7-82e9-61d6f4805698"
917
+ },
918
+ "source": [
919
+ "### Evaluation Metrics"
920
+ ]
921
+ },
922
+ {
923
+ "cell_type": "markdown",
924
+ "id": "66fee1a7-a44c-461e-b047-c3917221572e",
925
+ "metadata": {
926
+ "id": "66fee1a7-a44c-461e-b047-c3917221572e"
927
+ },
928
+ "source": [
929
+ "We'll use the word error rate (WER) metric, the 'de-facto' metric for assessing \n",
930
+ "ASR systems. For more information, refer to the WER [docs](https://huggingface.co/metrics/wer). We'll load the WER metric from 🤗 Evaluate:"
931
+ ]
932
+ },
933
+ {
934
+ "cell_type": "code",
935
+ "execution_count": null,
936
+ "id": "b22b4011-f31f-4b57-b684-c52332f92890",
937
+ "metadata": {
938
+ "id": "b22b4011-f31f-4b57-b684-c52332f92890"
939
+ },
940
+ "outputs": [],
941
+ "source": [
942
+ "import evaluate\n",
943
+ "\n",
944
+ "metric = evaluate.load(\"wer\")"
945
+ ]
946
+ },
947
+ {
948
+ "cell_type": "markdown",
949
+ "id": "4f32cab6-31f0-4cb9-af4c-40ba0f5fc508",
950
+ "metadata": {
951
+ "id": "4f32cab6-31f0-4cb9-af4c-40ba0f5fc508"
952
+ },
953
+ "source": [
954
+ "We then simply have to define a function that takes our model \n",
955
+ "predictions and returns the WER metric. This function, called\n",
956
+ "`compute_metrics`, first replaces `-100` with the `pad_token_id`\n",
957
+ "in the `label_ids` (undoing the step we applied in the \n",
958
+ "data collator to ignore padded tokens correctly in the loss).\n",
959
+ "It then decodes the predicted and label ids to strings. Finally,\n",
960
+ "it computes the WER between the predictions and reference labels. \n",
961
+ "Here, we have the option of evaluating with the 'normalised' transcriptions \n",
962
+ "and predictions. We recommend you set this to `True` to benefit from the WER \n",
963
+ "improvement obtained by normalising the transcriptions."
964
+ ]
965
+ },
966
+ {
967
+ "cell_type": "code",
968
+ "execution_count": null,
969
+ "id": "23959a70-22d0-4ffe-9fa1-72b61e75bb52",
970
+ "metadata": {
971
+ "id": "23959a70-22d0-4ffe-9fa1-72b61e75bb52"
972
+ },
973
+ "outputs": [],
974
+ "source": [
975
+ "# evaluate with the 'normalised' WER\n",
976
+ "do_normalize_eval = True\n",
977
+ "\n",
978
+ "def compute_metrics(pred):\n",
979
+ " pred_ids = pred.predictions\n",
980
+ " label_ids = pred.label_ids\n",
981
+ "\n",
982
+ " # replace -100 with the pad_token_id\n",
983
+ " label_ids[label_ids == -100] = processor.tokenizer.pad_token_id\n",
984
+ "\n",
985
+ " # we do not want to group tokens when computing the metrics\n",
986
+ " pred_str = processor.tokenizer.batch_decode(pred_ids, skip_special_tokens=True)\n",
987
+ " label_str = processor.tokenizer.batch_decode(label_ids, skip_special_tokens=True)\n",
988
+ "\n",
989
+ " if do_normalize_eval:\n",
990
+ " pred_str = [normalizer(pred) for pred in pred_str]\n",
991
+ " label_str = [normalizer(label) for label in label_str]\n",
992
+ "\n",
993
+ " wer = 100 * metric.compute(predictions=pred_str, references=label_str)\n",
994
+ "\n",
995
+ " return {\"wer\": wer}"
996
+ ]
997
+ },
998
+ {
999
+ "cell_type": "markdown",
1000
+ "id": "daf2a825-6d9f-4a23-b145-c37c0039075b",
1001
+ "metadata": {
1002
+ "id": "daf2a825-6d9f-4a23-b145-c37c0039075b"
1003
+ },
1004
+ "source": [
1005
+ "### Load a Pre-Trained Checkpoint"
1006
+ ]
1007
+ },
1008
+ {
1009
+ "cell_type": "markdown",
1010
+ "id": "437a97fa-4864-476b-8abc-f28b8166cfa5",
1011
+ "metadata": {
1012
+ "id": "437a97fa-4864-476b-8abc-f28b8166cfa5"
1013
+ },
1014
+ "source": [
1015
+ "Now let's load the pre-trained Whisper `small` checkpoint. Again, this \n",
1016
+ "is trivial through use of 🤗 Transformers!"
1017
+ ]
1018
+ },
1019
+ {
1020
+ "cell_type": "code",
1021
+ "execution_count": null,
1022
+ "id": "5a10cc4b-07ec-4ebd-ac1d-7c601023594f",
1023
+ "metadata": {
1024
+ "id": "5a10cc4b-07ec-4ebd-ac1d-7c601023594f"
1025
+ },
1026
+ "outputs": [],
1027
+ "source": [
1028
+ "from transformers import WhisperForConditionalGeneration\n",
1029
+ "\n",
1030
+ "model = WhisperForConditionalGeneration.from_pretrained(model_name)"
1031
+ ]
1032
+ },
1033
+ {
1034
+ "cell_type": "markdown",
1035
+ "id": "a15ead5f-2277-4a39-937b-585c2497b2df",
1036
+ "metadata": {
1037
+ "id": "a15ead5f-2277-4a39-937b-585c2497b2df"
1038
+ },
1039
+ "source": [
1040
+ "Override generation arguments - no tokens are forced as decoder outputs (see [`forced_decoder_ids`](https://huggingface.co/docs/transformers/main_classes/text_generation#transformers.generation_utils.GenerationMixin.generate.forced_decoder_ids)), no tokens are suppressed during generation (see [`suppress_tokens`](https://huggingface.co/docs/transformers/main_classes/text_generation#transformers.generation_utils.GenerationMixin.generate.suppress_tokens)). Set `use_cache` to False since we're using gradient checkpointing, and the two are incompatible:"
1041
+ ]
1042
+ },
1043
+ {
1044
+ "cell_type": "code",
1045
+ "execution_count": null,
1046
+ "id": "62038ba3-88ed-4fce-84db-338f50dcd04f",
1047
+ "metadata": {
1048
+ "id": "62038ba3-88ed-4fce-84db-338f50dcd04f"
1049
+ },
1050
+ "outputs": [],
1051
+ "source": [
1052
+ "model.config.forced_decoder_ids = None\n",
1053
+ "model.config.suppress_tokens = []\n",
1054
+ "model.config.use_cache = False"
1055
+ ]
1056
+ },
1057
+ {
1058
+ "cell_type": "markdown",
1059
+ "id": "2178dea4-80ca-47b6-b6ea-ba1915c90c06",
1060
+ "metadata": {
1061
+ "id": "2178dea4-80ca-47b6-b6ea-ba1915c90c06"
1062
+ },
1063
+ "source": [
1064
+ "### Define the Training Configuration"
1065
+ ]
1066
+ },
1067
+ {
1068
+ "cell_type": "markdown",
1069
+ "id": "c21af1e9-0188-4134-ac82-defc7bdcc436",
1070
+ "metadata": {
1071
+ "id": "c21af1e9-0188-4134-ac82-defc7bdcc436"
1072
+ },
1073
+ "source": [
1074
+ "In the final step, we define all the parameters related to training. For more detail on the training arguments, refer to the Seq2SeqTrainingArguments [docs](https://huggingface.co/docs/transformers/main_classes/trainer#transformers.Seq2SeqTrainingArguments)."
1075
+ ]
1076
+ },
1077
+ {
1078
+ "cell_type": "code",
1079
+ "execution_count": null,
1080
+ "id": "0ae3e9af-97b7-4aa0-ae85-20b23b5bcb3a",
1081
+ "metadata": {
1082
+ "id": "0ae3e9af-97b7-4aa0-ae85-20b23b5bcb3a"
1083
+ },
1084
+ "outputs": [],
1085
+ "source": [
1086
+ "from transformers import Seq2SeqTrainingArguments\n",
1087
+ "\n",
1088
+ "training_args = Seq2SeqTrainingArguments(\n",
1089
+ " output_dir=\"./\",\n",
1090
+ " per_device_train_batch_size=64,\n",
1091
+ " gradient_accumulation_steps=1, # increase by 2x for every 2x decrease in batch size\n",
1092
+ " learning_rate=1e-5,\n",
1093
+ " warmup_steps=500,\n",
1094
+ " max_steps=5000,\n",
1095
+ " gradient_checkpointing=True,\n",
1096
+ " fp16=True,\n",
1097
+ " evaluation_strategy=\"steps\",\n",
1098
+ " per_device_eval_batch_size=8,\n",
1099
+ " predict_with_generate=True,\n",
1100
+ " generation_max_length=225,\n",
1101
+ " save_steps=1000,\n",
1102
+ " eval_steps=1000,\n",
1103
+ " logging_steps=25,\n",
1104
+ " report_to=[\"tensorboard\"],\n",
1105
+ " load_best_model_at_end=True,\n",
1106
+ " metric_for_best_model=\"wer\",\n",
1107
+ " greater_is_better=False,\n",
1108
+ " push_to_hub=True,\n",
1109
+ ")"
1110
+ ]
1111
+ },
1112
+ {
1113
+ "cell_type": "markdown",
1114
+ "id": "b3a944d8-3112-4552-82a0-be25988b3857",
1115
+ "metadata": {
1116
+ "id": "b3a944d8-3112-4552-82a0-be25988b3857"
1117
+ },
1118
+ "source": [
1119
+ "**Note**: if one does not want to upload the model checkpoints to the Hub, \n",
1120
+ "set `push_to_hub=False`."
1121
+ ]
1122
+ },
1123
+ {
1124
+ "cell_type": "markdown",
1125
+ "id": "bac29114-d226-4f54-97cf-8718c9f94e1e",
1126
+ "metadata": {
1127
+ "id": "bac29114-d226-4f54-97cf-8718c9f94e1e"
1128
+ },
1129
+ "source": [
1130
+ "We can forward the training arguments to the 🤗 Trainer along with our model,\n",
1131
+ "dataset, data collator and `compute_metrics` function:"
1132
+ ]
1133
+ },
1134
+ {
1135
+ "cell_type": "code",
1136
+ "execution_count": null,
1137
+ "id": "d546d7fe-0543-479a-b708-2ebabec19493",
1138
+ "metadata": {
1139
+ "id": "d546d7fe-0543-479a-b708-2ebabec19493"
1140
+ },
1141
+ "outputs": [],
1142
+ "source": [
1143
+ "from transformers import Seq2SeqTrainer\n",
1144
+ "\n",
1145
+ "trainer = Seq2SeqTrainer(\n",
1146
+ " args=training_args,\n",
1147
+ " model=model,\n",
1148
+ " train_dataset=common_voice[\"train\"],\n",
1149
+ " eval_dataset=common_voice[\"test\"],\n",
1150
+ " data_collator=data_collator,\n",
1151
+ " compute_metrics=compute_metrics,\n",
1152
+ " tokenizer=processor.feature_extractor,\n",
1153
+ ")"
1154
+ ]
1155
+ },
1156
+ {
1157
+ "cell_type": "markdown",
1158
+ "id": "uOrRhDGtN5S4",
1159
+ "metadata": {
1160
+ "id": "uOrRhDGtN5S4"
1161
+ },
1162
+ "source": [
1163
+ "We'll save the processor object once before starting training. Since the processor is not trainable, it won't change over the course of training:"
1164
+ ]
1165
+ },
1166
+ {
1167
+ "cell_type": "code",
1168
+ "execution_count": null,
1169
+ "id": "-2zQwMfEOBJq",
1170
+ "metadata": {
1171
+ "id": "-2zQwMfEOBJq"
1172
+ },
1173
+ "outputs": [],
1174
+ "source": [
1175
+ "processor.save_pretrained(training_args.output_dir)"
1176
+ ]
1177
+ },
1178
+ {
1179
+ "cell_type": "markdown",
1180
+ "id": "7f404cf9-4345-468c-8196-4bd101d9bd51",
1181
+ "metadata": {
1182
+ "id": "7f404cf9-4345-468c-8196-4bd101d9bd51"
1183
+ },
1184
+ "source": [
1185
+ "### Training"
1186
+ ]
1187
+ },
1188
+ {
1189
+ "cell_type": "markdown",
1190
+ "id": "5e8b8d56-5a70-4f68-bd2e-f0752d0bd112",
1191
+ "metadata": {
1192
+ "id": "5e8b8d56-5a70-4f68-bd2e-f0752d0bd112"
1193
+ },
1194
+ "source": [
1195
+ "Training will take approximately 5-10 hours depending on your GPU. The peak GPU memory for the given training configuration is approximately 36GB. \n",
1196
+ "Depending on your GPU, it is possible that you will encounter a CUDA `\"out-of-memory\"` error when you launch training. \n",
1197
+ "In this case, you can reduce the `per_device_train_batch_size` incrementally by factors of 2 \n",
1198
+ "and employ [`gradient_accumulation_steps`](https://huggingface.co/docs/transformers/main_classes/trainer#transformers.Seq2SeqTrainingArguments.gradient_accumulation_steps)\n",
1199
+ "to compensate.\n",
1200
+ "\n",
1201
+ "To launch training, simply execute:"
1202
+ ]
1203
+ },
1204
+ {
1205
+ "cell_type": "code",
1206
+ "execution_count": null,
1207
+ "id": "ee8b7b8e-1c9a-4d77-9137-1778a629e6de",
1208
+ "metadata": {
1209
+ "id": "ee8b7b8e-1c9a-4d77-9137-1778a629e6de"
1210
+ },
1211
+ "outputs": [],
1212
+ "source": [
1213
+ "trainer.train()"
1214
+ ]
1215
+ },
1216
+ {
1217
+ "cell_type": "markdown",
1218
+ "id": "810ced54-7187-4a06-b2fe-ba6dcca94dc3",
1219
+ "metadata": {
1220
+ "id": "810ced54-7187-4a06-b2fe-ba6dcca94dc3"
1221
+ },
1222
+ "source": [
1223
+ "We can label our checkpoint with the `whisper-event` tag on push by setting the appropriate key-word arguments (kwargs):"
1224
+ ]
1225
+ },
1226
+ {
1227
+ "cell_type": "code",
1228
+ "execution_count": null,
1229
+ "id": "c704f91e-241b-48c9-b8e0-f0da396a9663",
1230
+ "metadata": {
1231
+ "id": "c704f91e-241b-48c9-b8e0-f0da396a9663"
1232
+ },
1233
+ "outputs": [],
1234
+ "source": [
1235
+ "kwargs = {\n",
1236
+ " \"dataset_tags\": \"mozilla-foundation/common_voice_11_0\",\n",
1237
+ " \"dataset\": \"Common Voice 11.0\", # a 'pretty' name for the training dataset\n",
1238
+ " \"language\": \"ar\",\n",
1239
+ " \"model_name\": \"Whisper Small ar - Zaid Alyafeai\", # a 'pretty' name for your model\n",
1240
+ " \"finetuned_from\": model_name,\n",
1241
+ " \"tasks\": \"automatic-speech-recognition\",\n",
1242
+ " \"tags\": \"whisper-event\",\n",
1243
+ "}"
1244
+ ]
1245
+ },
1246
+ {
1247
+ "cell_type": "markdown",
1248
+ "id": "090d676a-f944-4297-a938-a40eda0b2b68",
1249
+ "metadata": {
1250
+ "id": "090d676a-f944-4297-a938-a40eda0b2b68"
1251
+ },
1252
+ "source": [
1253
+ "The training results can now be uploaded to the Hub. To do so, execute the `push_to_hub` command and save the preprocessor object we created:"
1254
+ ]
1255
+ },
1256
+ {
1257
+ "cell_type": "code",
1258
+ "execution_count": null,
1259
+ "id": "d7030622-caf7-4039-939b-6195cdaa2585",
1260
+ "metadata": {
1261
+ "id": "d7030622-caf7-4039-939b-6195cdaa2585"
1262
+ },
1263
+ "outputs": [],
1264
+ "source": [
1265
+ "trainer.push_to_hub(**kwargs)"
1266
+ ]
1267
+ },
1268
+ {
1269
+ "cell_type": "markdown",
1270
+ "id": "ca743fbd-602c-48d4-ba8d-a2fe60af64ba",
1271
+ "metadata": {
1272
+ "id": "ca743fbd-602c-48d4-ba8d-a2fe60af64ba"
1273
+ },
1274
+ "source": [
1275
+ "## Closing Remarks"
1276
+ ]
1277
+ },
1278
+ {
1279
+ "cell_type": "markdown",
1280
+ "id": "7f737783-2870-4e35-aa11-86a42d7d997a",
1281
+ "metadata": {
1282
+ "id": "7f737783-2870-4e35-aa11-86a42d7d997a"
1283
+ },
1284
+ "source": [
1285
+ "In this blog, we covered a step-by-step guide on fine-tuning Whisper for multilingual ASR \n",
1286
+ "using 🤗 Datasets, Transformers and the Hugging Face Hub. For more details on the Whisper model, the Common Voice dataset and the theory behind fine-tuning, refere to the accompanying [blog post](https://huggingface.co/blog/fine-tune-whisper). If you're interested in fine-tuning other \n",
1287
+ "Transformers models, both for English and multilingual ASR, be sure to check out the \n",
1288
+ "examples scripts at [examples/pytorch/speech-recognition](https://github.com/huggingface/transformers/tree/main/examples/pytorch/speech-recognition)."
1289
+ ]
1290
+ }
1291
+ ],
1292
+ "metadata": {
1293
+ "colab": {
1294
+ "include_colab_link": true,
1295
+ "provenance": []
1296
+ },
1297
+ "kernelspec": {
1298
+ "display_name": "Python 3",
1299
+ "language": "python",
1300
+ "name": "python3"
1301
+ },
1302
+ "language_info": {
1303
+ "codemirror_mode": {
1304
+ "name": "ipython",
1305
+ "version": 3
1306
+ },
1307
+ "file_extension": ".py",
1308
+ "mimetype": "text/x-python",
1309
+ "name": "python",
1310
+ "nbconvert_exporter": "python",
1311
+ "pygments_lexer": "ipython3",
1312
+ "version": "3.8.10"
1313
+ },
1314
+ "vscode": {
1315
+ "interpreter": {
1316
+ "hash": "f9f85f796d01129d0dd105a088854619f454435301f6ffec2fea96ecbd9be4ac"
1317
+ }
1318
+ }
1319
+ },
1320
+ "nbformat": 4,
1321
+ "nbformat_minor": 5
1322
+ }
fine-tune-whisper-non-streaming.ipynb.1 ADDED
@@ -0,0 +1,1207 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "id": "75b58048-7d14-4fc6-8085-1fc08c81b4a6",
6
+ "metadata": {
7
+ "id": "75b58048-7d14-4fc6-8085-1fc08c81b4a6"
8
+ },
9
+ "source": [
10
+ "# Fine-Tune Whisper For Multilingual ASR with 🤗 Transformers"
11
+ ]
12
+ },
13
+ {
14
+ "cell_type": "markdown",
15
+ "id": "fbfa8ad5-4cdc-4512-9058-836cbbf65e1a",
16
+ "metadata": {
17
+ "id": "fbfa8ad5-4cdc-4512-9058-836cbbf65e1a"
18
+ },
19
+ "source": [
20
+ "In this Colab, we present a step-by-step guide on how to fine-tune Whisper \n",
21
+ "for any multilingual ASR dataset using Hugging Face 🤗 Transformers. This is a \n",
22
+ "more \"hands-on\" version of the accompanying [blog post](https://huggingface.co/blog/fine-tune-whisper). \n",
23
+ "For a more in-depth explanation of Whisper, the Common Voice dataset and the theory behind fine-tuning, the reader is advised to refer to the blog post."
24
+ ]
25
+ },
26
+ {
27
+ "cell_type": "markdown",
28
+ "id": "afe0d503-ae4e-4aa7-9af4-dbcba52db41e",
29
+ "metadata": {
30
+ "id": "afe0d503-ae4e-4aa7-9af4-dbcba52db41e"
31
+ },
32
+ "source": [
33
+ "## Introduction"
34
+ ]
35
+ },
36
+ {
37
+ "cell_type": "markdown",
38
+ "id": "9ae91ed4-9c3e-4ade-938e-f4c2dcfbfdc0",
39
+ "metadata": {
40
+ "id": "9ae91ed4-9c3e-4ade-938e-f4c2dcfbfdc0"
41
+ },
42
+ "source": [
43
+ "Whisper is a pre-trained model for automatic speech recognition (ASR) \n",
44
+ "published in [September 2022](https://openai.com/blog/whisper/) by the authors \n",
45
+ "Alec Radford et al. from OpenAI. Unlike many of its predecessors, such as \n",
46
+ "[Wav2Vec 2.0](https://arxiv.org/abs/2006.11477), which are pre-trained \n",
47
+ "on un-labelled audio data, Whisper is pre-trained on a vast quantity of \n",
48
+ "**labelled** audio-transcription data, 680,000 hours to be precise. \n",
49
+ "This is an order of magnitude more data than the un-labelled audio data used \n",
50
+ "to train Wav2Vec 2.0 (60,000 hours). What is more, 117,000 hours of this \n",
51
+ "pre-training data is multilingual ASR data. This results in checkpoints \n",
52
+ "that can be applied to over 96 languages, many of which are considered \n",
53
+ "_low-resource_.\n",
54
+ "\n",
55
+ "When scaled to 680,000 hours of labelled pre-training data, Whisper models \n",
56
+ "demonstrate a strong ability to generalise to many datasets and domains.\n",
57
+ "The pre-trained checkpoints achieve competitive results to state-of-the-art \n",
58
+ "ASR systems, with near 3% word error rate (WER) on the test-clean subset of \n",
59
+ "LibriSpeech ASR and a new state-of-the-art on TED-LIUM with 4.7% WER (_c.f._ \n",
60
+ "Table 8 of the [Whisper paper](https://cdn.openai.com/papers/whisper.pdf)).\n",
61
+ "The extensive multilingual ASR knowledge acquired by Whisper during pre-training \n",
62
+ "can be leveraged for other low-resource languages; through fine-tuning, the \n",
63
+ "pre-trained checkpoints can be adapted for specific datasets and languages \n",
64
+ "to further improve upon these results. We'll show just how Whisper can be fine-tuned \n",
65
+ "for low-resource languages in this Colab."
66
+ ]
67
+ },
68
+ {
69
+ "cell_type": "markdown",
70
+ "id": "e59b91d6-be24-4b5e-bb38-4977ea143a72",
71
+ "metadata": {
72
+ "id": "e59b91d6-be24-4b5e-bb38-4977ea143a72"
73
+ },
74
+ "source": [
75
+ "<figure>\n",
76
+ "<img src=\"https://raw.githubusercontent.com/sanchit-gandhi/notebooks/main/whisper_architecture.svg\" alt=\"Trulli\" style=\"width:100%\">\n",
77
+ "<figcaption align = \"center\"><b>Figure 1:</b> Whisper model. The architecture \n",
78
+ "follows the standard Transformer-based encoder-decoder model. A \n",
79
+ "log-Mel spectrogram is input to the encoder. The last encoder \n",
80
+ "hidden states are input to the decoder via cross-attention mechanisms. The \n",
81
+ "decoder autoregressively predicts text tokens, jointly conditional on the \n",
82
+ "encoder hidden states and previously predicted tokens. Figure source: \n",
83
+ "<a href=\"https://openai.com/blog/whisper/\">OpenAI Whisper Blog</a>.</figcaption>\n",
84
+ "</figure>"
85
+ ]
86
+ },
87
+ {
88
+ "cell_type": "markdown",
89
+ "id": "21b6316e-8a55-4549-a154-66d3da2ab74a",
90
+ "metadata": {
91
+ "id": "21b6316e-8a55-4549-a154-66d3da2ab74a"
92
+ },
93
+ "source": [
94
+ "The Whisper checkpoints come in five configurations of varying model sizes.\n",
95
+ "The smallest four are trained on either English-only or multilingual data.\n",
96
+ "The largest checkpoint is multilingual only. All nine of the pre-trained checkpoints \n",
97
+ "are available on the [Hugging Face Hub](https://huggingface.co/models?search=openai/whisper). The \n",
98
+ "checkpoints are summarised in the following table with links to the models on the Hub:\n",
99
+ "\n",
100
+ "| Size | Layers | Width | Heads | Parameters | English-only | Multilingual |\n",
101
+ "|--------|--------|-------|-------|------------|------------------------------------------------------|---------------------------------------------------|\n",
102
+ "| tiny | 4 | 384 | 6 | 39 M | [✓](https://huggingface.co/openai/whisper-tiny.en) | [✓](https://huggingface.co/openai/whisper-tiny.) |\n",
103
+ "| base | 6 | 512 | 8 | 74 M | [✓](https://huggingface.co/openai/whisper-base.en) | [✓](https://huggingface.co/openai/whisper-base) |\n",
104
+ "| small | 12 | 768 | 12 | 244 M | [✓](https://huggingface.co/openai/whisper-small.en) | [✓](https://huggingface.co/openai/whisper-small) |\n",
105
+ "| medium | 24 | 1024 | 16 | 769 M | [✓](https://huggingface.co/openai/whisper-medium.en) | [✓](https://huggingface.co/openai/whisper-medium) |\n",
106
+ "| large | 32 | 1280 | 20 | 1550 M | x | [✓](https://huggingface.co/openai/whisper-large) |\n",
107
+ "\n",
108
+ "For demonstration purposes, we'll fine-tune the multilingual version of the \n",
109
+ "[`\"small\"`](https://huggingface.co/openai/whisper-small) checkpoint with 244M params (~= 1GB). \n",
110
+ "As for our data, we'll train and evaluate our system on a low-resource language \n",
111
+ "taken from the [Common Voice](https://huggingface.co/datasets/mozilla-foundation/common_voice_11_0)\n",
112
+ "dataset. We'll show that with as little as 8 hours of fine-tuning data, we can achieve \n",
113
+ "strong performance in this language."
114
+ ]
115
+ },
116
+ {
117
+ "cell_type": "markdown",
118
+ "id": "3a680dfc-cbba-4f6c-8a1f-e1a5ff3f123a",
119
+ "metadata": {
120
+ "id": "3a680dfc-cbba-4f6c-8a1f-e1a5ff3f123a"
121
+ },
122
+ "source": [
123
+ "------------------------------------------------------------------------\n",
124
+ "\n",
125
+ "\\\\({}^1\\\\) The name Whisper follows from the acronym “WSPSR”, which stands for “Web-scale Supervised Pre-training for Speech Recognition”."
126
+ ]
127
+ },
128
+ {
129
+ "cell_type": "markdown",
130
+ "id": "b219c9dd-39b6-4a95-b2a1-3f547a1e7bc0",
131
+ "metadata": {
132
+ "id": "b219c9dd-39b6-4a95-b2a1-3f547a1e7bc0"
133
+ },
134
+ "source": [
135
+ "## Load Dataset"
136
+ ]
137
+ },
138
+ {
139
+ "cell_type": "markdown",
140
+ "id": "674429c5-0ab4-4adf-975b-621bb69eca38",
141
+ "metadata": {
142
+ "id": "674429c5-0ab4-4adf-975b-621bb69eca38"
143
+ },
144
+ "source": [
145
+ "Using 🤗 Datasets, downloading and preparing data is extremely simple. \n",
146
+ "We can download and prepare the Common Voice splits in just one line of code. \n",
147
+ "\n",
148
+ "First, ensure you have accepted the terms of use on the Hugging Face Hub: [mozilla-foundation/common_voice_11_0](https://huggingface.co/datasets/mozilla-foundation/common_voice_11_0). Once you have accepted the terms, you will have full access to the dataset and be able to download the data locally.\n",
149
+ "\n",
150
+ "Since Hindi is very low-resource, we'll combine the `train` and `validation` \n",
151
+ "splits to give approximately 8 hours of training data. We'll use the 4 hours \n",
152
+ "of `test` data as our held-out test set:"
153
+ ]
154
+ },
155
+ {
156
+ "cell_type": "code",
157
+ "execution_count": null,
158
+ "id": "a2787582-554f-44ce-9f38-4180a5ed6b44",
159
+ "metadata": {
160
+ "id": "a2787582-554f-44ce-9f38-4180a5ed6b44"
161
+ },
162
+ "outputs": [],
163
+ "source": [
164
+ "from datasets import load_dataset, DatasetDict\n",
165
+ "\n",
166
+ "common_voice = DatasetDict()\n",
167
+ "\n",
168
+ "common_voice[\"train\"] = load_dataset(\"mozilla-foundation/common_voice_11_0\", \"hi\", split=\"train+validation\", use_auth_token=True)\n",
169
+ "common_voice[\"test\"] = load_dataset(\"mozilla-foundation/common_voice_11_0\", \"hi\", split=\"test\", use_auth_token=True)\n",
170
+ "\n",
171
+ "print(common_voice)"
172
+ ]
173
+ },
174
+ {
175
+ "cell_type": "markdown",
176
+ "id": "d5c7c3d6-7197-41e7-a088-49b753c1681f",
177
+ "metadata": {
178
+ "id": "d5c7c3d6-7197-41e7-a088-49b753c1681f"
179
+ },
180
+ "source": [
181
+ "Most ASR datasets only provide input audio samples (`audio`) and the \n",
182
+ "corresponding transcribed text (`sentence`). Common Voice contains additional \n",
183
+ "metadata information, such as `accent` and `locale`, which we can disregard for ASR.\n",
184
+ "Keeping the notebook as general as possible, we only consider the input audio and\n",
185
+ "transcribed text for fine-tuning, discarding the additional metadata information:"
186
+ ]
187
+ },
188
+ {
189
+ "cell_type": "code",
190
+ "execution_count": null,
191
+ "id": "20ba635d-518c-47ac-97ee-3cad25f1e0ce",
192
+ "metadata": {
193
+ "id": "20ba635d-518c-47ac-97ee-3cad25f1e0ce"
194
+ },
195
+ "outputs": [],
196
+ "source": [
197
+ "common_voice = common_voice.remove_columns([\"accent\", \"age\", \"client_id\", \"down_votes\", \"gender\", \"locale\", \"path\", \"segment\", \"up_votes\"])\n",
198
+ "\n",
199
+ "print(common_voice)"
200
+ ]
201
+ },
202
+ {
203
+ "cell_type": "markdown",
204
+ "id": "2d63b2d2-f68a-4d74-b7f1-5127f6d16605",
205
+ "metadata": {
206
+ "id": "2d63b2d2-f68a-4d74-b7f1-5127f6d16605"
207
+ },
208
+ "source": [
209
+ "## Prepare Feature Extractor, Tokenizer and Data"
210
+ ]
211
+ },
212
+ {
213
+ "cell_type": "markdown",
214
+ "id": "601c3099-1026-439e-93e2-5635b3ba5a73",
215
+ "metadata": {
216
+ "id": "601c3099-1026-439e-93e2-5635b3ba5a73"
217
+ },
218
+ "source": [
219
+ "The ASR pipeline can be de-composed into three stages: \n",
220
+ "1) A feature extractor which pre-processes the raw audio-inputs\n",
221
+ "2) The model which performs the sequence-to-sequence mapping \n",
222
+ "3) A tokenizer which post-processes the model outputs to text format\n",
223
+ "\n",
224
+ "In 🤗 Transformers, the Whisper model has an associated feature extractor and tokenizer, \n",
225
+ "called [WhisperFeatureExtractor](https://huggingface.co/docs/transformers/main/model_doc/whisper#transformers.WhisperFeatureExtractor)\n",
226
+ "and [WhisperTokenizer](https://huggingface.co/docs/transformers/main/model_doc/whisper#transformers.WhisperTokenizer) \n",
227
+ "respectively.\n",
228
+ "\n",
229
+ "We'll go through details for setting-up the feature extractor and tokenizer one-by-one!"
230
+ ]
231
+ },
232
+ {
233
+ "cell_type": "markdown",
234
+ "id": "560332eb-3558-41a1-b500-e83a9f695f84",
235
+ "metadata": {
236
+ "id": "560332eb-3558-41a1-b500-e83a9f695f84"
237
+ },
238
+ "source": [
239
+ "### Load WhisperFeatureExtractor"
240
+ ]
241
+ },
242
+ {
243
+ "cell_type": "markdown",
244
+ "id": "32ec8068-0bd7-412d-b662-0edb9d1e7365",
245
+ "metadata": {
246
+ "id": "32ec8068-0bd7-412d-b662-0edb9d1e7365"
247
+ },
248
+ "source": [
249
+ "The Whisper feature extractor performs two operations:\n",
250
+ "1. Pads / truncates the audio inputs to 30s: any audio inputs shorter than 30s are padded to 30s with silence (zeros), and those longer that 30s are truncated to 30s\n",
251
+ "2. Converts the audio inputs to _log-Mel spectrogram_ input features, a visual representation of the audio and the form of the input expected by the Whisper model"
252
+ ]
253
+ },
254
+ {
255
+ "cell_type": "markdown",
256
+ "id": "589d9ec1-d12b-4b64-93f7-04c63997da19",
257
+ "metadata": {
258
+ "id": "589d9ec1-d12b-4b64-93f7-04c63997da19"
259
+ },
260
+ "source": [
261
+ "<figure>\n",
262
+ "<img src=\"https://raw.githubusercontent.com/sanchit-gandhi/notebooks/main/spectrogram.jpg\" alt=\"Trulli\" style=\"width:100%\">\n",
263
+ "<figcaption align = \"center\"><b>Figure 2:</b> Conversion of sampled audio array to log-Mel spectrogram.\n",
264
+ "Left: sampled 1-dimensional audio signal. Right: corresponding log-Mel spectrogram. Figure source:\n",
265
+ "<a href=\"https://ai.googleblog.com/2019/04/specaugment-new-data-augmentation.html\">Google SpecAugment Blog</a>.\n",
266
+ "</figcaption>"
267
+ ]
268
+ },
269
+ {
270
+ "cell_type": "markdown",
271
+ "id": "b2ef54d5-b946-4c1d-9fdc-adc5d01b46aa",
272
+ "metadata": {
273
+ "id": "b2ef54d5-b946-4c1d-9fdc-adc5d01b46aa"
274
+ },
275
+ "source": [
276
+ "We'll load the feature extractor from the pre-trained checkpoint with the default values:"
277
+ ]
278
+ },
279
+ {
280
+ "cell_type": "code",
281
+ "execution_count": null,
282
+ "id": "bc77d7bb-f9e2-47f5-b663-30f7a4321ce5",
283
+ "metadata": {
284
+ "id": "bc77d7bb-f9e2-47f5-b663-30f7a4321ce5"
285
+ },
286
+ "outputs": [],
287
+ "source": [
288
+ "from transformers import WhisperFeatureExtractor\n",
289
+ "\n",
290
+ "feature_extractor = WhisperFeatureExtractor.from_pretrained(\"openai/whisper-small\")"
291
+ ]
292
+ },
293
+ {
294
+ "cell_type": "markdown",
295
+ "id": "93748af7-b917-4ecf-a0c8-7d89077ff9cb",
296
+ "metadata": {
297
+ "id": "93748af7-b917-4ecf-a0c8-7d89077ff9cb"
298
+ },
299
+ "source": [
300
+ "### Load WhisperTokenizer"
301
+ ]
302
+ },
303
+ {
304
+ "cell_type": "markdown",
305
+ "id": "2bc82609-a9fb-447a-a2af-99597c864029",
306
+ "metadata": {
307
+ "id": "2bc82609-a9fb-447a-a2af-99597c864029"
308
+ },
309
+ "source": [
310
+ "The Whisper model outputs a sequence of _token ids_. The tokenizer maps each of these token ids to their corresponding text string. For Hindi, we can load the pre-trained tokenizer and use it for fine-tuning without any further modifications. We simply have to \n",
311
+ "specify the target language and the task. These arguments inform the \n",
312
+ "tokenizer to prefix the language and task tokens to the start of encoded \n",
313
+ "label sequences:"
314
+ ]
315
+ },
316
+ {
317
+ "cell_type": "code",
318
+ "execution_count": null,
319
+ "id": "c7b07f9b-ae0e-4f89-98f0-0c50d432eab6",
320
+ "metadata": {
321
+ "id": "c7b07f9b-ae0e-4f89-98f0-0c50d432eab6",
322
+ "outputId": "5c004b44-86e7-4e00-88be-39e0af5eed69"
323
+ },
324
+ "outputs": [
325
+ {
326
+ "data": {
327
+ "application/vnd.jupyter.widget-view+json": {
328
+ "model_id": "90d056e20b3e4f14ae0199a1a4ab1bb0",
329
+ "version_major": 2,
330
+ "version_minor": 0
331
+ },
332
+ "text/plain": [
333
+ "Downloading: 0%| | 0.00/829 [00:00<?, ?B/s]"
334
+ ]
335
+ },
336
+ "metadata": {},
337
+ "output_type": "display_data"
338
+ },
339
+ {
340
+ "data": {
341
+ "application/vnd.jupyter.widget-view+json": {
342
+ "model_id": "d82a88daec0e4f14add691b7b903064c",
343
+ "version_major": 2,
344
+ "version_minor": 0
345
+ },
346
+ "text/plain": [
347
+ "Downloading: 0%| | 0.00/1.04M [00:00<?, ?B/s]"
348
+ ]
349
+ },
350
+ "metadata": {},
351
+ "output_type": "display_data"
352
+ },
353
+ {
354
+ "data": {
355
+ "application/vnd.jupyter.widget-view+json": {
356
+ "model_id": "350acdb0f40e454099fa901e66de55f0",
357
+ "version_major": 2,
358
+ "version_minor": 0
359
+ },
360
+ "text/plain": [
361
+ "Downloading: 0%| | 0.00/494k [00:00<?, ?B/s]"
362
+ ]
363
+ },
364
+ "metadata": {},
365
+ "output_type": "display_data"
366
+ },
367
+ {
368
+ "data": {
369
+ "application/vnd.jupyter.widget-view+json": {
370
+ "model_id": "2e6a82a462cc411d90fa1bea4ee60790",
371
+ "version_major": 2,
372
+ "version_minor": 0
373
+ },
374
+ "text/plain": [
375
+ "Downloading: 0%| | 0.00/52.7k [00:00<?, ?B/s]"
376
+ ]
377
+ },
378
+ "metadata": {},
379
+ "output_type": "display_data"
380
+ },
381
+ {
382
+ "data": {
383
+ "application/vnd.jupyter.widget-view+json": {
384
+ "model_id": "c74bfee0198b4817832ea86e8e88d96c",
385
+ "version_major": 2,
386
+ "version_minor": 0
387
+ },
388
+ "text/plain": [
389
+ "Downloading: 0%| | 0.00/2.11k [00:00<?, ?B/s]"
390
+ ]
391
+ },
392
+ "metadata": {},
393
+ "output_type": "display_data"
394
+ },
395
+ {
396
+ "data": {
397
+ "application/vnd.jupyter.widget-view+json": {
398
+ "model_id": "04fb2d81eff646068e10475a08ae42f4",
399
+ "version_major": 2,
400
+ "version_minor": 0
401
+ },
402
+ "text/plain": [
403
+ "Downloading: 0%| | 0.00/2.06k [00:00<?, ?B/s]"
404
+ ]
405
+ },
406
+ "metadata": {},
407
+ "output_type": "display_data"
408
+ }
409
+ ],
410
+ "source": [
411
+ "from transformers import WhisperTokenizer\n",
412
+ "\n",
413
+ "tokenizer = WhisperTokenizer.from_pretrained(\"openai/whisper-small\", language=\"Hindi\", task=\"transcribe\")"
414
+ ]
415
+ },
416
+ {
417
+ "cell_type": "markdown",
418
+ "id": "d2ef23f3-f4a8-483a-a2dc-080a7496cb1b",
419
+ "metadata": {
420
+ "id": "d2ef23f3-f4a8-483a-a2dc-080a7496cb1b"
421
+ },
422
+ "source": [
423
+ "### Combine To Create A WhisperProcessor"
424
+ ]
425
+ },
426
+ {
427
+ "cell_type": "markdown",
428
+ "id": "5ff67654-5a29-4bb8-a69d-0228946c6f8d",
429
+ "metadata": {
430
+ "id": "5ff67654-5a29-4bb8-a69d-0228946c6f8d"
431
+ },
432
+ "source": [
433
+ "To simplify using the feature extractor and tokenizer, we can _wrap_ \n",
434
+ "both into a single `WhisperProcessor` class. This processor object \n",
435
+ "inherits from the `WhisperFeatureExtractor` and `WhisperProcessor`, \n",
436
+ "and can be used on the audio inputs and model predictions as required. \n",
437
+ "In doing so, we only need to keep track of two objects during training: \n",
438
+ "the `processor` and the `model`:"
439
+ ]
440
+ },
441
+ {
442
+ "cell_type": "code",
443
+ "execution_count": null,
444
+ "id": "77d9f0c5-8607-4642-a8ac-c3ab2e223ea6",
445
+ "metadata": {
446
+ "id": "77d9f0c5-8607-4642-a8ac-c3ab2e223ea6"
447
+ },
448
+ "outputs": [],
449
+ "source": [
450
+ "from transformers import WhisperProcessor\n",
451
+ "\n",
452
+ "processor = WhisperProcessor.from_pretrained(\"openai/whisper-small\", language=\"Hindi\", task=\"transcribe\")"
453
+ ]
454
+ },
455
+ {
456
+ "cell_type": "markdown",
457
+ "id": "381acd09-0b0f-4d04-9eb3-f028ac0e5f2c",
458
+ "metadata": {
459
+ "id": "381acd09-0b0f-4d04-9eb3-f028ac0e5f2c"
460
+ },
461
+ "source": [
462
+ "### Prepare Data"
463
+ ]
464
+ },
465
+ {
466
+ "cell_type": "markdown",
467
+ "id": "9649bf01-2e8a-45e5-8fca-441c13637b8f",
468
+ "metadata": {
469
+ "id": "9649bf01-2e8a-45e5-8fca-441c13637b8f"
470
+ },
471
+ "source": [
472
+ "Let's print the first example of the Common Voice dataset to see \n",
473
+ "what form the data is in:"
474
+ ]
475
+ },
476
+ {
477
+ "cell_type": "code",
478
+ "execution_count": null,
479
+ "id": "6e6b0ec5-0c94-4e2c-ae24-c791be1b2255",
480
+ "metadata": {
481
+ "id": "6e6b0ec5-0c94-4e2c-ae24-c791be1b2255"
482
+ },
483
+ "outputs": [],
484
+ "source": [
485
+ "print(common_voice[\"train\"][0])"
486
+ ]
487
+ },
488
+ {
489
+ "cell_type": "markdown",
490
+ "id": "5a679f05-063d-41b3-9b58-4fc9c6ccf4fd",
491
+ "metadata": {
492
+ "id": "5a679f05-063d-41b3-9b58-4fc9c6ccf4fd"
493
+ },
494
+ "source": [
495
+ "Since \n",
496
+ "our input audio is sampled at 48kHz, we need to _downsample_ it to \n",
497
+ "16kHz prior to passing it to the Whisper feature extractor, 16kHz being the sampling rate expected by the Whisper model. \n",
498
+ "\n",
499
+ "We'll set the audio inputs to the correct sampling rate using dataset's \n",
500
+ "[`cast_column`](https://huggingface.co/docs/datasets/package_reference/main_classes.html?highlight=cast_column#datasets.DatasetDict.cast_column)\n",
501
+ "method. This operation does not change the audio in-place, \n",
502
+ "but rather signals to `datasets` to resample audio samples _on the fly_ the \n",
503
+ "first time that they are loaded:"
504
+ ]
505
+ },
506
+ {
507
+ "cell_type": "code",
508
+ "execution_count": null,
509
+ "id": "f12e2e57-156f-417b-8cfb-69221cc198e8",
510
+ "metadata": {
511
+ "id": "f12e2e57-156f-417b-8cfb-69221cc198e8"
512
+ },
513
+ "outputs": [],
514
+ "source": [
515
+ "from datasets import Audio\n",
516
+ "\n",
517
+ "common_voice = common_voice.cast_column(\"audio\", Audio(sampling_rate=16000))"
518
+ ]
519
+ },
520
+ {
521
+ "cell_type": "markdown",
522
+ "id": "00382a3e-abec-4cdd-a54c-d1aaa3ea4707",
523
+ "metadata": {
524
+ "id": "00382a3e-abec-4cdd-a54c-d1aaa3ea4707"
525
+ },
526
+ "source": [
527
+ "Re-loading the first audio sample in the Common Voice dataset will resample \n",
528
+ "it to the desired sampling rate:"
529
+ ]
530
+ },
531
+ {
532
+ "cell_type": "code",
533
+ "execution_count": null,
534
+ "id": "87122d71-289a-466a-afcf-fa354b18946b",
535
+ "metadata": {
536
+ "id": "87122d71-289a-466a-afcf-fa354b18946b"
537
+ },
538
+ "outputs": [],
539
+ "source": [
540
+ "print(common_voice[\"train\"][0])"
541
+ ]
542
+ },
543
+ {
544
+ "cell_type": "markdown",
545
+ "id": "3df7378a-a4c0-45d7-8d07-defbd1062ab6",
546
+ "metadata": {},
547
+ "source": [
548
+ "We'll define our pre-processing strategy. We advise that you **do not** lower-case the transcriptions or remove punctuation unless mixing different datasets. This will enable you to fine-tune Whisper models that can predict punctuation and casing. Later, you will see how we can evaluate the predictions without punctuation or casing, so that the models benefit from the WER improvement obtained by normalising the transcriptions while still predicting fully formatted transcriptions."
549
+ ]
550
+ },
551
+ {
552
+ "cell_type": "code",
553
+ "execution_count": null,
554
+ "id": "d041650e-1c48-4439-87b3-5b6f4a514107",
555
+ "metadata": {},
556
+ "outputs": [],
557
+ "source": [
558
+ "from transformers.models.whisper.english_normalizer import BasicTextNormalizer\n",
559
+ "\n",
560
+ "do_lower_case = False\n",
561
+ "do_remove_punctuation = False\n",
562
+ "\n",
563
+ "normalizer = BasicTextNormalizer()"
564
+ ]
565
+ },
566
+ {
567
+ "cell_type": "markdown",
568
+ "id": "89e12c2e-2f14-479b-987b-f0c75c881095",
569
+ "metadata": {},
570
+ "source": [
571
+ "Now we can write a function to prepare our data ready for the model:\n",
572
+ "1. We load and resample the audio data by calling `batch[\"audio\"]`. As explained above, 🤗 Datasets performs any necessary resampling operations on the fly.\n",
573
+ "2. We use the feature extractor to compute the log-Mel spectrogram input features from our 1-dimensional audio array.\n",
574
+ "3. We perform any optional pre-processing (lower-case or remove punctuation).\n",
575
+ "4. We encode the transcriptions to label ids through the use of the tokenizer."
576
+ ]
577
+ },
578
+ {
579
+ "cell_type": "code",
580
+ "execution_count": null,
581
+ "id": "c085911c-a10a-41ef-8874-306e0503e9bb",
582
+ "metadata": {},
583
+ "outputs": [],
584
+ "source": [
585
+ "def prepare_dataset(batch):\n",
586
+ " # load and (possibly) resample audio data to 16kHz\n",
587
+ " audio = batch[\"audio\"]\n",
588
+ "\n",
589
+ " # compute log-Mel input features from input audio array \n",
590
+ " batch[\"input_features\"] = processor.feature_extractor(audio[\"array\"], sampling_rate=audio[\"sampling_rate\"]).input_features[0]\n",
591
+ " # compute input length of audio sample in seconds\n",
592
+ " batch[\"input_length\"] = len(audio[\"array\"]) / audio[\"sampling_rate\"]\n",
593
+ " \n",
594
+ " # optional pre-processing steps\n",
595
+ " transcription = batch[\"sentence\"]\n",
596
+ " if do_lower_case:\n",
597
+ " transcription = transcription.lower()\n",
598
+ " if do_remove_punctuation:\n",
599
+ " transcription = normalizer(transcription).strip()\n",
600
+ " \n",
601
+ " # encode target text to label ids\n",
602
+ " batch[\"labels\"] = processor.tokenizer(transcription).input_ids\n",
603
+ " return batch"
604
+ ]
605
+ },
606
+ {
607
+ "cell_type": "markdown",
608
+ "id": "8c960965-9fb6-466f-9dbd-c9d43e71d9d0",
609
+ "metadata": {
610
+ "id": "70b319fb-2439-4ef6-a70d-a47bf41c4a13"
611
+ },
612
+ "source": [
613
+ "We can apply the data preparation function to all of our training examples using dataset's `.map` method. The argument `num_proc` specifies how many CPU cores to use. Setting `num_proc` > 1 will enable multiprocessing. If the `.map` method hangs with multiprocessing, set `num_proc=1` and process the dataset sequentially."
614
+ ]
615
+ },
616
+ {
617
+ "cell_type": "code",
618
+ "execution_count": null,
619
+ "id": "7b73ab39-ffaf-4b9e-86e5-782963c6134b",
620
+ "metadata": {
621
+ "id": "7b73ab39-ffaf-4b9e-86e5-782963c6134b"
622
+ },
623
+ "outputs": [],
624
+ "source": [
625
+ "common_voice = common_voice.map(prepare_dataset, remove_columns=common_voice.column_names[\"train\"], num_proc=2)"
626
+ ]
627
+ },
628
+ {
629
+ "cell_type": "markdown",
630
+ "id": "54ce0fdb-7218-4a4d-b175-383980fec0df",
631
+ "metadata": {},
632
+ "source": [
633
+ "Finally, we filter any training data with audio samples longer than 30s. These samples would otherwise be truncated by the Whisper feature-extractor which could affect the stability of training. We define a function that returns `True` for samples that are less than 30s, and `False` for those that are longer:"
634
+ ]
635
+ },
636
+ {
637
+ "cell_type": "code",
638
+ "execution_count": null,
639
+ "id": "01cb25ef-4bb0-4325-9461-f59198acadf6",
640
+ "metadata": {},
641
+ "outputs": [],
642
+ "source": [
643
+ "max_input_length = 30.0\n",
644
+ "\n",
645
+ "def is_audio_in_length_range(length):\n",
646
+ " return length < max_input_length"
647
+ ]
648
+ },
649
+ {
650
+ "cell_type": "markdown",
651
+ "id": "30e676a8-7ca8-4850-8c5d-5b2b00d13fba",
652
+ "metadata": {},
653
+ "source": [
654
+ "We apply our filter function to all samples of our training dataset through 🤗 Datasets' `.filter` method:"
655
+ ]
656
+ },
657
+ {
658
+ "cell_type": "code",
659
+ "execution_count": null,
660
+ "id": "333f7f6e-6053-4d3b-8924-c733c79b82ac",
661
+ "metadata": {},
662
+ "outputs": [],
663
+ "source": [
664
+ "common_voice[\"train\"] = common_voice[\"train\"].filter(\n",
665
+ " is_audio_in_length_range,\n",
666
+ " input_columns=[\"input_length\"],\n",
667
+ ")"
668
+ ]
669
+ },
670
+ {
671
+ "cell_type": "markdown",
672
+ "id": "263a5a58-0239-4a25-b0df-c625fc9c5810",
673
+ "metadata": {
674
+ "id": "263a5a58-0239-4a25-b0df-c625fc9c5810"
675
+ },
676
+ "source": [
677
+ "## Training and Evaluation"
678
+ ]
679
+ },
680
+ {
681
+ "cell_type": "markdown",
682
+ "id": "a693e768-c5a6-453f-89a1-b601dcf7daf7",
683
+ "metadata": {
684
+ "id": "a693e768-c5a6-453f-89a1-b601dcf7daf7"
685
+ },
686
+ "source": [
687
+ "Now that we've prepared our data, we're ready to dive into the training pipeline. \n",
688
+ "The [🤗 Trainer](https://huggingface.co/transformers/master/main_classes/trainer.html?highlight=trainer)\n",
689
+ "will do much of the heavy lifting for us. All we have to do is:\n",
690
+ "\n",
691
+ "- Define a data collator: the data collator takes our pre-processed data and prepares PyTorch tensors ready for the model.\n",
692
+ "\n",
693
+ "- Evaluation metrics: during evaluation, we want to evaluate the model using the [word error rate (WER)](https://huggingface.co/metrics/wer) metric. We need to define a `compute_metrics` function that handles this computation.\n",
694
+ "\n",
695
+ "- Load a pre-trained checkpoint: we need to load a pre-trained checkpoint and configure it correctly for training.\n",
696
+ "\n",
697
+ "- Define the training configuration: this will be used by the 🤗 Trainer to define the training schedule.\n",
698
+ "\n",
699
+ "Once we've fine-tuned the model, we will evaluate it on the test data to verify that we have correctly trained it \n",
700
+ "to transcribe speech in Hindi."
701
+ ]
702
+ },
703
+ {
704
+ "cell_type": "markdown",
705
+ "id": "8d230e6d-624c-400a-bbf5-fa660881df25",
706
+ "metadata": {
707
+ "id": "8d230e6d-624c-400a-bbf5-fa660881df25"
708
+ },
709
+ "source": [
710
+ "### Define a Data Collator"
711
+ ]
712
+ },
713
+ {
714
+ "cell_type": "markdown",
715
+ "id": "04def221-0637-4a69-b242-d3f0c1d0ee78",
716
+ "metadata": {
717
+ "id": "04def221-0637-4a69-b242-d3f0c1d0ee78"
718
+ },
719
+ "source": [
720
+ "The data collator for a sequence-to-sequence speech model is unique in the sense that it \n",
721
+ "treats the `input_features` and `labels` independently: the `input_features` must be \n",
722
+ "handled by the feature extractor and the `labels` by the tokenizer.\n",
723
+ "\n",
724
+ "The `input_features` are already padded to 30s and converted to a log-Mel spectrogram \n",
725
+ "of fixed dimension by action of the feature extractor, so all we have to do is convert the `input_features`\n",
726
+ "to batched PyTorch tensors. We do this using the feature extractor's `.pad` method with `return_tensors=pt`.\n",
727
+ "\n",
728
+ "The `labels` on the other hand are un-padded. We first pad the sequences\n",
729
+ "to the maximum length in the batch using the tokenizer's `.pad` method. The padding tokens \n",
730
+ "are then replaced by `-100` so that these tokens are **not** taken into account when \n",
731
+ "computing the loss. We then cut the BOS token from the start of the label sequence as we \n",
732
+ "append it later during training.\n",
733
+ "\n",
734
+ "We can leverage the `WhisperProcessor` we defined earlier to perform both the \n",
735
+ "feature extractor and the tokenizer operations:"
736
+ ]
737
+ },
738
+ {
739
+ "cell_type": "code",
740
+ "execution_count": null,
741
+ "id": "8326221e-ec13-4731-bb4e-51e5fc1486c5",
742
+ "metadata": {
743
+ "id": "8326221e-ec13-4731-bb4e-51e5fc1486c5"
744
+ },
745
+ "outputs": [],
746
+ "source": [
747
+ "import torch\n",
748
+ "\n",
749
+ "from dataclasses import dataclass\n",
750
+ "from typing import Any, Dict, List, Union\n",
751
+ "\n",
752
+ "@dataclass\n",
753
+ "class DataCollatorSpeechSeq2SeqWithPadding:\n",
754
+ " processor: Any\n",
755
+ "\n",
756
+ " def __call__(self, features: List[Dict[str, Union[List[int], torch.Tensor]]]) -> Dict[str, torch.Tensor]:\n",
757
+ " # split inputs and labels since they have to be of different lengths and need different padding methods\n",
758
+ " # first treat the audio inputs by simply returning torch tensors\n",
759
+ " input_features = [{\"input_features\": feature[\"input_features\"]} for feature in features]\n",
760
+ " batch = self.processor.feature_extractor.pad(input_features, return_tensors=\"pt\")\n",
761
+ "\n",
762
+ " # get the tokenized label sequences\n",
763
+ " label_features = [{\"input_ids\": feature[\"labels\"]} for feature in features]\n",
764
+ " # pad the labels to max length\n",
765
+ " labels_batch = self.processor.tokenizer.pad(label_features, return_tensors=\"pt\")\n",
766
+ "\n",
767
+ " # replace padding with -100 to ignore loss correctly\n",
768
+ " labels = labels_batch[\"input_ids\"].masked_fill(labels_batch.attention_mask.ne(1), -100)\n",
769
+ "\n",
770
+ " # if bos token is appended in previous tokenization step,\n",
771
+ " # cut bos token here as it's append later anyways\n",
772
+ " if (labels[:, 0] == self.processor.tokenizer.bos_token_id).all().cpu().item():\n",
773
+ " labels = labels[:, 1:]\n",
774
+ "\n",
775
+ " batch[\"labels\"] = labels\n",
776
+ "\n",
777
+ " return batch"
778
+ ]
779
+ },
780
+ {
781
+ "cell_type": "markdown",
782
+ "id": "3cae7dbf-8a50-456e-a3a8-7fd005390f86",
783
+ "metadata": {
784
+ "id": "3cae7dbf-8a50-456e-a3a8-7fd005390f86"
785
+ },
786
+ "source": [
787
+ "Let's initialise the data collator we've just defined:"
788
+ ]
789
+ },
790
+ {
791
+ "cell_type": "code",
792
+ "execution_count": null,
793
+ "id": "fc834702-c0d3-4a96-b101-7b87be32bf42",
794
+ "metadata": {
795
+ "id": "fc834702-c0d3-4a96-b101-7b87be32bf42"
796
+ },
797
+ "outputs": [],
798
+ "source": [
799
+ "data_collator = DataCollatorSpeechSeq2SeqWithPadding(processor=processor)"
800
+ ]
801
+ },
802
+ {
803
+ "cell_type": "markdown",
804
+ "id": "d62bb2ab-750a-45e7-82e9-61d6f4805698",
805
+ "metadata": {
806
+ "id": "d62bb2ab-750a-45e7-82e9-61d6f4805698"
807
+ },
808
+ "source": [
809
+ "### Evaluation Metrics"
810
+ ]
811
+ },
812
+ {
813
+ "cell_type": "markdown",
814
+ "id": "66fee1a7-a44c-461e-b047-c3917221572e",
815
+ "metadata": {
816
+ "id": "66fee1a7-a44c-461e-b047-c3917221572e"
817
+ },
818
+ "source": [
819
+ "We'll use the word error rate (WER) metric, the 'de-facto' metric for assessing \n",
820
+ "ASR systems. For more information, refer to the WER [docs](https://huggingface.co/metrics/wer). We'll load the WER metric from 🤗 Evaluate:"
821
+ ]
822
+ },
823
+ {
824
+ "cell_type": "code",
825
+ "execution_count": null,
826
+ "id": "b22b4011-f31f-4b57-b684-c52332f92890",
827
+ "metadata": {
828
+ "id": "b22b4011-f31f-4b57-b684-c52332f92890"
829
+ },
830
+ "outputs": [],
831
+ "source": [
832
+ "import evaluate\n",
833
+ "\n",
834
+ "metric = evaluate.load(\"wer\")"
835
+ ]
836
+ },
837
+ {
838
+ "cell_type": "markdown",
839
+ "id": "4f32cab6-31f0-4cb9-af4c-40ba0f5fc508",
840
+ "metadata": {
841
+ "id": "4f32cab6-31f0-4cb9-af4c-40ba0f5fc508"
842
+ },
843
+ "source": [
844
+ "We then simply have to define a function that takes our model \n",
845
+ "predictions and returns the WER metric. This function, called\n",
846
+ "`compute_metrics`, first replaces `-100` with the `pad_token_id`\n",
847
+ "in the `label_ids` (undoing the step we applied in the \n",
848
+ "data collator to ignore padded tokens correctly in the loss).\n",
849
+ "It then decodes the predicted and label ids to strings. Finally,\n",
850
+ "it computes the WER between the predictions and reference labels. \n",
851
+ "Here, we have the option of evaluating with the 'normalised' transcriptions \n",
852
+ "and predictions. We recommend you set this to `True` to benefit from the WER \n",
853
+ "improvement obtained by normalising the transcriptions."
854
+ ]
855
+ },
856
+ {
857
+ "cell_type": "code",
858
+ "execution_count": null,
859
+ "id": "23959a70-22d0-4ffe-9fa1-72b61e75bb52",
860
+ "metadata": {
861
+ "id": "23959a70-22d0-4ffe-9fa1-72b61e75bb52"
862
+ },
863
+ "outputs": [],
864
+ "source": [
865
+ "# evaluate with the 'normalised' WER\n",
866
+ "do_normalize_eval = True\n",
867
+ "\n",
868
+ "def compute_metrics(pred):\n",
869
+ " pred_ids = pred.predictions\n",
870
+ " label_ids = pred.label_ids\n",
871
+ "\n",
872
+ " # replace -100 with the pad_token_id\n",
873
+ " label_ids[label_ids == -100] = processor.tokenizer.pad_token_id\n",
874
+ "\n",
875
+ " # we do not want to group tokens when computing the metrics\n",
876
+ " pred_str = processor.tokenizer.batch_decode(pred_ids, skip_special_tokens=True)\n",
877
+ " label_str = processor.tokenizer.batch_decode(label_ids, skip_special_tokens=True)\n",
878
+ "\n",
879
+ " if do_normalize_eval:\n",
880
+ " pred_str = [normalizer(pred) for pred in pred_str]\n",
881
+ " label_str = [normalizer(label) for label in label_str]\n",
882
+ "\n",
883
+ " wer = 100 * metric.compute(predictions=pred_str, references=label_str)\n",
884
+ "\n",
885
+ " return {\"wer\": wer}"
886
+ ]
887
+ },
888
+ {
889
+ "cell_type": "markdown",
890
+ "id": "daf2a825-6d9f-4a23-b145-c37c0039075b",
891
+ "metadata": {
892
+ "id": "daf2a825-6d9f-4a23-b145-c37c0039075b"
893
+ },
894
+ "source": [
895
+ "### Load a Pre-Trained Checkpoint"
896
+ ]
897
+ },
898
+ {
899
+ "cell_type": "markdown",
900
+ "id": "437a97fa-4864-476b-8abc-f28b8166cfa5",
901
+ "metadata": {
902
+ "id": "437a97fa-4864-476b-8abc-f28b8166cfa5"
903
+ },
904
+ "source": [
905
+ "Now let's load the pre-trained Whisper `small` checkpoint. Again, this \n",
906
+ "is trivial through use of 🤗 Transformers!"
907
+ ]
908
+ },
909
+ {
910
+ "cell_type": "code",
911
+ "execution_count": null,
912
+ "id": "5a10cc4b-07ec-4ebd-ac1d-7c601023594f",
913
+ "metadata": {
914
+ "id": "5a10cc4b-07ec-4ebd-ac1d-7c601023594f"
915
+ },
916
+ "outputs": [],
917
+ "source": [
918
+ "from transformers import WhisperForConditionalGeneration\n",
919
+ "\n",
920
+ "model = WhisperForConditionalGeneration.from_pretrained(\"openai/whisper-small\")"
921
+ ]
922
+ },
923
+ {
924
+ "cell_type": "markdown",
925
+ "id": "a15ead5f-2277-4a39-937b-585c2497b2df",
926
+ "metadata": {
927
+ "id": "a15ead5f-2277-4a39-937b-585c2497b2df"
928
+ },
929
+ "source": [
930
+ "Override generation arguments - no tokens are forced as decoder outputs (see [`forced_decoder_ids`](https://huggingface.co/docs/transformers/main_classes/text_generation#transformers.generation_utils.GenerationMixin.generate.forced_decoder_ids)), no tokens are suppressed during generation (see [`suppress_tokens`](https://huggingface.co/docs/transformers/main_classes/text_generation#transformers.generation_utils.GenerationMixin.generate.suppress_tokens)). Set `use_cache` to False since we're using gradient checkpointing, and the two are incompatible:"
931
+ ]
932
+ },
933
+ {
934
+ "cell_type": "code",
935
+ "execution_count": null,
936
+ "id": "62038ba3-88ed-4fce-84db-338f50dcd04f",
937
+ "metadata": {
938
+ "id": "62038ba3-88ed-4fce-84db-338f50dcd04f"
939
+ },
940
+ "outputs": [],
941
+ "source": [
942
+ "model.config.forced_decoder_ids = None\n",
943
+ "model.config.suppress_tokens = []\n",
944
+ "model.config.use_cache = False"
945
+ ]
946
+ },
947
+ {
948
+ "cell_type": "markdown",
949
+ "id": "2178dea4-80ca-47b6-b6ea-ba1915c90c06",
950
+ "metadata": {
951
+ "id": "2178dea4-80ca-47b6-b6ea-ba1915c90c06"
952
+ },
953
+ "source": [
954
+ "### Define the Training Configuration"
955
+ ]
956
+ },
957
+ {
958
+ "cell_type": "markdown",
959
+ "id": "c21af1e9-0188-4134-ac82-defc7bdcc436",
960
+ "metadata": {
961
+ "id": "c21af1e9-0188-4134-ac82-defc7bdcc436"
962
+ },
963
+ "source": [
964
+ "In the final step, we define all the parameters related to training. For more detail on the training arguments, refer to the Seq2SeqTrainingArguments [docs](https://huggingface.co/docs/transformers/main_classes/trainer#transformers.Seq2SeqTrainingArguments)."
965
+ ]
966
+ },
967
+ {
968
+ "cell_type": "code",
969
+ "execution_count": null,
970
+ "id": "0ae3e9af-97b7-4aa0-ae85-20b23b5bcb3a",
971
+ "metadata": {
972
+ "id": "0ae3e9af-97b7-4aa0-ae85-20b23b5bcb3a"
973
+ },
974
+ "outputs": [],
975
+ "source": [
976
+ "from transformers import Seq2SeqTrainingArguments\n",
977
+ "\n",
978
+ "training_args = Seq2SeqTrainingArguments(\n",
979
+ " output_dir=\"./\",\n",
980
+ " per_device_train_batch_size=64,\n",
981
+ " gradient_accumulation_steps=1, # increase by 2x for every 2x decrease in batch size\n",
982
+ " learning_rate=1e-5,\n",
983
+ " warmup_steps=500,\n",
984
+ " max_steps=5000,\n",
985
+ " gradient_checkpointing=True,\n",
986
+ " fp16=True,\n",
987
+ " evaluation_strategy=\"steps\",\n",
988
+ " per_device_eval_batch_size=8,\n",
989
+ " predict_with_generate=True,\n",
990
+ " generation_max_length=225,\n",
991
+ " save_steps=1000,\n",
992
+ " eval_steps=1000,\n",
993
+ " logging_steps=25,\n",
994
+ " report_to=[\"tensorboard\"],\n",
995
+ " load_best_model_at_end=True,\n",
996
+ " metric_for_best_model=\"wer\",\n",
997
+ " greater_is_better=False,\n",
998
+ " push_to_hub=True,\n",
999
+ ")"
1000
+ ]
1001
+ },
1002
+ {
1003
+ "cell_type": "markdown",
1004
+ "id": "b3a944d8-3112-4552-82a0-be25988b3857",
1005
+ "metadata": {
1006
+ "id": "b3a944d8-3112-4552-82a0-be25988b3857"
1007
+ },
1008
+ "source": [
1009
+ "**Note**: if one does not want to upload the model checkpoints to the Hub, \n",
1010
+ "set `push_to_hub=False`."
1011
+ ]
1012
+ },
1013
+ {
1014
+ "cell_type": "markdown",
1015
+ "id": "bac29114-d226-4f54-97cf-8718c9f94e1e",
1016
+ "metadata": {
1017
+ "id": "bac29114-d226-4f54-97cf-8718c9f94e1e"
1018
+ },
1019
+ "source": [
1020
+ "We can forward the training arguments to the 🤗 Trainer along with our model,\n",
1021
+ "dataset, data collator and `compute_metrics` function:"
1022
+ ]
1023
+ },
1024
+ {
1025
+ "cell_type": "code",
1026
+ "execution_count": null,
1027
+ "id": "d546d7fe-0543-479a-b708-2ebabec19493",
1028
+ "metadata": {
1029
+ "id": "d546d7fe-0543-479a-b708-2ebabec19493"
1030
+ },
1031
+ "outputs": [],
1032
+ "source": [
1033
+ "from transformers import Seq2SeqTrainer\n",
1034
+ "\n",
1035
+ "trainer = Seq2SeqTrainer(\n",
1036
+ " args=training_args,\n",
1037
+ " model=model,\n",
1038
+ " train_dataset=common_voice[\"train\"],\n",
1039
+ " eval_dataset=common_voice[\"test\"],\n",
1040
+ " data_collator=data_collator,\n",
1041
+ " compute_metrics=compute_metrics,\n",
1042
+ " tokenizer=processor.feature_extractor,\n",
1043
+ ")"
1044
+ ]
1045
+ },
1046
+ {
1047
+ "cell_type": "markdown",
1048
+ "id": "uOrRhDGtN5S4",
1049
+ "metadata": {
1050
+ "id": "uOrRhDGtN5S4"
1051
+ },
1052
+ "source": [
1053
+ "We'll save the processor object once before starting training. Since the processor is not trainable, it won't change over the course of training:"
1054
+ ]
1055
+ },
1056
+ {
1057
+ "cell_type": "code",
1058
+ "execution_count": null,
1059
+ "id": "-2zQwMfEOBJq",
1060
+ "metadata": {
1061
+ "id": "-2zQwMfEOBJq"
1062
+ },
1063
+ "outputs": [],
1064
+ "source": [
1065
+ "processor.save_pretrained(training_args.output_dir)"
1066
+ ]
1067
+ },
1068
+ {
1069
+ "cell_type": "markdown",
1070
+ "id": "7f404cf9-4345-468c-8196-4bd101d9bd51",
1071
+ "metadata": {
1072
+ "id": "7f404cf9-4345-468c-8196-4bd101d9bd51"
1073
+ },
1074
+ "source": [
1075
+ "### Training"
1076
+ ]
1077
+ },
1078
+ {
1079
+ "cell_type": "markdown",
1080
+ "id": "5e8b8d56-5a70-4f68-bd2e-f0752d0bd112",
1081
+ "metadata": {
1082
+ "id": "5e8b8d56-5a70-4f68-bd2e-f0752d0bd112"
1083
+ },
1084
+ "source": [
1085
+ "Training will take approximately 5-10 hours depending on your GPU. The peak GPU memory for the given training configuration is approximately 36GB. \n",
1086
+ "Depending on your GPU, it is possible that you will encounter a CUDA `\"out-of-memory\"` error when you launch training. \n",
1087
+ "In this case, you can reduce the `per_device_train_batch_size` incrementally by factors of 2 \n",
1088
+ "and employ [`gradient_accumulation_steps`](https://huggingface.co/docs/transformers/main_classes/trainer#transformers.Seq2SeqTrainingArguments.gradient_accumulation_steps)\n",
1089
+ "to compensate.\n",
1090
+ "\n",
1091
+ "To launch training, simply execute:"
1092
+ ]
1093
+ },
1094
+ {
1095
+ "cell_type": "code",
1096
+ "execution_count": null,
1097
+ "id": "ee8b7b8e-1c9a-4d77-9137-1778a629e6de",
1098
+ "metadata": {
1099
+ "id": "ee8b7b8e-1c9a-4d77-9137-1778a629e6de"
1100
+ },
1101
+ "outputs": [],
1102
+ "source": [
1103
+ "trainer.train()"
1104
+ ]
1105
+ },
1106
+ {
1107
+ "cell_type": "markdown",
1108
+ "id": "810ced54-7187-4a06-b2fe-ba6dcca94dc3",
1109
+ "metadata": {
1110
+ "id": "810ced54-7187-4a06-b2fe-ba6dcca94dc3"
1111
+ },
1112
+ "source": [
1113
+ "We can label our checkpoint with the `whisper-event` tag on push by setting the appropriate key-word arguments (kwargs):"
1114
+ ]
1115
+ },
1116
+ {
1117
+ "cell_type": "code",
1118
+ "execution_count": null,
1119
+ "id": "c704f91e-241b-48c9-b8e0-f0da396a9663",
1120
+ "metadata": {
1121
+ "id": "c704f91e-241b-48c9-b8e0-f0da396a9663"
1122
+ },
1123
+ "outputs": [],
1124
+ "source": [
1125
+ "kwargs = {\n",
1126
+ " \"dataset_tags\": \"mozilla-foundation/common_voice_11_0\",\n",
1127
+ " \"dataset\": \"Common Voice 11.0\", # a 'pretty' name for the training dataset\n",
1128
+ " \"language\": \"hi\",\n",
1129
+ " \"model_name\": \"Whisper Small Hi - Sanchit Gandhi\", # a 'pretty' name for your model\n",
1130
+ " \"finetuned_from\": \"openai/whisper-small\",\n",
1131
+ " \"tasks\": \"automatic-speech-recognition\",\n",
1132
+ " \"tags\": \"whisper-event\",\n",
1133
+ "}"
1134
+ ]
1135
+ },
1136
+ {
1137
+ "cell_type": "markdown",
1138
+ "id": "090d676a-f944-4297-a938-a40eda0b2b68",
1139
+ "metadata": {
1140
+ "id": "090d676a-f944-4297-a938-a40eda0b2b68"
1141
+ },
1142
+ "source": [
1143
+ "The training results can now be uploaded to the Hub. To do so, execute the `push_to_hub` command and save the preprocessor object we created:"
1144
+ ]
1145
+ },
1146
+ {
1147
+ "cell_type": "code",
1148
+ "execution_count": null,
1149
+ "id": "d7030622-caf7-4039-939b-6195cdaa2585",
1150
+ "metadata": {
1151
+ "id": "d7030622-caf7-4039-939b-6195cdaa2585"
1152
+ },
1153
+ "outputs": [],
1154
+ "source": [
1155
+ "trainer.push_to_hub(**kwargs)"
1156
+ ]
1157
+ },
1158
+ {
1159
+ "cell_type": "markdown",
1160
+ "id": "ca743fbd-602c-48d4-ba8d-a2fe60af64ba",
1161
+ "metadata": {
1162
+ "id": "ca743fbd-602c-48d4-ba8d-a2fe60af64ba"
1163
+ },
1164
+ "source": [
1165
+ "## Closing Remarks"
1166
+ ]
1167
+ },
1168
+ {
1169
+ "cell_type": "markdown",
1170
+ "id": "7f737783-2870-4e35-aa11-86a42d7d997a",
1171
+ "metadata": {
1172
+ "id": "7f737783-2870-4e35-aa11-86a42d7d997a"
1173
+ },
1174
+ "source": [
1175
+ "In this blog, we covered a step-by-step guide on fine-tuning Whisper for multilingual ASR \n",
1176
+ "using 🤗 Datasets, Transformers and the Hugging Face Hub. For more details on the Whisper model, the Common Voice dataset and the theory behind fine-tuning, refere to the accompanying [blog post](https://huggingface.co/blog/fine-tune-whisper). If you're interested in fine-tuning other \n",
1177
+ "Transformers models, both for English and multilingual ASR, be sure to check out the \n",
1178
+ "examples scripts at [examples/pytorch/speech-recognition](https://github.com/huggingface/transformers/tree/main/examples/pytorch/speech-recognition)."
1179
+ ]
1180
+ }
1181
+ ],
1182
+ "metadata": {
1183
+ "colab": {
1184
+ "include_colab_link": true,
1185
+ "provenance": []
1186
+ },
1187
+ "kernelspec": {
1188
+ "display_name": "Python 3 (ipykernel)",
1189
+ "language": "python",
1190
+ "name": "python3"
1191
+ },
1192
+ "language_info": {
1193
+ "codemirror_mode": {
1194
+ "name": "ipython",
1195
+ "version": 3
1196
+ },
1197
+ "file_extension": ".py",
1198
+ "mimetype": "text/x-python",
1199
+ "name": "python",
1200
+ "nbconvert_exporter": "python",
1201
+ "pygments_lexer": "ipython3",
1202
+ "version": "3.8.9"
1203
+ }
1204
+ },
1205
+ "nbformat": 4,
1206
+ "nbformat_minor": 5
1207
+ }
merges.txt ADDED
The diff for this file is too large to render. See raw diff
 
mgb2_speech.py ADDED
@@ -0,0 +1,169 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import datasets
2
+ import os
3
+
4
+
5
+ _DESCRIPTION = "MGB2 speech recognition dataset AR"
6
+ _HOMEPAGE = "https://arabicspeech.org/mgb2/"
7
+ _LICENSE = "MGB-2 License agreement"
8
+ _CITATION = """@misc{https://doi.org/10.48550/arxiv.1609.05625,
9
+ doi = {10.48550/ARXIV.1609.05625},
10
+
11
+ url = {https://arxiv.org/abs/1609.05625},
12
+
13
+ author = {Ali, Ahmed and Bell, Peter and Glass, James and Messaoui, Yacine and Mubarak, Hamdy and Renals, Steve and Zhang, Yifan},
14
+
15
+ keywords = {Computation and Language (cs.CL), FOS: Computer and information sciences, FOS: Computer and information sciences},
16
+
17
+ title = {The MGB-2 Challenge: Arabic Multi-Dialect Broadcast Media Recognition},
18
+
19
+ publisher = {arXiv},
20
+
21
+ year = {2016},
22
+
23
+ copyright = {arXiv.org perpetual, non-exclusive license}
24
+ }
25
+ """
26
+ _DATA_ARCHIVE_ROOT = "archives/"
27
+ _DATA_URL = {
28
+ "test": _DATA_ARCHIVE_ROOT + "mgb2_wav.test.tar.gz",
29
+ "dev": _DATA_ARCHIVE_ROOT + "mgb2_wav.dev.tar.gz",
30
+ "train": [_DATA_ARCHIVE_ROOT + f"mgb2_wav_{x}.train.tar.gz" for x in range(48)], # we have 48 archives
31
+ }
32
+ _TEXT_URL = {
33
+ "test": _DATA_ARCHIVE_ROOT + "mgb2_txt.test.tar.gz",
34
+ "dev": _DATA_ARCHIVE_ROOT + "mgb2_txt.dev.tar.gz",
35
+ "train": _DATA_ARCHIVE_ROOT + "mgb2_txt.train.tar.gz",
36
+ }
37
+
38
+ class MGDB2Dataset(datasets.GeneratorBasedBuilder):
39
+ def _info(self):
40
+ return datasets.DatasetInfo(
41
+ description=_DESCRIPTION,
42
+ features=datasets.Features(
43
+ {
44
+ "path": datasets.Value("string"),
45
+ "audio": datasets.Audio(sampling_rate=16_000),
46
+ "text": datasets.Value("string"),
47
+ }
48
+ ),
49
+ supervised_keys=None,
50
+ homepage=_HOMEPAGE,
51
+ license=_LICENSE,
52
+ citation=_CITATION,
53
+ )
54
+
55
+ def _split_generators(self, dl_manager):
56
+ wav_archive = dl_manager.download(_DATA_URL)
57
+ txt_archive = dl_manager.download(_TEXT_URL)
58
+ test_dir = "dataset/test"
59
+ dev_dir = "dataset/dev"
60
+ train_dir = "dataset/train"
61
+
62
+ if dl_manager.is_streaming:
63
+
64
+ return [
65
+ datasets.SplitGenerator(
66
+ name=datasets.Split.TEST,
67
+ gen_kwargs={
68
+ "path_to_txt": test_dir + "/txt",
69
+ "path_to_wav": test_dir + "/wav",
70
+ "wav_files": [dl_manager.iter_archive(wav_archive['test'])],
71
+ "txt_files": dl_manager.iter_archive(txt_archive['test']),
72
+ },
73
+ ),
74
+ datasets.SplitGenerator(
75
+ name=datasets.Split.VALIDATION,
76
+ gen_kwargs={
77
+ "path_to_txt": dev_dir + "/txt",
78
+ "path_to_wav": dev_dir + "/wav",
79
+ "wav_files": [dl_manager.iter_archive(wav_archive['dev'])],
80
+ "txt_files": dl_manager.iter_archive(txt_archive['dev']),
81
+ },
82
+ ),
83
+ datasets.SplitGenerator(
84
+ name=datasets.Split.TRAIN,
85
+ gen_kwargs={
86
+ "path_to_txt": train_dir + "/txt",
87
+ "path_to_wav": train_dir + "/wav",
88
+ "wav_files": [dl_manager.iter_archive(a) for a in wav_archive['train']],
89
+ "txt_files": dl_manager.iter_archive(txt_archive['train']),
90
+ },
91
+ ),
92
+ ]
93
+ else:
94
+ return [
95
+ datasets.SplitGenerator(
96
+ name=datasets.Split.TEST,
97
+ gen_kwargs={
98
+ "path_to_txt": test_dir + "/txt",
99
+ "path_to_wav": test_dir + "/wav",
100
+ "wav_files": [dl_manager.extract(wav_archive['test'])],
101
+ "txt_files": dl_manager.extract(txt_archive['test']),
102
+ },
103
+ ),
104
+ datasets.SplitGenerator(
105
+ name=datasets.Split.VALIDATION,
106
+ gen_kwargs={
107
+ "path_to_txt": dev_dir + "/txt",
108
+ "path_to_wav": dev_dir + "/wav",
109
+ "wav_files": [dl_manager.extract(wav_archive['dev'])],
110
+ "txt_files": dl_manager.extract(txt_archive['dev']),
111
+ },
112
+ ),
113
+ datasets.SplitGenerator(
114
+ name=datasets.Split.TRAIN,
115
+ gen_kwargs={
116
+ "path_to_txt": train_dir + "/txt",
117
+ "path_to_wav": train_dir + "/wav",
118
+ "wav_files": [dl_manager.extract(a) for a in wav_archive['train']],
119
+ "txt_files": dl_manager.extract(txt_archive['train']),
120
+ },
121
+ ),
122
+ ]
123
+
124
+
125
+
126
+ def _generate_examples(self, path_to_txt, path_to_wav, wav_files, txt_files):
127
+ """
128
+ This assumes that the text directory alphabetically precedes the wav dir
129
+ The file names for wav and text seem to match and are unique
130
+ We can use them for the dictionary matching them
131
+ """
132
+ examples = {}
133
+ id_ = 0
134
+ # need to prepare the transcript - wave map
135
+ for item in txt_files:
136
+ if type(item) is tuple:
137
+ # iter_archive will return path and file
138
+ path, f = item
139
+ txt = f.read().decode(encoding="utf-8").strip()
140
+ else:
141
+ # extract will return path only
142
+ path = item
143
+ with open(path, encoding="utf-8") as f:
144
+ txt = f.read().strip()
145
+
146
+ if path.find(path_to_txt) > -1:
147
+ # construct the wav path
148
+ # which is used as an identifier
149
+ wav_path = os.path.split(path)[1].replace("_utf8", "").replace(".txt", ".wav").strip()
150
+
151
+ examples[wav_path] = {
152
+ "text": txt,
153
+ "path": wav_path,
154
+ }
155
+
156
+ for wf in wav_files:
157
+ for item in wf:
158
+ if type(item) is tuple:
159
+ path, f = item
160
+ wav_data = f.read()
161
+ else:
162
+ path = item
163
+ with open(path, "rb") as f:
164
+ wav_data = f.read()
165
+ if path.find(path_to_wav) > -1:
166
+ wav_path = os.path.split(path)[1].strip()
167
+ audio = {"path": path, "bytes": wav_data}
168
+ yield id_, {**examples[wav_path], "audio": audio}
169
+ id_ += 1
normalizer.json ADDED
@@ -0,0 +1,1742 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "accessorise": "accessorize",
3
+ "accessorised": "accessorized",
4
+ "accessorises": "accessorizes",
5
+ "accessorising": "accessorizing",
6
+ "acclimatisation": "acclimatization",
7
+ "acclimatise": "acclimatize",
8
+ "acclimatised": "acclimatized",
9
+ "acclimatises": "acclimatizes",
10
+ "acclimatising": "acclimatizing",
11
+ "accoutrements": "accouterments",
12
+ "aeon": "eon",
13
+ "aeons": "eons",
14
+ "aerogramme": "aerogram",
15
+ "aerogrammes": "aerograms",
16
+ "aeroplane": "airplane",
17
+ "aeroplanes": "airplanes",
18
+ "aesthete": "esthete",
19
+ "aesthetes": "esthetes",
20
+ "aesthetic": "esthetic",
21
+ "aesthetically": "esthetically",
22
+ "aesthetics": "esthetics",
23
+ "aetiology": "etiology",
24
+ "ageing": "aging",
25
+ "aggrandisement": "aggrandizement",
26
+ "agonise": "agonize",
27
+ "agonised": "agonized",
28
+ "agonises": "agonizes",
29
+ "agonising": "agonizing",
30
+ "agonisingly": "agonizingly",
31
+ "almanack": "almanac",
32
+ "almanacks": "almanacs",
33
+ "aluminium": "aluminum",
34
+ "amortisable": "amortizable",
35
+ "amortisation": "amortization",
36
+ "amortisations": "amortizations",
37
+ "amortise": "amortize",
38
+ "amortised": "amortized",
39
+ "amortises": "amortizes",
40
+ "amortising": "amortizing",
41
+ "amphitheatre": "amphitheater",
42
+ "amphitheatres": "amphitheaters",
43
+ "anaemia": "anemia",
44
+ "anaemic": "anemic",
45
+ "anaesthesia": "anesthesia",
46
+ "anaesthetic": "anesthetic",
47
+ "anaesthetics": "anesthetics",
48
+ "anaesthetise": "anesthetize",
49
+ "anaesthetised": "anesthetized",
50
+ "anaesthetises": "anesthetizes",
51
+ "anaesthetising": "anesthetizing",
52
+ "anaesthetist": "anesthetist",
53
+ "anaesthetists": "anesthetists",
54
+ "anaesthetize": "anesthetize",
55
+ "anaesthetized": "anesthetized",
56
+ "anaesthetizes": "anesthetizes",
57
+ "anaesthetizing": "anesthetizing",
58
+ "analogue": "analog",
59
+ "analogues": "analogs",
60
+ "analyse": "analyze",
61
+ "analysed": "analyzed",
62
+ "analyses": "analyzes",
63
+ "analysing": "analyzing",
64
+ "anglicise": "anglicize",
65
+ "anglicised": "anglicized",
66
+ "anglicises": "anglicizes",
67
+ "anglicising": "anglicizing",
68
+ "annualised": "annualized",
69
+ "antagonise": "antagonize",
70
+ "antagonised": "antagonized",
71
+ "antagonises": "antagonizes",
72
+ "antagonising": "antagonizing",
73
+ "apologise": "apologize",
74
+ "apologised": "apologized",
75
+ "apologises": "apologizes",
76
+ "apologising": "apologizing",
77
+ "appal": "appall",
78
+ "appals": "appalls",
79
+ "appetiser": "appetizer",
80
+ "appetisers": "appetizers",
81
+ "appetising": "appetizing",
82
+ "appetisingly": "appetizingly",
83
+ "arbour": "arbor",
84
+ "arbours": "arbors",
85
+ "archaeologically": "archeologically",
86
+ "archaeologist": "archeologist",
87
+ "archaeologists": "archeologists",
88
+ "archaeology": "archeology</span>",
89
+ "archeological": "archaeological",
90
+ "ardour": "ardor",
91
+ "armour": "armor",
92
+ "armoured": "armored",
93
+ "armourer": "armorer",
94
+ "armourers": "armorers",
95
+ "armouries": "armories",
96
+ "armoury": "armory",
97
+ "artefact": "artifact",
98
+ "artefacts": "artifacts",
99
+ "authorise": "authorize",
100
+ "authorised": "authorized",
101
+ "authorises": "authorizes",
102
+ "authorising": "authorizing",
103
+ "axe": "ax",
104
+ "backpedalled": "backpedaled",
105
+ "backpedalling": "backpedaling",
106
+ "bannister": "banister",
107
+ "bannisters": "banisters",
108
+ "baptise": "baptize",
109
+ "baptised": "baptized",
110
+ "baptises": "baptizes",
111
+ "baptising": "baptizing",
112
+ "bastardise": "bastardize",
113
+ "bastardised": "bastardized",
114
+ "bastardises": "bastardizes",
115
+ "bastardising": "bastardizing",
116
+ "battleax": "battleaxe",
117
+ "baulk": "balk",
118
+ "baulked": "balked",
119
+ "baulking": "balking",
120
+ "baulks": "balks",
121
+ "bedevilled": "bedeviled",
122
+ "bedevilling": "bedeviling",
123
+ "behaviour": "behavior",
124
+ "behavioural": "behavioral",
125
+ "behaviourism": "behaviorism",
126
+ "behaviourist": "behaviorist",
127
+ "behaviourists": "behaviorists",
128
+ "behaviours": "behaviors",
129
+ "behove": "behoove",
130
+ "behoved": "behooved",
131
+ "behoves": "behooves",
132
+ "bejewelled": "bejeweled",
133
+ "belabour": "belabor",
134
+ "belaboured": "belabored",
135
+ "belabouring": "belaboring",
136
+ "belabours": "belabors",
137
+ "bevelled": "beveled",
138
+ "bevvies": "bevies",
139
+ "bevvy": "bevy",
140
+ "biassed": "biased",
141
+ "biassing": "biasing",
142
+ "bingeing": "binging",
143
+ "bougainvillaea": "bougainvillea",
144
+ "bougainvillaeas": "bougainvilleas",
145
+ "bowdlerise": "bowdlerize",
146
+ "bowdlerised": "bowdlerized",
147
+ "bowdlerises": "bowdlerizes",
148
+ "bowdlerising": "bowdlerizing",
149
+ "breathalyse": "breathalyze",
150
+ "breathalysed": "breathalyzed",
151
+ "breathalyser": "breathalyzer",
152
+ "breathalysers": "breathalyzers",
153
+ "breathalyses": "breathalyzes",
154
+ "breathalysing": "breathalyzing",
155
+ "brutalise": "brutalize",
156
+ "brutalised": "brutalized",
157
+ "brutalises": "brutalizes",
158
+ "brutalising": "brutalizing",
159
+ "busses": "buses",
160
+ "bussing": "busing",
161
+ "caesarean": "cesarean",
162
+ "caesareans": "cesareans",
163
+ "calibre": "caliber",
164
+ "calibres": "calibers",
165
+ "calliper": "caliper",
166
+ "callipers": "calipers",
167
+ "callisthenics": "calisthenics",
168
+ "canalise": "canalize",
169
+ "canalised": "canalized",
170
+ "canalises": "canalizes",
171
+ "canalising": "canalizing",
172
+ "cancelation": "cancellation",
173
+ "cancelations": "cancellations",
174
+ "cancelled": "canceled",
175
+ "cancelling": "canceling",
176
+ "candour": "candor",
177
+ "cannibalise": "cannibalize",
178
+ "cannibalised": "cannibalized",
179
+ "cannibalises": "cannibalizes",
180
+ "cannibalising": "cannibalizing",
181
+ "canonise": "canonize",
182
+ "canonised": "canonized",
183
+ "canonises": "canonizes",
184
+ "canonising": "canonizing",
185
+ "capitalise": "capitalize",
186
+ "capitalised": "capitalized",
187
+ "capitalises": "capitalizes",
188
+ "capitalising": "capitalizing",
189
+ "caramelise": "caramelize",
190
+ "caramelised": "caramelized",
191
+ "caramelises": "caramelizes",
192
+ "caramelising": "caramelizing",
193
+ "carbonise": "carbonize",
194
+ "carbonised": "carbonized",
195
+ "carbonises": "carbonizes",
196
+ "carbonising": "carbonizing",
197
+ "carolled": "caroled",
198
+ "carolling": "caroling",
199
+ "catalogue": "catalog",
200
+ "catalogued": "cataloged",
201
+ "catalogues": "catalogs",
202
+ "cataloguing": "cataloging",
203
+ "catalyse": "catalyze",
204
+ "catalysed": "catalyzed",
205
+ "catalyses": "catalyzes",
206
+ "catalysing": "catalyzing",
207
+ "categorise": "categorize",
208
+ "categorised": "categorized",
209
+ "categorises": "categorizes",
210
+ "categorising": "categorizing",
211
+ "cauterise": "cauterize",
212
+ "cauterised": "cauterized",
213
+ "cauterises": "cauterizes",
214
+ "cauterising": "cauterizing",
215
+ "cavilled": "caviled",
216
+ "cavilling": "caviling",
217
+ "centigramme": "centigram",
218
+ "centigrammes": "centigrams",
219
+ "centilitre": "centiliter",
220
+ "centilitres": "centiliters",
221
+ "centimetre": "centimeter",
222
+ "centimetres": "centimeters",
223
+ "centralise": "centralize",
224
+ "centralised": "centralized",
225
+ "centralises": "centralizes",
226
+ "centralising": "centralizing",
227
+ "centre": "center",
228
+ "centred": "centered",
229
+ "centrefold": "centerfold",
230
+ "centrefolds": "centerfolds",
231
+ "centrepiece": "centerpiece",
232
+ "centrepieces": "centerpieces",
233
+ "centres": "centers",
234
+ "channelled": "channeled",
235
+ "channelling": "channeling",
236
+ "characterise": "characterize",
237
+ "characterised": "characterized",
238
+ "characterises": "characterizes",
239
+ "characterising": "characterizing",
240
+ "cheque": "check",
241
+ "chequebook": "checkbook",
242
+ "chequebooks": "checkbooks",
243
+ "chequered": "checkered",
244
+ "cheques": "checks",
245
+ "chilli": "chili",
246
+ "chimaera": "chimera",
247
+ "chimaeras": "chimeras",
248
+ "chiselled": "chiseled",
249
+ "chiselling": "chiseling",
250
+ "circularise": "circularize",
251
+ "circularised": "circularized",
252
+ "circularises": "circularizes",
253
+ "circularising": "circularizing",
254
+ "civilise": "civilize",
255
+ "civilised": "civilized",
256
+ "civilises": "civilizes",
257
+ "civilising": "civilizing",
258
+ "clamour": "clamor",
259
+ "clamoured": "clamored",
260
+ "clamouring": "clamoring",
261
+ "clamours": "clamors",
262
+ "clangour": "clangor",
263
+ "clarinettist": "clarinetist",
264
+ "clarinettists": "clarinetists",
265
+ "collectivise": "collectivize",
266
+ "collectivised": "collectivized",
267
+ "collectivises": "collectivizes",
268
+ "collectivising": "collectivizing",
269
+ "colonisation": "colonization",
270
+ "colonise": "colonize",
271
+ "colonised": "colonized",
272
+ "coloniser": "colonizer",
273
+ "colonisers": "colonizers",
274
+ "colonises": "colonizes",
275
+ "colonising": "colonizing",
276
+ "colour": "color",
277
+ "colourant": "colorant",
278
+ "colourants": "colorants",
279
+ "coloured": "colored",
280
+ "coloureds": "coloreds",
281
+ "colourful": "colorful",
282
+ "colourfully": "colorfully",
283
+ "colouring": "coloring",
284
+ "colourize": "colorize",
285
+ "colourized": "colorized",
286
+ "colourizes": "colorizes",
287
+ "colourizing": "colorizing",
288
+ "colourless": "colorless",
289
+ "colours": "colors",
290
+ "commercialise": "commercialize",
291
+ "commercialised": "commercialized",
292
+ "commercialises": "commercializes",
293
+ "commercialising": "commercializing",
294
+ "compartmentalise": "compartmentalize",
295
+ "compartmentalised": "compartmentalized",
296
+ "compartmentalises": "compartmentalizes",
297
+ "compartmentalising": "compartmentalizing",
298
+ "computerise": "computerize",
299
+ "computerised": "computerized",
300
+ "computerises": "computerizes",
301
+ "computerising": "computerizing",
302
+ "conceptualise": "conceptualize",
303
+ "conceptualised": "conceptualized",
304
+ "conceptualises": "conceptualizes",
305
+ "conceptualising": "conceptualizing",
306
+ "connexion": "connection",
307
+ "connexions": "connections",
308
+ "contextualise": "contextualize",
309
+ "contextualised": "contextualized",
310
+ "contextualises": "contextualizes",
311
+ "contextualising": "contextualizing",
312
+ "cosier": "cozier",
313
+ "cosies": "cozies",
314
+ "cosiest": "coziest",
315
+ "cosily": "cozily",
316
+ "cosiness": "coziness",
317
+ "cosy": "cozy",
318
+ "councillor": "councilor",
319
+ "councillors": "councilors",
320
+ "counselled": "counseled",
321
+ "counselling": "counseling",
322
+ "counsellor": "counselor",
323
+ "counsellors": "counselors",
324
+ "crenelated": "crenellated",
325
+ "criminalise": "criminalize",
326
+ "criminalised": "criminalized",
327
+ "criminalises": "criminalizes",
328
+ "criminalising": "criminalizing",
329
+ "criticise": "criticize",
330
+ "criticised": "criticized",
331
+ "criticises": "criticizes",
332
+ "criticising": "criticizing",
333
+ "crueller": "crueler",
334
+ "cruellest": "cruelest",
335
+ "crystallisation": "crystallization",
336
+ "crystallise": "crystallize",
337
+ "crystallised": "crystallized",
338
+ "crystallises": "crystallizes",
339
+ "crystallising": "crystallizing",
340
+ "cudgelled": "cudgeled",
341
+ "cudgelling": "cudgeling",
342
+ "customise": "customize",
343
+ "customised": "customized",
344
+ "customises": "customizes",
345
+ "customising": "customizing",
346
+ "cypher": "cipher",
347
+ "cyphers": "ciphers",
348
+ "decentralisation": "decentralization",
349
+ "decentralise": "decentralize",
350
+ "decentralised": "decentralized",
351
+ "decentralises": "decentralizes",
352
+ "decentralising": "decentralizing",
353
+ "decriminalisation": "decriminalization",
354
+ "decriminalise": "decriminalize",
355
+ "decriminalised": "decriminalized",
356
+ "decriminalises": "decriminalizes",
357
+ "decriminalising": "decriminalizing",
358
+ "defence": "defense",
359
+ "defenceless": "defenseless",
360
+ "defences": "defenses",
361
+ "dehumanisation": "dehumanization",
362
+ "dehumanise": "dehumanize",
363
+ "dehumanised": "dehumanized",
364
+ "dehumanises": "dehumanizes",
365
+ "dehumanising": "dehumanizing",
366
+ "demeanour": "demeanor",
367
+ "demilitarisation": "demilitarization",
368
+ "demilitarise": "demilitarize",
369
+ "demilitarised": "demilitarized",
370
+ "demilitarises": "demilitarizes",
371
+ "demilitarising": "demilitarizing",
372
+ "demobilisation": "demobilization",
373
+ "demobilise": "demobilize",
374
+ "demobilised": "demobilized",
375
+ "demobilises": "demobilizes",
376
+ "demobilising": "demobilizing",
377
+ "democratisation": "democratization",
378
+ "democratise": "democratize",
379
+ "democratised": "democratized",
380
+ "democratises": "democratizes",
381
+ "democratising": "democratizing",
382
+ "demonise": "demonize",
383
+ "demonised": "demonized",
384
+ "demonises": "demonizes",
385
+ "demonising": "demonizing",
386
+ "demoralisation": "demoralization",
387
+ "demoralise": "demoralize",
388
+ "demoralised": "demoralized",
389
+ "demoralises": "demoralizes",
390
+ "demoralising": "demoralizing",
391
+ "denationalisation": "denationalization",
392
+ "denationalise": "denationalize",
393
+ "denationalised": "denationalized",
394
+ "denationalises": "denationalizes",
395
+ "denationalising": "denationalizing",
396
+ "deodorise": "deodorize",
397
+ "deodorised": "deodorized",
398
+ "deodorises": "deodorizes",
399
+ "deodorising": "deodorizing",
400
+ "depersonalise": "depersonalize",
401
+ "depersonalised": "depersonalized",
402
+ "depersonalises": "depersonalizes",
403
+ "depersonalising": "depersonalizing",
404
+ "deputise": "deputize",
405
+ "deputised": "deputized",
406
+ "deputises": "deputizes",
407
+ "deputising": "deputizing",
408
+ "desensitisation": "desensitization",
409
+ "desensitise": "desensitize",
410
+ "desensitised": "desensitized",
411
+ "desensitises": "desensitizes",
412
+ "desensitising": "desensitizing",
413
+ "destabilisation": "destabilization",
414
+ "destabilise": "destabilize",
415
+ "destabilised": "destabilized",
416
+ "destabilises": "destabilizes",
417
+ "destabilising": "destabilizing",
418
+ "dialled": "dialed",
419
+ "dialling": "dialing",
420
+ "dialogue": "dialog",
421
+ "dialogues": "dialogs",
422
+ "diarrhoea": "diarrhea",
423
+ "digitise": "digitize",
424
+ "digitised": "digitized",
425
+ "digitises": "digitizes",
426
+ "digitising": "digitizing",
427
+ "disc": "disk",
428
+ "discolour": "discolor",
429
+ "discoloured": "discolored",
430
+ "discolouring": "discoloring",
431
+ "discolours": "discolors",
432
+ "discs": "disks",
433
+ "disembowelled": "disemboweled",
434
+ "disembowelling": "disemboweling",
435
+ "disfavour": "disfavor",
436
+ "dishevelled": "disheveled",
437
+ "dishonour": "dishonor",
438
+ "dishonourable": "dishonorable",
439
+ "dishonourably": "dishonorably",
440
+ "dishonoured": "dishonored",
441
+ "dishonouring": "dishonoring",
442
+ "dishonours": "dishonors",
443
+ "disorganisation": "disorganization",
444
+ "disorganised": "disorganized",
445
+ "distil": "distill",
446
+ "distils": "distills",
447
+ "dramatisation": "dramatization",
448
+ "dramatisations": "dramatizations",
449
+ "dramatise": "dramatize",
450
+ "dramatised": "dramatized",
451
+ "dramatises": "dramatizes",
452
+ "dramatising": "dramatizing",
453
+ "draught": "draft",
454
+ "draughtboard": "draftboard",
455
+ "draughtboards": "draftboards",
456
+ "draughtier": "draftier",
457
+ "draughtiest": "draftiest",
458
+ "draughts": "drafts",
459
+ "draughtsman": "draftsman",
460
+ "draughtsmanship": "draftsmanship",
461
+ "draughtsmen": "draftsmen",
462
+ "draughtswoman": "draftswoman",
463
+ "draughtswomen": "draftswomen",
464
+ "draughty": "drafty",
465
+ "drivelled": "driveled",
466
+ "drivelling": "driveling",
467
+ "duelled": "dueled",
468
+ "duelling": "dueling",
469
+ "economise": "economize",
470
+ "economised": "economized",
471
+ "economises": "economizes",
472
+ "economising": "economizing",
473
+ "editorialise": "editorialize",
474
+ "editorialised": "editorialized",
475
+ "editorialises": "editorializes",
476
+ "editorialising": "editorializing",
477
+ "edoema": "edema",
478
+ "empathise": "empathize",
479
+ "empathised": "empathized",
480
+ "empathises": "empathizes",
481
+ "empathising": "empathizing",
482
+ "emphasise": "emphasize",
483
+ "emphasised": "emphasized",
484
+ "emphasises": "emphasizes",
485
+ "emphasising": "emphasizing",
486
+ "enamelled": "enameled",
487
+ "enamelling": "enameling",
488
+ "enamoured": "enamored",
489
+ "encyclopaedia": "encyclopedia",
490
+ "encyclopaedias": "encyclopedias",
491
+ "encyclopaedic": "encyclopedic",
492
+ "endeavour": "endeavor",
493
+ "endeavoured": "endeavored",
494
+ "endeavouring": "endeavoring",
495
+ "endeavours": "endeavors",
496
+ "energise": "energize",
497
+ "energised": "energized",
498
+ "energises": "energizes",
499
+ "energising": "energizing",
500
+ "enrol": "enroll",
501
+ "enrols": "enrolls",
502
+ "enthral": "enthrall",
503
+ "enthrals": "enthralls",
504
+ "epaulette": "epaulet",
505
+ "epaulettes": "epaulets",
506
+ "epicentre": "epicenter",
507
+ "epicentres": "epicenters",
508
+ "epilogue": "epilog",
509
+ "epilogues": "epilogs",
510
+ "epitomise": "epitomize",
511
+ "epitomised": "epitomized",
512
+ "epitomises": "epitomizes",
513
+ "epitomising": "epitomizing",
514
+ "equalisation": "equalization",
515
+ "equalise": "equalize",
516
+ "equalised": "equalized",
517
+ "equaliser": "equalizer",
518
+ "equalisers": "equalizers",
519
+ "equalises": "equalizes",
520
+ "equalising": "equalizing",
521
+ "eulogise": "eulogize",
522
+ "eulogised": "eulogized",
523
+ "eulogises": "eulogizes",
524
+ "eulogising": "eulogizing",
525
+ "evangelise": "evangelize",
526
+ "evangelised": "evangelized",
527
+ "evangelises": "evangelizes",
528
+ "evangelising": "evangelizing",
529
+ "exorcise": "exorcize",
530
+ "exorcised": "exorcized",
531
+ "exorcises": "exorcizes",
532
+ "exorcising": "exorcizing",
533
+ "extemporisation": "extemporization",
534
+ "extemporise": "extemporize",
535
+ "extemporised": "extemporized",
536
+ "extemporises": "extemporizes",
537
+ "extemporising": "extemporizing",
538
+ "externalisation": "externalization",
539
+ "externalisations": "externalizations",
540
+ "externalise": "externalize",
541
+ "externalised": "externalized",
542
+ "externalises": "externalizes",
543
+ "externalising": "externalizing",
544
+ "factorise": "factorize",
545
+ "factorised": "factorized",
546
+ "factorises": "factorizes",
547
+ "factorising": "factorizing",
548
+ "faecal": "fecal",
549
+ "faeces": "feces",
550
+ "familiarisation": "familiarization",
551
+ "familiarise": "familiarize",
552
+ "familiarised": "familiarized",
553
+ "familiarises": "familiarizes",
554
+ "familiarising": "familiarizing",
555
+ "fantasise": "fantasize",
556
+ "fantasised": "fantasized",
557
+ "fantasises": "fantasizes",
558
+ "fantasising": "fantasizing",
559
+ "favour": "favor",
560
+ "favourable": "favorable",
561
+ "favourably": "favorably",
562
+ "favoured": "favored",
563
+ "favouring": "favoring",
564
+ "favourite": "favorite",
565
+ "favourites": "favorites",
566
+ "favouritism": "favoritism",
567
+ "favours": "favors",
568
+ "feminise": "feminize",
569
+ "feminised": "feminized",
570
+ "feminises": "feminizes",
571
+ "feminising": "feminizing",
572
+ "fertilisation": "fertilization",
573
+ "fertilise": "fertilize",
574
+ "fertilised": "fertilized",
575
+ "fertiliser": "fertilizer",
576
+ "fertilisers": "fertilizers",
577
+ "fertilises": "fertilizes",
578
+ "fertilising": "fertilizing",
579
+ "fervour": "fervor",
580
+ "fibre": "fiber",
581
+ "fibreglass": "fiberglass",
582
+ "fibres": "fibers",
583
+ "fictionalisation": "fictionalization",
584
+ "fictionalisations": "fictionalizations",
585
+ "fictionalise": "fictionalize",
586
+ "fictionalised": "fictionalized",
587
+ "fictionalises": "fictionalizes",
588
+ "fictionalising": "fictionalizing",
589
+ "fillet": "filet",
590
+ "filleted": "fileted",
591
+ "filleting": "fileting",
592
+ "fillets": "filets",
593
+ "finalisation": "finalization",
594
+ "finalise": "finalize",
595
+ "finalised": "finalized",
596
+ "finalises": "finalizes",
597
+ "finalising": "finalizing",
598
+ "flautist": "flutist",
599
+ "flautists": "flutists",
600
+ "flavour": "flavor",
601
+ "flavoured": "flavored",
602
+ "flavouring": "flavoring",
603
+ "flavourings": "flavorings",
604
+ "flavourless": "flavorless",
605
+ "flavours": "flavors",
606
+ "flavoursome": "flavorsome",
607
+ "flyer / flier": "flier / flyer",
608
+ "foetal": "fetal",
609
+ "foetid": "fetid",
610
+ "foetus": "fetus",
611
+ "foetuses": "fetuses",
612
+ "formalisation": "formalization",
613
+ "formalise": "formalize",
614
+ "formalised": "formalized",
615
+ "formalises": "formalizes",
616
+ "formalising": "formalizing",
617
+ "fossilisation": "fossilization",
618
+ "fossilise": "fossilize",
619
+ "fossilised": "fossilized",
620
+ "fossilises": "fossilizes",
621
+ "fossilising": "fossilizing",
622
+ "fraternisation": "fraternization",
623
+ "fraternise": "fraternize",
624
+ "fraternised": "fraternized",
625
+ "fraternises": "fraternizes",
626
+ "fraternising": "fraternizing",
627
+ "fulfil": "fulfill",
628
+ "fulfilment": "fulfillment",
629
+ "fulfils": "fulfills",
630
+ "funnelled": "funneled",
631
+ "funnelling": "funneling",
632
+ "gage": "gauge",
633
+ "gaged": "gauged",
634
+ "gages": "gauges",
635
+ "gaging": "gauging",
636
+ "galvanise": "galvanize",
637
+ "galvanised": "galvanized",
638
+ "galvanises": "galvanizes",
639
+ "galvanising": "galvanizing",
640
+ "gambolled": "gamboled",
641
+ "gambolling": "gamboling",
642
+ "gaol": "jail",
643
+ "gaolbird": "jailbird",
644
+ "gaolbirds": "jailbirds",
645
+ "gaolbreak": "jailbreak",
646
+ "gaolbreaks": "jailbreaks",
647
+ "gaoled": "jailed",
648
+ "gaoler": "jailer",
649
+ "gaolers": "jailers",
650
+ "gaoling": "jailing",
651
+ "gaols": "jails",
652
+ "gasses": "gases",
653
+ "generalisation": "generalization",
654
+ "generalisations": "generalizations",
655
+ "generalise": "generalize",
656
+ "generalised": "generalized",
657
+ "generalises": "generalizes",
658
+ "generalising": "generalizing",
659
+ "ghettoise": "ghettoize",
660
+ "ghettoised": "ghettoized",
661
+ "ghettoises": "ghettoizes",
662
+ "ghettoising": "ghettoizing",
663
+ "gipsies": "gypsies",
664
+ "glamor": "glamour",
665
+ "glamorise": "glamorize",
666
+ "glamorised": "glamorized",
667
+ "glamorises": "glamorizes",
668
+ "glamorising": "glamorizing",
669
+ "globalisation": "globalization",
670
+ "globalise": "globalize",
671
+ "globalised": "globalized",
672
+ "globalises": "globalizes",
673
+ "globalising": "globalizing",
674
+ "glueing": "gluing",
675
+ "goitre": "goiter",
676
+ "goitres": "goiters",
677
+ "gonorrhoea": "gonorrhea",
678
+ "gramme": "gram",
679
+ "grammes": "grams",
680
+ "gravelled": "graveled",
681
+ "grey": "gray",
682
+ "greyed": "grayed",
683
+ "greying": "graying",
684
+ "greyish": "grayish",
685
+ "greyness": "grayness",
686
+ "greys": "grays",
687
+ "grovelled": "groveled",
688
+ "grovelling": "groveling",
689
+ "groyne": "groin",
690
+ "groynes": "groins",
691
+ "gruelling": "grueling",
692
+ "gruellingly": "gruelingly",
693
+ "gryphon": "griffin",
694
+ "gryphons": "griffins",
695
+ "gynaecological": "gynecological",
696
+ "gynaecologist": "gynecologist",
697
+ "gynaecologists": "gynecologists",
698
+ "gynaecology": "gynecology",
699
+ "haematological": "hematological",
700
+ "haematologist": "hematologist",
701
+ "haematologists": "hematologists",
702
+ "haematology": "hematology",
703
+ "haemoglobin": "hemoglobin",
704
+ "haemophilia": "hemophilia",
705
+ "haemophiliac": "hemophiliac",
706
+ "haemophiliacs": "hemophiliacs",
707
+ "haemorrhage": "hemorrhage",
708
+ "haemorrhaged": "hemorrhaged",
709
+ "haemorrhages": "hemorrhages",
710
+ "haemorrhaging": "hemorrhaging",
711
+ "haemorrhoids": "hemorrhoids",
712
+ "harbour": "harbor",
713
+ "harboured": "harbored",
714
+ "harbouring": "harboring",
715
+ "harbours": "harbors",
716
+ "harmonisation": "harmonization",
717
+ "harmonise": "harmonize",
718
+ "harmonised": "harmonized",
719
+ "harmonises": "harmonizes",
720
+ "harmonising": "harmonizing",
721
+ "homoeopath": "homeopath",
722
+ "homoeopathic": "homeopathic",
723
+ "homoeopaths": "homeopaths",
724
+ "homoeopathy": "homeopathy",
725
+ "homogenise": "homogenize",
726
+ "homogenised": "homogenized",
727
+ "homogenises": "homogenizes",
728
+ "homogenising": "homogenizing",
729
+ "honour": "honor",
730
+ "honourable": "honorable",
731
+ "honourably": "honorably",
732
+ "honoured": "honored",
733
+ "honouring": "honoring",
734
+ "honours": "honors",
735
+ "hospitalisation": "hospitalization",
736
+ "hospitalise": "hospitalize",
737
+ "hospitalised": "hospitalized",
738
+ "hospitalises": "hospitalizes",
739
+ "hospitalising": "hospitalizing",
740
+ "humanise": "humanize",
741
+ "humanised": "humanized",
742
+ "humanises": "humanizes",
743
+ "humanising": "humanizing",
744
+ "humour": "humor",
745
+ "humoured": "humored",
746
+ "humouring": "humoring",
747
+ "humourless": "humorless",
748
+ "humours": "humors",
749
+ "hybridise": "hybridize",
750
+ "hybridised": "hybridized",
751
+ "hybridises": "hybridizes",
752
+ "hybridising": "hybridizing",
753
+ "hypnotise": "hypnotize",
754
+ "hypnotised": "hypnotized",
755
+ "hypnotises": "hypnotizes",
756
+ "hypnotising": "hypnotizing",
757
+ "hypothesise": "hypothesize",
758
+ "hypothesised": "hypothesized",
759
+ "hypothesises": "hypothesizes",
760
+ "hypothesising": "hypothesizing",
761
+ "idealisation": "idealization",
762
+ "idealise": "idealize",
763
+ "idealised": "idealized",
764
+ "idealises": "idealizes",
765
+ "idealising": "idealizing",
766
+ "idolise": "idolize",
767
+ "idolised": "idolized",
768
+ "idolises": "idolizes",
769
+ "idolising": "idolizing",
770
+ "immobilisation": "immobilization",
771
+ "immobilise": "immobilize",
772
+ "immobilised": "immobilized",
773
+ "immobiliser": "immobilizer",
774
+ "immobilisers": "immobilizers",
775
+ "immobilises": "immobilizes",
776
+ "immobilising": "immobilizing",
777
+ "immortalise": "immortalize",
778
+ "immortalised": "immortalized",
779
+ "immortalises": "immortalizes",
780
+ "immortalising": "immortalizing",
781
+ "immunisation": "immunization",
782
+ "immunise": "immunize",
783
+ "immunised": "immunized",
784
+ "immunises": "immunizes",
785
+ "immunising": "immunizing",
786
+ "impanelled": "impaneled",
787
+ "impanelling": "impaneling",
788
+ "imperilled": "imperiled",
789
+ "imperilling": "imperiling",
790
+ "individualise": "individualize",
791
+ "individualised": "individualized",
792
+ "individualises": "individualizes",
793
+ "individualising": "individualizing",
794
+ "industrialise": "industrialize",
795
+ "industrialised": "industrialized",
796
+ "industrialises": "industrializes",
797
+ "industrialising": "industrializing",
798
+ "inflexion": "inflection",
799
+ "inflexions": "inflections",
800
+ "initialise": "initialize",
801
+ "initialised": "initialized",
802
+ "initialises": "initializes",
803
+ "initialising": "initializing",
804
+ "initialled": "initialed",
805
+ "initialling": "initialing",
806
+ "instal": "install",
807
+ "instalment": "installment",
808
+ "instalments": "installments",
809
+ "instals": "installs",
810
+ "instil": "instill",
811
+ "instils": "instills",
812
+ "institutionalisation": "institutionalization",
813
+ "institutionalise": "institutionalize",
814
+ "institutionalised": "institutionalized",
815
+ "institutionalises": "institutionalizes",
816
+ "institutionalising": "institutionalizing",
817
+ "intellectualise": "intellectualize",
818
+ "intellectualised": "intellectualized",
819
+ "intellectualises": "intellectualizes",
820
+ "intellectualising": "intellectualizing",
821
+ "internalisation": "internalization",
822
+ "internalise": "internalize",
823
+ "internalised": "internalized",
824
+ "internalises": "internalizes",
825
+ "internalising": "internalizing",
826
+ "internationalisation": "internationalization",
827
+ "internationalise": "internationalize",
828
+ "internationalised": "internationalized",
829
+ "internationalises": "internationalizes",
830
+ "internationalising": "internationalizing",
831
+ "ionisation": "ionization",
832
+ "ionise": "ionize",
833
+ "ionised": "ionized",
834
+ "ioniser": "ionizer",
835
+ "ionisers": "ionizers",
836
+ "ionises": "ionizes",
837
+ "ionising": "ionizing",
838
+ "italicise": "italicize",
839
+ "italicised": "italicized",
840
+ "italicises": "italicizes",
841
+ "italicising": "italicizing",
842
+ "itemise": "itemize",
843
+ "itemised": "itemized",
844
+ "itemises": "itemizes",
845
+ "itemising": "itemizing",
846
+ "jeopardise": "jeopardize",
847
+ "jeopardised": "jeopardized",
848
+ "jeopardises": "jeopardizes",
849
+ "jeopardising": "jeopardizing",
850
+ "jewelled": "jeweled",
851
+ "jeweller": "jeweler",
852
+ "jewellers": "jewelers",
853
+ "jewellery": "jewelry",
854
+ "judgement": "judgment",
855
+ "kilogramme": "kilogram",
856
+ "kilogrammes": "kilograms",
857
+ "kilometre": "kilometer",
858
+ "kilometres": "kilometers",
859
+ "labelled": "labeled",
860
+ "labelling": "labeling",
861
+ "labour": "labor",
862
+ "laboured": "labored",
863
+ "labourer": "laborer",
864
+ "labourers": "laborers",
865
+ "labouring": "laboring",
866
+ "labours": "labors",
867
+ "lacklustre": "lackluster",
868
+ "legalisation": "legalization",
869
+ "legalise": "legalize",
870
+ "legalised": "legalized",
871
+ "legalises": "legalizes",
872
+ "legalising": "legalizing",
873
+ "legitimise": "legitimize",
874
+ "legitimised": "legitimized",
875
+ "legitimises": "legitimizes",
876
+ "legitimising": "legitimizing",
877
+ "leukaemia": "leukemia",
878
+ "levelled": "leveled",
879
+ "leveller": "leveler",
880
+ "levellers": "levelers",
881
+ "levelling": "leveling",
882
+ "libelled": "libeled",
883
+ "libelling": "libeling",
884
+ "libellous": "libelous",
885
+ "liberalisation": "liberalization",
886
+ "liberalise": "liberalize",
887
+ "liberalised": "liberalized",
888
+ "liberalises": "liberalizes",
889
+ "liberalising": "liberalizing",
890
+ "licence": "license",
891
+ "licenced": "licensed",
892
+ "licences": "licenses",
893
+ "licencing": "licensing",
894
+ "likeable": "likable",
895
+ "lionisation": "lionization",
896
+ "lionise": "lionize",
897
+ "lionised": "lionized",
898
+ "lionises": "lionizes",
899
+ "lionising": "lionizing",
900
+ "liquidise": "liquidize",
901
+ "liquidised": "liquidized",
902
+ "liquidiser": "liquidizer",
903
+ "liquidisers": "liquidizers",
904
+ "liquidises": "liquidizes",
905
+ "liquidising": "liquidizing",
906
+ "litre": "liter",
907
+ "litres": "liters",
908
+ "localise": "localize",
909
+ "localised": "localized",
910
+ "localises": "localizes",
911
+ "localising": "localizing",
912
+ "louvre": "louver",
913
+ "louvred": "louvered",
914
+ "louvres": "louvers",
915
+ "lustre": "luster",
916
+ "magnetise": "magnetize",
917
+ "magnetised": "magnetized",
918
+ "magnetises": "magnetizes",
919
+ "magnetising": "magnetizing",
920
+ "manoeuvrability": "maneuverability",
921
+ "manoeuvrable": "maneuverable",
922
+ "manoeuvre": "maneuver",
923
+ "manoeuvred": "maneuvered",
924
+ "manoeuvres": "maneuvers",
925
+ "manoeuvring": "maneuvering",
926
+ "manoeuvrings": "maneuverings",
927
+ "marginalisation": "marginalization",
928
+ "marginalise": "marginalize",
929
+ "marginalised": "marginalized",
930
+ "marginalises": "marginalizes",
931
+ "marginalising": "marginalizing",
932
+ "marshalled": "marshaled",
933
+ "marshalling": "marshaling",
934
+ "marvelled": "marveled",
935
+ "marvelling": "marveling",
936
+ "marvellous": "marvelous",
937
+ "marvellously": "marvelously",
938
+ "materialisation": "materialization",
939
+ "materialise": "materialize",
940
+ "materialised": "materialized",
941
+ "materialises": "materializes",
942
+ "materialising": "materializing",
943
+ "maximisation": "maximization",
944
+ "maximise": "maximize",
945
+ "maximised": "maximized",
946
+ "maximises": "maximizes",
947
+ "maximising": "maximizing",
948
+ "meagre": "meager",
949
+ "mechanisation": "mechanization",
950
+ "mechanise": "mechanize",
951
+ "mechanised": "mechanized",
952
+ "mechanises": "mechanizes",
953
+ "mechanising": "mechanizing",
954
+ "mediaeval": "medieval",
955
+ "memorialise": "memorialize",
956
+ "memorialised": "memorialized",
957
+ "memorialises": "memorializes",
958
+ "memorialising": "memorializing",
959
+ "memorise": "memorize",
960
+ "memorised": "memorized",
961
+ "memorises": "memorizes",
962
+ "memorising": "memorizing",
963
+ "mesmerise": "mesmerize",
964
+ "mesmerised": "mesmerized",
965
+ "mesmerises": "mesmerizes",
966
+ "mesmerising": "mesmerizing",
967
+ "metabolise": "metabolize",
968
+ "metabolised": "metabolized",
969
+ "metabolises": "metabolizes",
970
+ "metabolising": "metabolizing",
971
+ "metre": "meter",
972
+ "metres": "meters",
973
+ "mhm": "hmm",
974
+ "micrometre": "micrometer",
975
+ "micrometres": "micrometers",
976
+ "militarise": "militarize",
977
+ "militarised": "militarized",
978
+ "militarises": "militarizes",
979
+ "militarising": "militarizing",
980
+ "milligramme": "milligram",
981
+ "milligrammes": "milligrams",
982
+ "millilitre": "milliliter",
983
+ "millilitres": "milliliters",
984
+ "millimetre": "millimeter",
985
+ "millimetres": "millimeters",
986
+ "miniaturisation": "miniaturization",
987
+ "miniaturise": "miniaturize",
988
+ "miniaturised": "miniaturized",
989
+ "miniaturises": "miniaturizes",
990
+ "miniaturising": "miniaturizing",
991
+ "minibusses": "minibuses",
992
+ "minimise": "minimize",
993
+ "minimised": "minimized",
994
+ "minimises": "minimizes",
995
+ "minimising": "minimizing",
996
+ "misbehaviour": "misbehavior",
997
+ "misdemeanour": "misdemeanor",
998
+ "misdemeanours": "misdemeanors",
999
+ "misspelt": "misspelled",
1000
+ "mitre": "miter",
1001
+ "mitres": "miters",
1002
+ "mm": "hmm",
1003
+ "mmm": "hmm",
1004
+ "mobilisation": "mobilization",
1005
+ "mobilise": "mobilize",
1006
+ "mobilised": "mobilized",
1007
+ "mobilises": "mobilizes",
1008
+ "mobilising": "mobilizing",
1009
+ "modelled": "modeled",
1010
+ "modeller": "modeler",
1011
+ "modellers": "modelers",
1012
+ "modelling": "modeling",
1013
+ "modernise": "modernize",
1014
+ "modernised": "modernized",
1015
+ "modernises": "modernizes",
1016
+ "modernising": "modernizing",
1017
+ "moisturise": "moisturize",
1018
+ "moisturised": "moisturized",
1019
+ "moisturiser": "moisturizer",
1020
+ "moisturisers": "moisturizers",
1021
+ "moisturises": "moisturizes",
1022
+ "moisturising": "moisturizing",
1023
+ "monologue": "monolog",
1024
+ "monologues": "monologs",
1025
+ "monopolisation": "monopolization",
1026
+ "monopolise": "monopolize",
1027
+ "monopolised": "monopolized",
1028
+ "monopolises": "monopolizes",
1029
+ "monopolising": "monopolizing",
1030
+ "moralise": "moralize",
1031
+ "moralised": "moralized",
1032
+ "moralises": "moralizes",
1033
+ "moralising": "moralizing",
1034
+ "motorised": "motorized",
1035
+ "mould": "mold",
1036
+ "moulded": "molded",
1037
+ "moulder": "molder",
1038
+ "mouldered": "moldered",
1039
+ "mouldering": "moldering",
1040
+ "moulders": "molders",
1041
+ "mouldier": "moldier",
1042
+ "mouldiest": "moldiest",
1043
+ "moulding": "molding",
1044
+ "mouldings": "moldings",
1045
+ "moulds": "molds",
1046
+ "mouldy": "moldy",
1047
+ "moult": "molt",
1048
+ "moulted": "molted",
1049
+ "moulting": "molting",
1050
+ "moults": "molts",
1051
+ "moustache": "mustache",
1052
+ "moustached": "mustached",
1053
+ "moustaches": "mustaches",
1054
+ "moustachioed": "mustachioed",
1055
+ "multicoloured": "multicolored",
1056
+ "nationalisation": "nationalization",
1057
+ "nationalisations": "nationalizations",
1058
+ "nationalise": "nationalize",
1059
+ "nationalised": "nationalized",
1060
+ "nationalises": "nationalizes",
1061
+ "nationalising": "nationalizing",
1062
+ "naturalisation": "naturalization",
1063
+ "naturalise": "naturalize",
1064
+ "naturalised": "naturalized",
1065
+ "naturalises": "naturalizes",
1066
+ "naturalising": "naturalizing",
1067
+ "neighbour": "neighbor",
1068
+ "neighbourhood": "neighborhood",
1069
+ "neighbourhoods": "neighborhoods",
1070
+ "neighbouring": "neighboring",
1071
+ "neighbourliness": "neighborliness",
1072
+ "neighbourly": "neighborly",
1073
+ "neighbours": "neighbors",
1074
+ "neutralisation": "neutralization",
1075
+ "neutralise": "neutralize",
1076
+ "neutralised": "neutralized",
1077
+ "neutralises": "neutralizes",
1078
+ "neutralising": "neutralizing",
1079
+ "normalisation": "normalization",
1080
+ "normalise": "normalize",
1081
+ "normalised": "normalized",
1082
+ "normalises": "normalizes",
1083
+ "normalising": "normalizing",
1084
+ "odour": "odor",
1085
+ "odourless": "odorless",
1086
+ "odours": "odors",
1087
+ "oesophagus": "esophagus",
1088
+ "oesophaguses": "esophaguses",
1089
+ "oestrogen": "estrogen",
1090
+ "offence": "offense",
1091
+ "offences": "offenses",
1092
+ "omelette": "omelet",
1093
+ "omelettes": "omelets",
1094
+ "optimise": "optimize",
1095
+ "optimised": "optimized",
1096
+ "optimises": "optimizes",
1097
+ "optimising": "optimizing",
1098
+ "organisation": "organization",
1099
+ "organisational": "organizational",
1100
+ "organisations": "organizations",
1101
+ "organise": "organize",
1102
+ "organised": "organized",
1103
+ "organiser": "organizer",
1104
+ "organisers": "organizers",
1105
+ "organises": "organizes",
1106
+ "organising": "organizing",
1107
+ "orthopaedic": "orthopedic",
1108
+ "orthopaedics": "orthopedics",
1109
+ "ostracise": "ostracize",
1110
+ "ostracised": "ostracized",
1111
+ "ostracises": "ostracizes",
1112
+ "ostracising": "ostracizing",
1113
+ "outmanoeuvre": "outmaneuver",
1114
+ "outmanoeuvred": "outmaneuvered",
1115
+ "outmanoeuvres": "outmaneuvers",
1116
+ "outmanoeuvring": "outmaneuvering",
1117
+ "overemphasise": "overemphasize",
1118
+ "overemphasised": "overemphasized",
1119
+ "overemphasises": "overemphasizes",
1120
+ "overemphasising": "overemphasizing",
1121
+ "oxidisation": "oxidization",
1122
+ "oxidise": "oxidize",
1123
+ "oxidised": "oxidized",
1124
+ "oxidises": "oxidizes",
1125
+ "oxidising": "oxidizing",
1126
+ "paederast": "pederast",
1127
+ "paederasts": "pederasts",
1128
+ "paediatric": "pediatric",
1129
+ "paediatrician": "pediatrician",
1130
+ "paediatricians": "pediatricians",
1131
+ "paediatrics": "pediatrics",
1132
+ "paedophile": "pedophile",
1133
+ "paedophiles": "pedophiles",
1134
+ "paedophilia": "pedophilia",
1135
+ "palaeolithic": "paleolithic",
1136
+ "palaeontologist": "paleontologist",
1137
+ "palaeontologists": "paleontologists",
1138
+ "palaeontology": "paleontology",
1139
+ "panelled": "paneled",
1140
+ "panelling": "paneling",
1141
+ "panellist": "panelist",
1142
+ "panellists": "panelists",
1143
+ "paralyse": "paralyze",
1144
+ "paralysed": "paralyzed",
1145
+ "paralyses": "paralyzes",
1146
+ "paralysing": "paralyzing",
1147
+ "parcelled": "parceled",
1148
+ "parcelling": "parceling",
1149
+ "parlour": "parlor",
1150
+ "parlours": "parlors",
1151
+ "particularise": "particularize",
1152
+ "particularised": "particularized",
1153
+ "particularises": "particularizes",
1154
+ "particularising": "particularizing",
1155
+ "passivisation": "passivization",
1156
+ "passivise": "passivize",
1157
+ "passivised": "passivized",
1158
+ "passivises": "passivizes",
1159
+ "passivising": "passivizing",
1160
+ "pasteurisation": "pasteurization",
1161
+ "pasteurise": "pasteurize",
1162
+ "pasteurised": "pasteurized",
1163
+ "pasteurises": "pasteurizes",
1164
+ "pasteurising": "pasteurizing",
1165
+ "patronise": "patronize",
1166
+ "patronised": "patronized",
1167
+ "patronises": "patronizes",
1168
+ "patronising": "patronizing",
1169
+ "patronisingly": "patronizingly",
1170
+ "pedalled": "pedaled",
1171
+ "pedalling": "pedaling",
1172
+ "pedestrianisation": "pedestrianization",
1173
+ "pedestrianise": "pedestrianize",
1174
+ "pedestrianised": "pedestrianized",
1175
+ "pedestrianises": "pedestrianizes",
1176
+ "pedestrianising": "pedestrianizing",
1177
+ "penalise": "penalize",
1178
+ "penalised": "penalized",
1179
+ "penalises": "penalizes",
1180
+ "penalising": "penalizing",
1181
+ "pencilled": "penciled",
1182
+ "pencilling": "penciling",
1183
+ "personalise": "personalize",
1184
+ "personalised": "personalized",
1185
+ "personalises": "personalizes",
1186
+ "personalising": "personalizing",
1187
+ "pharmacopoeia": "pharmacopeia",
1188
+ "pharmacopoeias": "pharmacopeias",
1189
+ "philosophise": "philosophize",
1190
+ "philosophised": "philosophized",
1191
+ "philosophises": "philosophizes",
1192
+ "philosophising": "philosophizing",
1193
+ "philtre": "filter",
1194
+ "philtres": "filters",
1195
+ "phoney": "phony",
1196
+ "plagiarise": "plagiarize",
1197
+ "plagiarised": "plagiarized",
1198
+ "plagiarises": "plagiarizes",
1199
+ "plagiarising": "plagiarizing",
1200
+ "plough": "plow",
1201
+ "ploughed": "plowed",
1202
+ "ploughing": "plowing",
1203
+ "ploughman": "plowman",
1204
+ "ploughmen": "plowmen",
1205
+ "ploughs": "plows",
1206
+ "ploughshare": "plowshare",
1207
+ "ploughshares": "plowshares",
1208
+ "polarisation": "polarization",
1209
+ "polarise": "polarize",
1210
+ "polarised": "polarized",
1211
+ "polarises": "polarizes",
1212
+ "polarising": "polarizing",
1213
+ "politicisation": "politicization",
1214
+ "politicise": "politicize",
1215
+ "politicised": "politicized",
1216
+ "politicises": "politicizes",
1217
+ "politicising": "politicizing",
1218
+ "popularisation": "popularization",
1219
+ "popularise": "popularize",
1220
+ "popularised": "popularized",
1221
+ "popularises": "popularizes",
1222
+ "popularising": "popularizing",
1223
+ "pouffe": "pouf",
1224
+ "pouffes": "poufs",
1225
+ "practise": "practice",
1226
+ "practised": "practiced",
1227
+ "practises": "practices",
1228
+ "practising": "practicing",
1229
+ "praesidium": "presidium",
1230
+ "praesidiums": "presidiums",
1231
+ "pressurisation": "pressurization",
1232
+ "pressurise": "pressurize",
1233
+ "pressurised": "pressurized",
1234
+ "pressurises": "pressurizes",
1235
+ "pressurising": "pressurizing",
1236
+ "pretence": "pretense",
1237
+ "pretences": "pretenses",
1238
+ "primaeval": "primeval",
1239
+ "prioritisation": "prioritization",
1240
+ "prioritise": "prioritize",
1241
+ "prioritised": "prioritized",
1242
+ "prioritises": "prioritizes",
1243
+ "prioritising": "prioritizing",
1244
+ "privatisation": "privatization",
1245
+ "privatisations": "privatizations",
1246
+ "privatise": "privatize",
1247
+ "privatised": "privatized",
1248
+ "privatises": "privatizes",
1249
+ "privatising": "privatizing",
1250
+ "professionalisation": "professionalization",
1251
+ "professionalise": "professionalize",
1252
+ "professionalised": "professionalized",
1253
+ "professionalises": "professionalizes",
1254
+ "professionalising": "professionalizing",
1255
+ "programme": "program",
1256
+ "programmes": "programs",
1257
+ "prologue": "prolog",
1258
+ "prologues": "prologs",
1259
+ "propagandise": "propagandize",
1260
+ "propagandised": "propagandized",
1261
+ "propagandises": "propagandizes",
1262
+ "propagandising": "propagandizing",
1263
+ "proselytise": "proselytize",
1264
+ "proselytised": "proselytized",
1265
+ "proselytiser": "proselytizer",
1266
+ "proselytisers": "proselytizers",
1267
+ "proselytises": "proselytizes",
1268
+ "proselytising": "proselytizing",
1269
+ "psychoanalyse": "psychoanalyze",
1270
+ "psychoanalysed": "psychoanalyzed",
1271
+ "psychoanalyses": "psychoanalyzes",
1272
+ "psychoanalysing": "psychoanalyzing",
1273
+ "publicise": "publicize",
1274
+ "publicised": "publicized",
1275
+ "publicises": "publicizes",
1276
+ "publicising": "publicizing",
1277
+ "pulverisation": "pulverization",
1278
+ "pulverise": "pulverize",
1279
+ "pulverised": "pulverized",
1280
+ "pulverises": "pulverizes",
1281
+ "pulverising": "pulverizing",
1282
+ "pummelled": "pummel",
1283
+ "pummelling": "pummeled",
1284
+ "pyjama": "pajama",
1285
+ "pyjamas": "pajamas",
1286
+ "pzazz": "pizzazz",
1287
+ "quarrelled": "quarreled",
1288
+ "quarrelling": "quarreling",
1289
+ "radicalise": "radicalize",
1290
+ "radicalised": "radicalized",
1291
+ "radicalises": "radicalizes",
1292
+ "radicalising": "radicalizing",
1293
+ "rancour": "rancor",
1294
+ "randomise": "randomize",
1295
+ "randomised": "randomized",
1296
+ "randomises": "randomizes",
1297
+ "randomising": "randomizing",
1298
+ "rationalisation": "rationalization",
1299
+ "rationalisations": "rationalizations",
1300
+ "rationalise": "rationalize",
1301
+ "rationalised": "rationalized",
1302
+ "rationalises": "rationalizes",
1303
+ "rationalising": "rationalizing",
1304
+ "ravelled": "raveled",
1305
+ "ravelling": "raveling",
1306
+ "realisable": "realizable",
1307
+ "realisation": "realization",
1308
+ "realisations": "realizations",
1309
+ "realise": "realize",
1310
+ "realised": "realized",
1311
+ "realises": "realizes",
1312
+ "realising": "realizing",
1313
+ "recognisable": "recognizable",
1314
+ "recognisably": "recognizably",
1315
+ "recognisance": "recognizance",
1316
+ "recognise": "recognize",
1317
+ "recognised": "recognized",
1318
+ "recognises": "recognizes",
1319
+ "recognising": "recognizing",
1320
+ "reconnoitre": "reconnoiter",
1321
+ "reconnoitred": "reconnoitered",
1322
+ "reconnoitres": "reconnoiters",
1323
+ "reconnoitring": "reconnoitering",
1324
+ "refuelled": "refueled",
1325
+ "refuelling": "refueling",
1326
+ "regularisation": "regularization",
1327
+ "regularise": "regularize",
1328
+ "regularised": "regularized",
1329
+ "regularises": "regularizes",
1330
+ "regularising": "regularizing",
1331
+ "remodelled": "remodeled",
1332
+ "remodelling": "remodeling",
1333
+ "remould": "remold",
1334
+ "remoulded": "remolded",
1335
+ "remoulding": "remolding",
1336
+ "remoulds": "remolds",
1337
+ "reorganisation": "reorganization",
1338
+ "reorganisations": "reorganizations",
1339
+ "reorganise": "reorganize",
1340
+ "reorganised": "reorganized",
1341
+ "reorganises": "reorganizes",
1342
+ "reorganising": "reorganizing",
1343
+ "revelled": "reveled",
1344
+ "reveller": "reveler",
1345
+ "revellers": "revelers",
1346
+ "revelling": "reveling",
1347
+ "revitalise": "revitalize",
1348
+ "revitalised": "revitalized",
1349
+ "revitalises": "revitalizes",
1350
+ "revitalising": "revitalizing",
1351
+ "revolutionise": "revolutionize",
1352
+ "revolutionised": "revolutionized",
1353
+ "revolutionises": "revolutionizes",
1354
+ "revolutionising": "revolutionizing",
1355
+ "rhapsodise": "rhapsodize",
1356
+ "rhapsodised": "rhapsodized",
1357
+ "rhapsodises": "rhapsodizes",
1358
+ "rhapsodising": "rhapsodizing",
1359
+ "rigour": "rigor",
1360
+ "rigours": "rigors",
1361
+ "ritualised": "ritualized",
1362
+ "rivalled": "rivaled",
1363
+ "rivalling": "rivaling",
1364
+ "romanticise": "romanticize",
1365
+ "romanticised": "romanticized",
1366
+ "romanticises": "romanticizes",
1367
+ "romanticising": "romanticizing",
1368
+ "rumour": "rumor",
1369
+ "rumoured": "rumored",
1370
+ "rumours": "rumors",
1371
+ "sabre": "saber",
1372
+ "sabres": "sabers",
1373
+ "saltpetre": "saltpeter",
1374
+ "sanitise": "sanitize",
1375
+ "sanitised": "sanitized",
1376
+ "sanitises": "sanitizes",
1377
+ "sanitising": "sanitizing",
1378
+ "satirise": "satirize",
1379
+ "satirised": "satirized",
1380
+ "satirises": "satirizes",
1381
+ "satirising": "satirizing",
1382
+ "saviour": "savior",
1383
+ "saviours": "saviors",
1384
+ "savour": "savor",
1385
+ "savoured": "savored",
1386
+ "savouries": "savories",
1387
+ "savouring": "savoring",
1388
+ "savours": "savors",
1389
+ "savoury": "savory",
1390
+ "scandalise": "scandalize",
1391
+ "scandalised": "scandalized",
1392
+ "scandalises": "scandalizes",
1393
+ "scandalising": "scandalizing",
1394
+ "sceptic": "skeptic",
1395
+ "sceptical": "skeptical",
1396
+ "sceptically": "skeptically",
1397
+ "scepticism": "skepticism",
1398
+ "sceptics": "skeptics",
1399
+ "sceptre": "scepter",
1400
+ "sceptres": "scepters",
1401
+ "scrutinise": "scrutinize",
1402
+ "scrutinised": "scrutinized",
1403
+ "scrutinises": "scrutinizes",
1404
+ "scrutinising": "scrutinizing",
1405
+ "secularisation": "secularization",
1406
+ "secularise": "secularize",
1407
+ "secularised": "secularized",
1408
+ "secularises": "secularizes",
1409
+ "secularising": "secularizing",
1410
+ "sensationalise": "sensationalize",
1411
+ "sensationalised": "sensationalized",
1412
+ "sensationalises": "sensationalizes",
1413
+ "sensationalising": "sensationalizing",
1414
+ "sensitise": "sensitize",
1415
+ "sensitised": "sensitized",
1416
+ "sensitises": "sensitizes",
1417
+ "sensitising": "sensitizing",
1418
+ "sentimentalise": "sentimentalize",
1419
+ "sentimentalised": "sentimentalized",
1420
+ "sentimentalises": "sentimentalizes",
1421
+ "sentimentalising": "sentimentalizing",
1422
+ "sepulchre": "sepulcher",
1423
+ "sepulchres": "sepulchers",
1424
+ "serialisation": "serialization",
1425
+ "serialisations": "serializations",
1426
+ "serialise": "serialize",
1427
+ "serialised": "serialized",
1428
+ "serialises": "serializes",
1429
+ "serialising": "serializing",
1430
+ "sermonise": "sermonize",
1431
+ "sermonised": "sermonized",
1432
+ "sermonises": "sermonizes",
1433
+ "sermonising": "sermonizing",
1434
+ "sheikh": "sheik",
1435
+ "shovelled": "shoveled",
1436
+ "shovelling": "shoveling",
1437
+ "shrivelled": "shriveled",
1438
+ "shrivelling": "shriveling",
1439
+ "signalise": "signalize",
1440
+ "signalised": "signalized",
1441
+ "signalises": "signalizes",
1442
+ "signalising": "signalizing",
1443
+ "signalled": "signaled",
1444
+ "signalling": "signaling",
1445
+ "smoulder": "smolder",
1446
+ "smouldered": "smoldered",
1447
+ "smouldering": "smoldering",
1448
+ "smoulders": "smolders",
1449
+ "snivelled": "sniveled",
1450
+ "snivelling": "sniveling",
1451
+ "snorkelled": "snorkeled",
1452
+ "snorkelling": "snorkeling",
1453
+ "snowplough": "snowplow",
1454
+ "snowploughs": "snowplow",
1455
+ "socialisation": "socialization",
1456
+ "socialise": "socialize",
1457
+ "socialised": "socialized",
1458
+ "socialises": "socializes",
1459
+ "socialising": "socializing",
1460
+ "sodomise": "sodomize",
1461
+ "sodomised": "sodomized",
1462
+ "sodomises": "sodomizes",
1463
+ "sodomising": "sodomizing",
1464
+ "solemnise": "solemnize",
1465
+ "solemnised": "solemnized",
1466
+ "solemnises": "solemnizes",
1467
+ "solemnising": "solemnizing",
1468
+ "sombre": "somber",
1469
+ "specialisation": "specialization",
1470
+ "specialisations": "specializations",
1471
+ "specialise": "specialize",
1472
+ "specialised": "specialized",
1473
+ "specialises": "specializes",
1474
+ "specialising": "specializing",
1475
+ "spectre": "specter",
1476
+ "spectres": "specters",
1477
+ "spiralled": "spiraled",
1478
+ "spiralling": "spiraling",
1479
+ "splendour": "splendor",
1480
+ "splendours": "splendors",
1481
+ "squirrelled": "squirreled",
1482
+ "squirrelling": "squirreling",
1483
+ "stabilisation": "stabilization",
1484
+ "stabilise": "stabilize",
1485
+ "stabilised": "stabilized",
1486
+ "stabiliser": "stabilizer",
1487
+ "stabilisers": "stabilizers",
1488
+ "stabilises": "stabilizes",
1489
+ "stabilising": "stabilizing",
1490
+ "standardisation": "standardization",
1491
+ "standardise": "standardize",
1492
+ "standardised": "standardized",
1493
+ "standardises": "standardizes",
1494
+ "standardising": "standardizing",
1495
+ "stencilled": "stenciled",
1496
+ "stencilling": "stenciling",
1497
+ "sterilisation": "sterilization",
1498
+ "sterilisations": "sterilizations",
1499
+ "sterilise": "sterilize",
1500
+ "sterilised": "sterilized",
1501
+ "steriliser": "sterilizer",
1502
+ "sterilisers": "sterilizers",
1503
+ "sterilises": "sterilizes",
1504
+ "sterilising": "sterilizing",
1505
+ "stigmatisation": "stigmatization",
1506
+ "stigmatise": "stigmatize",
1507
+ "stigmatised": "stigmatized",
1508
+ "stigmatises": "stigmatizes",
1509
+ "stigmatising": "stigmatizing",
1510
+ "storey": "story",
1511
+ "storeys": "stories",
1512
+ "subsidisation": "subsidization",
1513
+ "subsidise": "subsidize",
1514
+ "subsidised": "subsidized",
1515
+ "subsidiser": "subsidizer",
1516
+ "subsidisers": "subsidizers",
1517
+ "subsidises": "subsidizes",
1518
+ "subsidising": "subsidizing",
1519
+ "succour": "succor",
1520
+ "succoured": "succored",
1521
+ "succouring": "succoring",
1522
+ "succours": "succors",
1523
+ "sulphate": "sulfate",
1524
+ "sulphates": "sulfates",
1525
+ "sulphide": "sulfide",
1526
+ "sulphides": "sulfides",
1527
+ "sulphur": "sulfur",
1528
+ "sulphurous": "sulfurous",
1529
+ "summarise": "summarize",
1530
+ "summarised": "summarized",
1531
+ "summarises": "summarizes",
1532
+ "summarising": "summarizing",
1533
+ "swivelled": "swiveled",
1534
+ "swivelling": "swiveling",
1535
+ "symbolise": "symbolize",
1536
+ "symbolised": "symbolized",
1537
+ "symbolises": "symbolizes",
1538
+ "symbolising": "symbolizing",
1539
+ "sympathise": "sympathize",
1540
+ "sympathised": "sympathized",
1541
+ "sympathiser": "sympathizer",
1542
+ "sympathisers": "sympathizers",
1543
+ "sympathises": "sympathizes",
1544
+ "sympathising": "sympathizing",
1545
+ "synchronisation": "synchronization",
1546
+ "synchronise": "synchronize",
1547
+ "synchronised": "synchronized",
1548
+ "synchronises": "synchronizes",
1549
+ "synchronising": "synchronizing",
1550
+ "synthesise": "synthesize",
1551
+ "synthesised": "synthesized",
1552
+ "synthesiser": "synthesizer",
1553
+ "synthesisers": "synthesizers",
1554
+ "synthesises": "synthesizes",
1555
+ "synthesising": "synthesizing",
1556
+ "syphon": "siphon",
1557
+ "syphoned": "siphoned",
1558
+ "syphoning": "siphoning",
1559
+ "syphons": "siphons",
1560
+ "systematisation": "systematization",
1561
+ "systematise": "systematize",
1562
+ "systematised": "systematized",
1563
+ "systematises": "systematizes",
1564
+ "systematising": "systematizing",
1565
+ "tantalise": "tantalize",
1566
+ "tantalised": "tantalized",
1567
+ "tantalises": "tantalizes",
1568
+ "tantalising": "tantalizing",
1569
+ "tantalisingly": "tantalizingly",
1570
+ "tasselled": "tasseled",
1571
+ "technicolour": "technicolor",
1572
+ "temporise": "temporize",
1573
+ "temporised": "temporized",
1574
+ "temporises": "temporizes",
1575
+ "temporising": "temporizing",
1576
+ "tenderise": "tenderize",
1577
+ "tenderised": "tenderized",
1578
+ "tenderises": "tenderizes",
1579
+ "tenderising": "tenderizing",
1580
+ "terrorise": "terrorize",
1581
+ "terrorised": "terrorized",
1582
+ "terrorises": "terrorizes",
1583
+ "terrorising": "terrorizing",
1584
+ "theatre": "theater",
1585
+ "theatregoer": "theatergoer",
1586
+ "theatregoers": "theatergoers",
1587
+ "theatres": "theaters",
1588
+ "theorise": "theorize",
1589
+ "theorised": "theorized",
1590
+ "theorises": "theorizes",
1591
+ "theorising": "theorizing",
1592
+ "tonne": "ton",
1593
+ "tonnes": "tons",
1594
+ "towelled": "toweled",
1595
+ "towelling": "toweling",
1596
+ "toxaemia": "toxemia",
1597
+ "tranquillise": "tranquilize",
1598
+ "tranquillised": "tranquilized",
1599
+ "tranquilliser": "tranquilizer",
1600
+ "tranquillisers": "tranquilizers",
1601
+ "tranquillises": "tranquilizes",
1602
+ "tranquillising": "tranquilizing",
1603
+ "tranquillity": "tranquility",
1604
+ "tranquillize": "tranquilize",
1605
+ "tranquillized": "tranquilized",
1606
+ "tranquillizer": "tranquilizer",
1607
+ "tranquillizers": "tranquilizers",
1608
+ "tranquillizes": "tranquilizes",
1609
+ "tranquillizing": "tranquilizing",
1610
+ "tranquilly": "tranquility",
1611
+ "transistorised": "transistorized",
1612
+ "traumatise": "traumatize",
1613
+ "traumatised": "traumatized",
1614
+ "traumatises": "traumatizes",
1615
+ "traumatising": "traumatizing",
1616
+ "travelled": "traveled",
1617
+ "traveller": "traveler",
1618
+ "travellers": "travelers",
1619
+ "travelling": "traveling",
1620
+ "travelog": "travelogue",
1621
+ "travelogs": "travelogues",
1622
+ "trialled": "trialed",
1623
+ "trialling": "trialing",
1624
+ "tricolour": "tricolor",
1625
+ "tricolours": "tricolors",
1626
+ "trivialise": "trivialize",
1627
+ "trivialised": "trivialized",
1628
+ "trivialises": "trivializes",
1629
+ "trivialising": "trivializing",
1630
+ "tumour": "tumor",
1631
+ "tumours": "tumors",
1632
+ "tunnelled": "tunneled",
1633
+ "tunnelling": "tunneling",
1634
+ "tyrannise": "tyrannize",
1635
+ "tyrannised": "tyrannized",
1636
+ "tyrannises": "tyrannizes",
1637
+ "tyrannising": "tyrannizing",
1638
+ "tyre": "tire",
1639
+ "tyres": "tires",
1640
+ "unauthorised": "unauthorized",
1641
+ "uncivilised": "uncivilized",
1642
+ "underutilised": "underutilized",
1643
+ "unequalled": "unequaled",
1644
+ "unfavourable": "unfavorable",
1645
+ "unfavourably": "unfavorably",
1646
+ "unionisation": "unionization",
1647
+ "unionise": "unionize",
1648
+ "unionised": "unionized",
1649
+ "unionises": "unionizes",
1650
+ "unionising": "unionizing",
1651
+ "unorganised": "unorganized",
1652
+ "unravelled": "unraveled",
1653
+ "unravelling": "unraveling",
1654
+ "unrecognisable": "unrecognizable",
1655
+ "unrecognised": "unrecognized",
1656
+ "unrivalled": "unrivaled",
1657
+ "unsavoury": "unsavory",
1658
+ "untrammelled": "untrammeled",
1659
+ "urbanisation": "urbanization",
1660
+ "urbanise": "urbanize",
1661
+ "urbanised": "urbanized",
1662
+ "urbanises": "urbanizes",
1663
+ "urbanising": "urbanizing",
1664
+ "utilisable": "utilizable",
1665
+ "utilisation": "utilization",
1666
+ "utilise": "utilize",
1667
+ "utilised": "utilized",
1668
+ "utilises": "utilizes",
1669
+ "utilising": "utilizing",
1670
+ "valour": "valor",
1671
+ "vandalise": "vandalize",
1672
+ "vandalised": "vandalized",
1673
+ "vandalises": "vandalizes",
1674
+ "vandalising": "vandalizing",
1675
+ "vaporisation": "vaporization",
1676
+ "vaporise": "vaporize",
1677
+ "vaporised": "vaporized",
1678
+ "vaporises": "vaporizes",
1679
+ "vaporising": "vaporizing",
1680
+ "vapour": "vapor",
1681
+ "vapours": "vapors",
1682
+ "verbalise": "verbalize",
1683
+ "verbalised": "verbalized",
1684
+ "verbalises": "verbalizes",
1685
+ "verbalising": "verbalizing",
1686
+ "victimisation": "victimization",
1687
+ "victimise": "victimize",
1688
+ "victimised": "victimized",
1689
+ "victimises": "victimizes",
1690
+ "victimising": "victimizing",
1691
+ "videodisc": "videodisk",
1692
+ "videodiscs": "videodisks",
1693
+ "vigour": "vigor",
1694
+ "visualisation": "visualization",
1695
+ "visualisations": "visualizations",
1696
+ "visualise": "visualize",
1697
+ "visualised": "visualized",
1698
+ "visualises": "visualizes",
1699
+ "visualising": "visualizing",
1700
+ "vocalisation": "vocalization",
1701
+ "vocalisations": "vocalizations",
1702
+ "vocalise": "vocalize",
1703
+ "vocalised": "vocalized",
1704
+ "vocalises": "vocalizes",
1705
+ "vocalising": "vocalizing",
1706
+ "vulcanised": "vulcanized",
1707
+ "vulgarisation": "vulgarization",
1708
+ "vulgarise": "vulgarize",
1709
+ "vulgarised": "vulgarized",
1710
+ "vulgarises": "vulgarizes",
1711
+ "vulgarising": "vulgarizing",
1712
+ "waggon": "wagon",
1713
+ "waggons": "wagons",
1714
+ "watercolour": "watercolor",
1715
+ "watercolours": "watercolors",
1716
+ "weaselled": "weaseled",
1717
+ "weaselling": "weaseling",
1718
+ "westernisation": "westernization",
1719
+ "westernise": "westernize",
1720
+ "westernised": "westernized",
1721
+ "westernises": "westernizes",
1722
+ "westernising": "westernizing",
1723
+ "womanise": "womanize",
1724
+ "womanised": "womanized",
1725
+ "womaniser": "womanizer",
1726
+ "womanisers": "womanizers",
1727
+ "womanises": "womanizes",
1728
+ "womanising": "womanizing",
1729
+ "woollen": "woolen",
1730
+ "woollens": "woolens",
1731
+ "woollies": "woolies",
1732
+ "woolly": "wooly",
1733
+ "worshipped": "worshiped",
1734
+ "worshipper": "worshiper",
1735
+ "worshipping": "worshiping",
1736
+ "yodelled": "yodeled",
1737
+ "yodelling": "yodeling",
1738
+ "yoghourt": "yogurt",
1739
+ "yoghourts": "yogurts",
1740
+ "yoghurt": "yogurt",
1741
+ "yoghurts": "yogurts"
1742
+ }
preprocess_dataset.py ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datasets import load_dataset, DatasetDict
2
+ from transformers import WhisperFeatureExtractor
3
+ from transformers import WhisperTokenizer
4
+ from transformers import WhisperProcessor
5
+ from datasets import Audio
6
+ from transformers.models.whisper.english_normalizer import BasicTextNormalizer
7
+ from huggingface_hub import login
8
+
9
+ import argparse
10
+
11
+ my_parser = argparse.ArgumentParser()
12
+
13
+ my_parser.add_argument(
14
+ "--model_name",
15
+ "-model_name",
16
+ type=str,
17
+ action="store",
18
+ default="openai/whisper-tiny",
19
+ )
20
+ my_parser.add_argument("--hf_token", "-hf_token", type=str, action="store")
21
+ my_parser.add_argument(
22
+ "--dataset_name", "-dataset_name", type=str, action="store", default="google/fleurs"
23
+ )
24
+ my_parser.add_argument("--split", "-split", type=str, action="store", default="test")
25
+ my_parser.add_argument("--subset", "-subset", type=str, action="store")
26
+
27
+ args = my_parser.parse_args()
28
+
29
+ dataset_name = args.dataset_name
30
+ model_name = args.model_name
31
+ subset = args.subset
32
+ hf_token = args.hf_token
33
+ login(hf_token)
34
+ text_column = "sentence"
35
+ if dataset_name == "google/fleurs":
36
+ text_column = "transcription"
37
+
38
+ do_lower_case = False
39
+ do_remove_punctuation = False
40
+
41
+ normalizer = BasicTextNormalizer()
42
+ processor = WhisperProcessor.from_pretrained(
43
+ model_name, language="Arabic", task="transcribe"
44
+ )
45
+ dataset = load_dataset(dataset_name, subset, use_auth_token=True)
46
+
47
+ print(dataset)
48
+
49
+ feature_extractor = WhisperFeatureExtractor.from_pretrained(model_name)
50
+
51
+ tokenizer = WhisperTokenizer.from_pretrained(
52
+ model_name, language="Arabic", task="transcribe"
53
+ )
54
+ dataset = dataset.cast_column("audio", Audio(sampling_rate=16000))
55
+
56
+
57
+ def prepare_dataset(batch):
58
+ # load and (possibly) resample audio data to 16kHz
59
+ audio = batch["audio"]
60
+
61
+ # compute log-Mel input features from input audio array
62
+ batch["input_features"] = processor.feature_extractor(
63
+ audio["array"], sampling_rate=audio["sampling_rate"]
64
+ ).input_features[0]
65
+ # compute input length of audio sample in seconds
66
+ batch["input_length"] = len(audio["array"]) / audio["sampling_rate"]
67
+
68
+ # optional pre-processing steps
69
+ transcription = batch[text_column]
70
+ if do_lower_case:
71
+ transcription = transcription.lower()
72
+ if do_remove_punctuation:
73
+ transcription = normalizer(transcription).strip()
74
+
75
+ # encode target text to label ids
76
+ batch["labels"] = processor.tokenizer(transcription).input_ids
77
+ return batch
78
+
79
+
80
+ dataset = dataset.map(prepare_dataset, remove_columns=dataset.column_names["train"])
81
+
82
+ login(hf_token)
83
+ print(
84
+ f"pushing to arbml/{dataset_name.split('/')[-1]}_preprocessed_{model_name.split('/')[-1]}"
85
+ )
86
+ dataset.push_to_hub(
87
+ f"arbml/{dataset_name.split('/')[-1]}_preprocessed_{model_name.split('/')[-1]}",
88
+ private=True,
89
+ )
preprocessor_config.json ADDED
The diff for this file is too large to render. See raw diff
 
pytorch_model.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:741f78834421d6167313de767bbe172b6f5319506073dda3ff2255c81647ee73
3
+ size 967102601
requirements.txt ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ torch>=1.7
2
+ torchaudio
3
+ git+https://github.com/huggingface/transformers
4
+ git+https://github.com/huggingface/datasets
5
+ librosa
6
+ jiwer
7
+ evaluate>=0.3.0
8
+ more-itertools
9
+ tensorboard
10
+ bitsandbytes
11
+ sentencepiece
12
+ accelerate
13
+ deepspeed
14
+ pyarabic
requirements_colab.txt ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ torchaudio==0.11.0
2
+ git+https://github.com/huggingface/transformers
3
+ git+https://github.com/huggingface/datasets
4
+ librosa
5
+ jiwer
6
+ evaluate>=0.3.0
7
+ more-itertools
8
+ tensorboard
9
+ bitsandbytes
10
+ accelerate deepspeed
11
+ pyarabic
run.sh ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ python run_speech_recognition_seq2seq_streaming.py \
2
+ --model_name_or_path="openai/whisper-small" \
3
+ --dataset_name="mozilla-foundation/common_voice_11_0" \
4
+ --dataset_config_name="ar" \
5
+ --language="Arabic" \
6
+ --train_split_name="train+validation" \
7
+ --eval_split_name="test" \
8
+ --model_index_name="Whisper Small Arabic" \
9
+ --max_steps="5000" \
10
+ --output_dir="./" \
11
+ --per_device_train_batch_size="64" \
12
+ --per_device_eval_batch_size="32" \
13
+ --logging_steps="25" \
14
+ --learning_rate="1e-5" \
15
+ --warmup_steps="500" \
16
+ --evaluation_strategy="steps" \
17
+ --eval_steps="1000" \
18
+ --save_strategy="steps" \
19
+ --save_steps="1000" \
20
+ --generation_max_length="225" \
21
+ --length_column_name="input_length" \
22
+ --max_duration_in_seconds="30" \
23
+ --text_column_name="sentence" \
24
+ --freeze_feature_encoder="False" \
25
+ --report_to="tensorboard" \
26
+ --metric_for_best_model="wer" \
27
+ --greater_is_better="False" \
28
+ --load_best_model_at_end \
29
+ --gradient_checkpointing \
30
+ --fp16 \
31
+ --overwrite_output_dir \
32
+ --optim="adamw_bnb_8bit" \
33
+ --do_train \
34
+ --do_eval \
35
+ --predict_with_generate \
36
+ --do_normalize_eval \
37
+ --use_auth_token \
38
+ --push_to_hub
run_eval_cv_11.sh ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ python run_eval_whisper_streaming.py \
2
+ --dataset mozilla-foundation/common_voice_11_0 \
3
+ --model_id $1 \
4
+ --split test \
5
+ --config="ar" \
6
+ --batch_size="16" \
7
+ --remove_diacritics="True" \
8
+ --language="ar" \
9
+ --device 0 \
10
+ --streaming="False"
run_eval_fleurs.sh ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ python run_eval_whisper_streaming.py \
2
+ --dataset google/fleurs \
3
+ --model_id $1 \
4
+ --split test \
5
+ --config ar_eg \
6
+ --batch_size="16" \
7
+ --remove_diacritics="True" \
8
+ --language="ar" \
9
+ --device 0 \
10
+ --streaming="False"
run_eval_whisper_streaming.py ADDED
@@ -0,0 +1,166 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import pyarabic.araby as araby
3
+ from transformers import pipeline
4
+ from transformers.models.whisper.english_normalizer import BasicTextNormalizer
5
+ from datasets import load_dataset, Audio
6
+ import evaluate
7
+
8
+ wer_metric = evaluate.load("wer")
9
+
10
+
11
+ def is_target_text_in_range(ref):
12
+ if ref.strip() == "ignore time segment in scoring":
13
+ return False
14
+ else:
15
+ return ref.strip() != ""
16
+
17
+
18
+ def get_text(sample):
19
+ if "text" in sample:
20
+ return sample["text"]
21
+ elif "sentence" in sample:
22
+ return sample["sentence"]
23
+ elif "normalized_text" in sample:
24
+ return sample["normalized_text"]
25
+ elif "transcript" in sample:
26
+ return sample["transcript"]
27
+ elif "transcription" in sample:
28
+ return sample["transcription"]
29
+ else:
30
+ raise ValueError(
31
+ f"Expected transcript column of either 'text', 'sentence', 'normalized_text' or 'transcript'. Got sample of "
32
+ ".join{sample.keys()}. Ensure a text column name is present in the dataset."
33
+ )
34
+
35
+
36
+ whisper_norm = BasicTextNormalizer()
37
+
38
+
39
+ def normalise(batch):
40
+ batch["norm_text"] = whisper_norm(get_text(batch))
41
+ return batch
42
+
43
+
44
+ def remove_diacritics(batch):
45
+ batch["norm_text"] = araby.strip_diacritics(get_text(batch))
46
+ return batch
47
+
48
+
49
+ def data(dataset):
50
+ for i, item in enumerate(dataset):
51
+ yield {**item["audio"], "reference": item["norm_text"]}
52
+
53
+
54
+ def main(args):
55
+ batch_size = args.batch_size
56
+ whisper_asr = pipeline(
57
+ "automatic-speech-recognition", model=args.model_id, device=args.device
58
+ )
59
+
60
+ whisper_asr.model.config.forced_decoder_ids = (
61
+ whisper_asr.tokenizer.get_decoder_prompt_ids(
62
+ language=args.language, task="transcribe"
63
+ )
64
+ )
65
+
66
+ dataset = load_dataset(
67
+ args.dataset,
68
+ args.config,
69
+ split=args.split,
70
+ streaming=args.streaming,
71
+ use_auth_token=True,
72
+ )
73
+
74
+ # Only uncomment for debugging
75
+ dataset = dataset.take(args.max_eval_samples)
76
+
77
+ dataset = dataset.cast_column("audio", Audio(sampling_rate=16000))
78
+ dataset = dataset.map(normalise)
79
+ if args.remove_diacritics:
80
+ print("stripping diacritics")
81
+ dataset = dataset.map(remove_diacritics)
82
+ dataset = dataset.filter(is_target_text_in_range, input_columns=["norm_text"])
83
+
84
+ predictions = []
85
+ references = []
86
+
87
+ # run streamed inference
88
+ for out in whisper_asr(data(dataset), batch_size=batch_size):
89
+ predictions.append(whisper_norm(out["text"]))
90
+ references.append(out["reference"][0])
91
+
92
+ wer = wer_metric.compute(references=references, predictions=predictions)
93
+ wer = round(100 * wer, 2)
94
+
95
+ print("WER:", wer)
96
+
97
+
98
+ if __name__ == "__main__":
99
+ parser = argparse.ArgumentParser()
100
+
101
+ parser.add_argument(
102
+ "--model_id",
103
+ type=str,
104
+ required=True,
105
+ help="Model identifier. Should be loadable with 🤗 Transformers",
106
+ )
107
+ parser.add_argument(
108
+ "--dataset",
109
+ type=str,
110
+ default="mozilla-foundation/common_voice_11_0",
111
+ help="Dataset name to evaluate the `model_id`. Should be loadable with 🤗 Datasets",
112
+ )
113
+ parser.add_argument(
114
+ "--config",
115
+ type=str,
116
+ required=True,
117
+ help="Config of the dataset. *E.g.* `'en'` for the English split of Common Voice",
118
+ )
119
+ parser.add_argument(
120
+ "--split",
121
+ type=str,
122
+ default="test",
123
+ help="Split of the dataset. *E.g.* `'test'`",
124
+ )
125
+
126
+ parser.add_argument(
127
+ "--device",
128
+ type=int,
129
+ default=-1,
130
+ help="The device to run the pipeline on. -1 for CPU (default), 0 for the first GPU and so on.",
131
+ )
132
+ parser.add_argument(
133
+ "--batch_size",
134
+ type=int,
135
+ default=16,
136
+ help="Number of samples to go through each streamed batch.",
137
+ )
138
+ parser.add_argument(
139
+ "--max_eval_samples",
140
+ type=int,
141
+ default=None,
142
+ help="Number of samples to be evaluated. Put a lower number e.g. 64 for testing this script.",
143
+ )
144
+ parser.add_argument(
145
+ "--streaming",
146
+ type=bool,
147
+ default=True,
148
+ help="Choose whether you'd like to download the entire dataset or stream it during the evaluation.",
149
+ )
150
+ parser.add_argument(
151
+ "--language",
152
+ type=str,
153
+ required=True,
154
+ help="Two letter language code for the transcription language, e.g. use 'en' for English.",
155
+ )
156
+
157
+ parser.add_argument(
158
+ "--remove_diacritics",
159
+ type=bool,
160
+ default=False,
161
+ help="Choose whether you'd like remove_diacritics",
162
+ )
163
+
164
+ args = parser.parse_args()
165
+
166
+ main(args)
run_mgb2.sh ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ python run_speech_recognition_seq2seq_mixed_mgb2-cv1.py \
2
+ --model_name_or_path="openai/whisper-small" \
3
+ --dataset_name="arbml/mgb2_speech" \
4
+ --dataset_config_name="ar" \
5
+ --language="Arabic" \
6
+ --train_split_name="train" \
7
+ --eval_split_name="test" \
8
+ --model_index_name="Whisper Small Arabic" \
9
+ --max_steps="5000" \
10
+ --output_dir="./" \
11
+ --per_device_train_batch_size="64" \
12
+ --per_device_eval_batch_size="8" \
13
+ --logging_steps="25" \
14
+ --learning_rate="1e-5" \
15
+ --warmup_steps="500" \
16
+ --evaluation_strategy="steps" \
17
+ --eval_steps="1000" \
18
+ --save_strategy="steps" \
19
+ --save_steps="1000" \
20
+ --generation_max_length="225" \
21
+ --length_column_name="input_length" \
22
+ --max_duration_in_seconds="30" \
23
+ --text_column_name="sentence" \
24
+ --freeze_feature_encoder="False" \
25
+ --report_to="tensorboard" \
26
+ --metric_for_best_model="wer" \
27
+ --greater_is_better="False" \
28
+ --load_best_model_at_end \
29
+ --gradient_checkpointing \
30
+ --fp16 \
31
+ --overwrite_output_dir \
32
+ --optim="adamw_bnb_8bit" \
33
+ --do_train \
34
+ --do_eval \
35
+ --predict_with_generate \
36
+ --do_normalize_eval \
37
+ --use_auth_token \
38
+ --push_to_hub
run_mgb2_deepspeed.sh ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ deepspeed run_speech_recognition_seq2seq_mixed_mgb2.py \
2
+ --model_name_or_path="openai/whisper-small" \
3
+ --deepspeed="ds_config.json" \
4
+ --dataset_name="arbml/mgb2_speech" \
5
+ --dataset_config_name="ar" \
6
+ --language="Arabic" \
7
+ --train_split_name="train" \
8
+ --eval_split_name="test" \
9
+ --model_index_name="Whisper Small Arabic" \
10
+ --max_steps="5000" \
11
+ --output_dir="./" \
12
+ --per_device_train_batch_size="16" \
13
+ --per_device_eval_batch_size="8" \
14
+ --logging_steps="25" \
15
+ --learning_rate="1e-5" \
16
+ --warmup_steps="500" \
17
+ --evaluation_strategy="steps" \
18
+ --eval_steps="1000" \
19
+ --save_strategy="steps" \
20
+ --save_steps="1000" \
21
+ --generation_max_length="225" \
22
+ --length_column_name="input_length" \
23
+ --max_duration_in_seconds="30" \
24
+ --text_column_name="text" \
25
+ --freeze_feature_encoder="False" \
26
+ --report_to="tensorboard" \
27
+ --metric_for_best_model="wer" \
28
+ --greater_is_better="False" \
29
+ --load_best_model_at_end \
30
+ --gradient_checkpointing \
31
+ --fp16 \
32
+ --overwrite_output_dir \
33
+ --do_train \
34
+ --do_eval \
35
+ --predict_with_generate \
36
+ --do_normalize_eval \
37
+ --use_auth_token \
38
+ --push_to_hub
run_speech_recognition_seq2seq.py ADDED
@@ -0,0 +1,607 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # coding=utf-8
3
+ # Copyright 2022 The HuggingFace Team. All rights reserved.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ """
17
+ Fine-tuning the library models for sequence to sequence speech recognition.
18
+ """
19
+ # You can also adapt this script for your own sequence to sequence speech
20
+ # recognition task. Pointers for this are left as comments.
21
+
22
+ import logging
23
+ import os
24
+ import sys
25
+ from dataclasses import dataclass, field
26
+ from typing import Any, Dict, List, Optional, Union
27
+
28
+ import datasets
29
+ import torch
30
+ from datasets import IterableDatasetDict, interleave_datasets, load_dataset
31
+ from torch.utils.data import IterableDataset
32
+
33
+ import evaluate
34
+ import transformers
35
+ from transformers import (
36
+ AutoConfig,
37
+ AutoFeatureExtractor,
38
+ AutoModelForSpeechSeq2Seq,
39
+ AutoProcessor,
40
+ AutoTokenizer,
41
+ HfArgumentParser,
42
+ Seq2SeqTrainer,
43
+ Seq2SeqTrainingArguments,
44
+ TrainerCallback,
45
+ set_seed,
46
+ )
47
+ from transformers.trainer_pt_utils import IterableDatasetShard
48
+ from transformers.trainer_utils import get_last_checkpoint, is_main_process
49
+ from transformers.utils import check_min_version, send_example_telemetry
50
+ from transformers.utils.versions import require_version
51
+ from transformers.models.whisper.english_normalizer import BasicTextNormalizer
52
+ import os
53
+ os.environ['LD_LIBRARY_PATH'] = '/usr/lib/x86_64-linux-gnu'
54
+ # Will error if the minimal version of Transformers is not installed. Remove at your own risks.
55
+ check_min_version("4.25.0.dev0")
56
+
57
+ require_version("datasets>=1.18.2", "To fix: pip install -r examples/pytorch/speech-recognition/requirements.txt")
58
+
59
+ logger = logging.getLogger(__name__)
60
+
61
+
62
+ @dataclass
63
+ class ModelArguments:
64
+ """
65
+ Arguments pertaining to which model/config/tokenizer we are going to fine-tune from.
66
+ """
67
+
68
+ model_name_or_path: str = field(
69
+ metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"}
70
+ )
71
+ config_name: Optional[str] = field(
72
+ default=None, metadata={"help": "Pretrained config name or path if not the same as model_name"}
73
+ )
74
+ tokenizer_name: Optional[str] = field(
75
+ default=None, metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"}
76
+ )
77
+ feature_extractor_name: Optional[str] = field(
78
+ default=None, metadata={"help": "feature extractor name or path if not the same as model_name"}
79
+ )
80
+ cache_dir: Optional[str] = field(
81
+ default=None,
82
+ metadata={"help": "Where to store the pretrained models downloaded from huggingface.co"},
83
+ )
84
+ use_fast_tokenizer: bool = field(
85
+ default=True,
86
+ metadata={"help": "Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."},
87
+ )
88
+ model_revision: str = field(
89
+ default="main",
90
+ metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."},
91
+ )
92
+ use_auth_token: bool = field(
93
+ default=False,
94
+ metadata={
95
+ "help": (
96
+ "Will use the token generated when running `huggingface-cli login` (necessary to use this script "
97
+ "with private models)."
98
+ )
99
+ },
100
+ )
101
+ freeze_feature_encoder: bool = field(
102
+ default=True, metadata={"help": "Whether to freeze the feature encoder layers of the model."}
103
+ )
104
+ freeze_encoder: bool = field(
105
+ default=False, metadata={"help": "Whether to freeze the entire encoder of the seq2seq model."}
106
+ )
107
+ forced_decoder_ids: List[List[int]] = field(
108
+ default=None,
109
+ metadata={
110
+ "help": (
111
+ "A list of pairs of integers which indicates a mapping from generation indices to token indices "
112
+ "that will be forced before sampling. For example, [[0, 123]] means the first generated token "
113
+ "will always be a token of index 123."
114
+ )
115
+ },
116
+ )
117
+ suppress_tokens: List[int] = field(
118
+ default=None, metadata={"help": "A list of tokens that will be suppressed at generation."}
119
+ )
120
+ model_index_name: str = field(default=None, metadata={"help": "Pretty name for the model card."})
121
+
122
+
123
+ @dataclass
124
+ class DataTrainingArguments:
125
+ """
126
+ Arguments pertaining to what data we are going to input our model for training and eval.
127
+ """
128
+
129
+ dataset_name: str = field(
130
+ default=None, metadata={"help": "The name of the dataset to use (via the datasets library)."}
131
+ )
132
+ dataset_config_name: Optional[str] = field(
133
+ default=None, metadata={"help": "The configuration name of the dataset to use (via the datasets library)."}
134
+ )
135
+ text_column: Optional[str] = field(
136
+ default=None,
137
+ metadata={"help": "The name of the column in the datasets containing the full texts (for summarization)."},
138
+ )
139
+ max_train_samples: Optional[int] = field(
140
+ default=None,
141
+ metadata={
142
+ "help": (
143
+ "For debugging purposes or quicker training, truncate the number of training examples to this "
144
+ "value if set."
145
+ )
146
+ },
147
+ )
148
+ max_eval_samples: Optional[int] = field(
149
+ default=None,
150
+ metadata={
151
+ "help": (
152
+ "For debugging purposes or quicker training, truncate the number of evaluation examples to this "
153
+ "value if set."
154
+ )
155
+ },
156
+ )
157
+ audio_column_name: str = field(
158
+ default="audio",
159
+ metadata={"help": "The name of the dataset column containing the audio data. Defaults to 'audio'"},
160
+ )
161
+ text_column_name: str = field(
162
+ default="text",
163
+ metadata={"help": "The name of the dataset column containing the text data. Defaults to 'text'"},
164
+ )
165
+ max_duration_in_seconds: float = field(
166
+ default=20.0,
167
+ metadata={
168
+ "help": (
169
+ "Truncate audio files that are longer than `max_duration_in_seconds` seconds to"
170
+ " 'max_duration_in_seconds`"
171
+ )
172
+ },
173
+ )
174
+ min_duration_in_seconds: float = field(
175
+ default=0.0, metadata={"help": "Filter audio files that are shorter than `min_duration_in_seconds` seconds"}
176
+ )
177
+ train_split_name: str = field(
178
+ default="train",
179
+ metadata={
180
+ "help": "The name of the training data set split to use (via the datasets library). Defaults to 'train'"
181
+ },
182
+ )
183
+ eval_split_name: str = field(
184
+ default="test",
185
+ metadata={
186
+ "help": "The name of the training data set split to use (via the datasets library). Defaults to 'train'"
187
+ },
188
+ )
189
+ do_lower_case: bool = field(
190
+ default=False,
191
+ metadata={"help": "Whether the target text should be lower cased."},
192
+ )
193
+ do_remove_punctuation: bool = field(
194
+ default=False,
195
+ metadata={"help": "Whether the target text should be striped of punctuation."},
196
+ )
197
+ do_normalize_eval: bool = field(
198
+ default=True,
199
+ metadata={"help": "Whether to normalise the references and predictions in the eval WER calculation."},
200
+ )
201
+ language: str = field(
202
+ default=None,
203
+ metadata={
204
+ "help": (
205
+ "Language for multilingual fine-tuning. This argument should be set for multilingual fine-tuning "
206
+ "only. For English speech recognition, it should be set to `None`."
207
+ )
208
+ },
209
+ )
210
+ task: str = field(
211
+ default="transcribe",
212
+ metadata={"help": "Task, either `transcribe` for speech recognition or `translate` for speech translation."},
213
+ )
214
+ shuffle_buffer_size: Optional[int] = field(
215
+ default=500,
216
+ metadata={
217
+ "help": (
218
+ "The number of streamed examples to download before shuffling them. The large the buffer, "
219
+ "the closer it is to real offline shuffling."
220
+ )
221
+ },
222
+ )
223
+
224
+
225
+ @dataclass
226
+ class DataCollatorSpeechSeq2SeqWithPadding:
227
+ """
228
+ Data collator that will dynamically pad the inputs received.
229
+ Args:
230
+ processor ([`WhisperProcessor`])
231
+ The processor used for processing the data.
232
+ decoder_start_token_id (`int`)
233
+ The begin-of-sentence of the decoder.
234
+ """
235
+
236
+ processor: Any
237
+ decoder_start_token_id: int
238
+
239
+ def __call__(self, features: List[Dict[str, Union[List[int], torch.Tensor]]]) -> Dict[str, torch.Tensor]:
240
+ # split inputs and labels since they have to be of different lengths and need
241
+ # different padding methods
242
+ model_input_name = self.processor.model_input_names[0]
243
+ input_features = [{model_input_name: feature[model_input_name]} for feature in features]
244
+ label_features = [{"input_ids": feature["labels"]} for feature in features]
245
+
246
+ batch = self.processor.feature_extractor.pad(input_features, return_tensors="pt")
247
+
248
+ labels_batch = self.processor.tokenizer.pad(label_features, return_tensors="pt")
249
+
250
+ # replace padding with -100 to ignore loss correctly
251
+ labels = labels_batch["input_ids"].masked_fill(labels_batch.attention_mask.ne(1), -100)
252
+
253
+ # if bos token is appended in previous tokenization step,
254
+ # cut bos token here as it's append later anyways
255
+ if (labels[:, 0] == self.decoder_start_token_id).all().cpu().item():
256
+ labels = labels[:, 1:]
257
+
258
+ batch["labels"] = labels
259
+
260
+ return batch
261
+
262
+
263
+ def load_datasets(dataset_name, dataset_config_name, split="train", **kwargs):
264
+ """
265
+ Utility function to load a dataset in streaming mode. For datasets with multiple splits,
266
+ each split is loaded individually and then splits combined by taking alternating examples from
267
+ each (interleaving).
268
+ """
269
+ if "+" in split:
270
+ # load multiple splits separated by the `+` symbol with streaming mode
271
+ dataset_splits = [
272
+ load_dataset(dataset_name, dataset_config_name, split=split_name, **kwargs)
273
+ for split_name in split.split("+")
274
+ ]
275
+ # interleave multiple splits to form one dataset
276
+ interleaved_dataset = interleave_datasets(dataset_splits)
277
+ return interleaved_dataset
278
+ else:
279
+ # load a single split *with* streaming mode
280
+ dataset = load_dataset(dataset_name, dataset_config_name, split=split, **kwargs)
281
+ return dataset
282
+
283
+
284
+ def main():
285
+ # 1. Parse input arguments
286
+ # See all possible arguments in src/transformers/training_args.py
287
+ # or by passing the --help flag to this script.
288
+ # We now keep distinct sets of args, for a cleaner separation of concerns.
289
+ parser = HfArgumentParser((ModelArguments, DataTrainingArguments, Seq2SeqTrainingArguments))
290
+
291
+ if len(sys.argv) == 2 and sys.argv[1].endswith(".json"):
292
+ # If we pass only one argument to the script and it's the path to a json file,
293
+ # let's parse it to get our arguments.
294
+ model_args, data_args, training_args = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]))
295
+ else:
296
+ model_args, data_args, training_args = parser.parse_args_into_dataclasses()
297
+
298
+ # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
299
+ # information sent is the one passed as arguments along with your Python/PyTorch versions.
300
+ send_example_telemetry("run_speech_recognition_seq2seq", model_args, data_args)
301
+
302
+ # 2. Setup logging
303
+ logging.basicConfig(
304
+ format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
305
+ datefmt="%m/%d/%Y %H:%M:%S",
306
+ handlers=[logging.StreamHandler(sys.stdout)],
307
+ )
308
+ log_level = training_args.get_process_log_level()
309
+ logger.setLevel(log_level)
310
+ datasets.utils.logging.set_verbosity(log_level)
311
+ transformers.utils.logging.set_verbosity(log_level)
312
+ transformers.utils.logging.enable_default_handler()
313
+ transformers.utils.logging.enable_explicit_format()
314
+
315
+ logger.setLevel(logging.INFO if is_main_process(training_args.local_rank) else logging.WARN)
316
+
317
+ # Log on each process the small summary:
318
+ logger.warning(
319
+ f"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}"
320
+ f"distributed training: {bool(training_args.local_rank != -1)}, 16-bits training: {training_args.fp16}"
321
+ )
322
+ logger.info(f"Training/evaluation parameters {training_args}")
323
+
324
+ # Set the verbosity to info of the Transformers logger (on main process only):
325
+ if is_main_process(training_args.local_rank):
326
+ transformers.utils.logging.set_verbosity_info()
327
+ logger.info("Training/evaluation parameters %s", training_args)
328
+
329
+ # 3. Detecting last checkpoint and eventually continue from last checkpoint
330
+ last_checkpoint = None
331
+ if os.path.isdir(training_args.output_dir) and training_args.do_train and not training_args.overwrite_output_dir:
332
+ last_checkpoint = get_last_checkpoint(training_args.output_dir)
333
+ if last_checkpoint is None and len(os.listdir(training_args.output_dir)) > 0:
334
+ raise ValueError(
335
+ f"Output directory ({training_args.output_dir}) already exists and is not empty. "
336
+ "Use --overwrite_output_dir to overcome."
337
+ )
338
+ elif last_checkpoint is not None and training_args.resume_from_checkpoint is None:
339
+ logger.info(
340
+ f"Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change "
341
+ "the `--output_dir` or add `--overwrite_output_dir` to train from scratch."
342
+ )
343
+
344
+ # Set seed before initializing model.
345
+ set_seed(training_args.seed)
346
+
347
+ # 4. Load dataset
348
+ raw_datasets = IterableDatasetDict()
349
+
350
+ if training_args.do_train:
351
+ raw_datasets["train"] = load_datasets(
352
+ data_args.dataset_name,
353
+ data_args.dataset_config_name,
354
+ split=data_args.train_split_name,
355
+ use_auth_token=True if model_args.use_auth_token else None,
356
+ )
357
+
358
+ if training_args.do_eval:
359
+ raw_datasets["eval"] = load_datasets(
360
+ data_args.dataset_name,
361
+ data_args.dataset_config_name,
362
+ split=data_args.eval_split_name,
363
+ use_auth_token=True if model_args.use_auth_token else None,
364
+ )
365
+
366
+ raw_datasets_features = list(next(iter(raw_datasets.values())).features.keys())
367
+
368
+ if data_args.audio_column_name not in raw_datasets_features:
369
+ raise ValueError(
370
+ f"--audio_column_name '{data_args.audio_column_name}' not found in dataset '{data_args.dataset_name}'. "
371
+ "Make sure to set `--audio_column_name` to the correct audio column - one of "
372
+ f"{', '.join(raw_datasets_features)}."
373
+ )
374
+
375
+ if data_args.text_column_name not in raw_datasets_features:
376
+ raise ValueError(
377
+ f"--text_column_name {data_args.text_column_name} not found in dataset '{data_args.dataset_name}'. "
378
+ "Make sure to set `--text_column_name` to the correct text column - one of "
379
+ f"{', '.join(raw_datasets_features)}."
380
+ )
381
+
382
+ # 5. Load pretrained model, tokenizer, and feature extractor
383
+ #
384
+ # Distributed training:
385
+ # The .from_pretrained methods guarantee that only one local process can concurrently
386
+ config = AutoConfig.from_pretrained(
387
+ model_args.config_name if model_args.config_name else model_args.model_name_or_path,
388
+ cache_dir=model_args.cache_dir,
389
+ revision=model_args.model_revision,
390
+ use_auth_token=True if model_args.use_auth_token else None,
391
+ )
392
+
393
+ config.update({"forced_decoder_ids": model_args.forced_decoder_ids, "suppress_tokens": model_args.suppress_tokens})
394
+
395
+ feature_extractor = AutoFeatureExtractor.from_pretrained(
396
+ model_args.feature_extractor_name if model_args.feature_extractor_name else model_args.model_name_or_path,
397
+ cache_dir=model_args.cache_dir,
398
+ revision=model_args.model_revision,
399
+ use_auth_token=True if model_args.use_auth_token else None,
400
+ )
401
+ tokenizer = AutoTokenizer.from_pretrained(
402
+ model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path,
403
+ cache_dir=model_args.cache_dir,
404
+ use_fast=model_args.use_fast_tokenizer,
405
+ revision=model_args.model_revision,
406
+ use_auth_token=True if model_args.use_auth_token else None,
407
+ )
408
+ model = AutoModelForSpeechSeq2Seq.from_pretrained(
409
+ model_args.model_name_or_path,
410
+ config=config,
411
+ cache_dir=model_args.cache_dir,
412
+ revision=model_args.model_revision,
413
+ use_auth_token=True if model_args.use_auth_token else None,
414
+ )
415
+ model.config.use_cache = False
416
+
417
+ if model.config.decoder_start_token_id is None:
418
+ raise ValueError("Make sure that `config.decoder_start_token_id` is correctly defined")
419
+
420
+ if model_args.freeze_feature_encoder:
421
+ model.freeze_feature_encoder()
422
+
423
+ if model_args.freeze_encoder:
424
+ model.freeze_encoder()
425
+ model.model.encoder.gradient_checkpointing = False
426
+
427
+ if data_args.language is not None:
428
+ # We only need to set the task id when the language is specified (i.e. in a multilingual setting)
429
+ tokenizer.set_prefix_tokens(language=data_args.language, task=data_args.task)
430
+
431
+ # 6. Resample speech dataset if necessary
432
+ dataset_sampling_rate = next(iter(raw_datasets.values())).features[data_args.audio_column_name].sampling_rate
433
+ if dataset_sampling_rate != feature_extractor.sampling_rate:
434
+ raw_datasets = raw_datasets.cast_column(
435
+ data_args.audio_column_name, datasets.features.Audio(sampling_rate=feature_extractor.sampling_rate)
436
+ )
437
+
438
+ # 7. Preprocessing the datasets.
439
+ # We need to read the audio files as arrays and tokenize the targets.
440
+ max_input_length = data_args.max_duration_in_seconds * feature_extractor.sampling_rate
441
+ min_input_length = data_args.min_duration_in_seconds * feature_extractor.sampling_rate
442
+ audio_column_name = data_args.audio_column_name
443
+ text_column_name = data_args.text_column_name
444
+ model_input_name = feature_extractor.model_input_names[0]
445
+ do_lower_case = data_args.do_lower_case
446
+ do_remove_punctuation = data_args.do_remove_punctuation
447
+ normalizer = BasicTextNormalizer() # 'official' text normalizer from OpenAI
448
+
449
+ if data_args.max_train_samples is not None:
450
+ raw_datasets["train"] = raw_datasets["train"].select(range(data_args.max_train_samples))
451
+
452
+ if data_args.max_eval_samples is not None:
453
+ raw_datasets["eval"] = raw_datasets["eval"].select(range(data_args.max_eval_samples))
454
+
455
+ def prepare_dataset(batch):
456
+ # process audio
457
+ sample = batch[audio_column_name]
458
+ inputs = feature_extractor(sample["array"], sampling_rate=sample["sampling_rate"])
459
+ # process audio length
460
+ batch[model_input_name] = inputs.get(model_input_name)[0]
461
+ batch["input_length"] = len(sample["array"])
462
+
463
+ # process targets
464
+ input_str = batch[text_column_name].lower() if do_lower_case else batch[text_column_name]
465
+ if do_remove_punctuation:
466
+ input_str = normalizer(input_str).strip()
467
+ batch["labels"] = tokenizer(input_str).input_ids
468
+ return batch
469
+
470
+ with training_args.main_process_first(desc="dataset map pre-processing"):
471
+ vectorized_datasets = raw_datasets.map(
472
+ prepare_dataset,
473
+ remove_columns=raw_datasets_features,
474
+ ).with_format("torch")
475
+
476
+ if training_args.do_train:
477
+ vectorized_datasets["train"] = vectorized_datasets["train"].shuffle(
478
+ # buffer_size=data_args.shuffle_buffer_size,
479
+ seed=training_args.seed,
480
+ )
481
+
482
+ # filter training data that is shorter than min_input_length or longer than
483
+ # max_input_length
484
+ def is_audio_in_length_range(length):
485
+ return min_input_length < length < max_input_length
486
+
487
+ vectorized_datasets["train"] = vectorized_datasets["train"].filter(
488
+ is_audio_in_length_range,
489
+ input_columns=["input_length"],
490
+ )
491
+
492
+ # 8. Load Metric
493
+ metric = evaluate.load("wer")
494
+ do_normalize_eval = data_args.do_normalize_eval
495
+
496
+ def compute_metrics(pred):
497
+ pred_ids = pred.predictions
498
+
499
+ pred.label_ids[pred.label_ids == -100] = tokenizer.pad_token_id
500
+
501
+ pred_str = tokenizer.batch_decode(pred_ids, skip_special_tokens=True)
502
+ # we do not want to group tokens when computing the metrics
503
+ label_str = tokenizer.batch_decode(pred.label_ids, skip_special_tokens=True)
504
+
505
+ if do_normalize_eval:
506
+ pred_str = [normalizer(pred) for pred in pred_str]
507
+ label_str = [normalizer(label) for label in label_str]
508
+
509
+ wer = 100 * metric.compute(predictions=pred_str, references=label_str)
510
+
511
+ return {"wer": wer}
512
+
513
+ # 9. Create a single speech processor
514
+ if is_main_process(training_args.local_rank):
515
+ # save feature extractor, tokenizer and config
516
+ feature_extractor.save_pretrained(training_args.output_dir)
517
+ tokenizer.save_pretrained(training_args.output_dir)
518
+ config.save_pretrained(training_args.output_dir)
519
+
520
+ processor = AutoProcessor.from_pretrained(training_args.output_dir)
521
+
522
+ # 10. Define data collator
523
+ data_collator = DataCollatorSpeechSeq2SeqWithPadding(
524
+ processor=processor,
525
+ decoder_start_token_id=model.config.decoder_start_token_id,
526
+ )
527
+
528
+ # 11. Configure Trainer
529
+ # Trainer callback to reinitialise and reshuffle the streamable datasets at the beginning of each epoch
530
+ class ShuffleCallback(TrainerCallback):
531
+ def on_epoch_begin(self, args, state, control, train_dataloader, **kwargs):
532
+ if isinstance(train_dataloader.dataset, IterableDatasetShard):
533
+ pass # set_epoch() is handled by the Trainer
534
+ elif isinstance(train_dataloader.dataset, IterableDataset):
535
+ train_dataloader.dataset.set_epoch(train_dataloader.dataset._epoch + 1)
536
+
537
+ # Initialize Trainer
538
+ trainer = Seq2SeqTrainer(
539
+ model=model,
540
+ args=training_args,
541
+ train_dataset=vectorized_datasets["train"] if training_args.do_train else None,
542
+ eval_dataset=vectorized_datasets["eval"] if training_args.do_eval else None,
543
+ tokenizer=feature_extractor,
544
+ data_collator=data_collator,
545
+ compute_metrics=compute_metrics if training_args.predict_with_generate else None,
546
+ callbacks=[ShuffleCallback()],
547
+ )
548
+
549
+ # 12. Training
550
+ if training_args.do_train:
551
+ checkpoint = None
552
+ if training_args.resume_from_checkpoint is not None:
553
+ checkpoint = training_args.resume_from_checkpoint
554
+ elif last_checkpoint is not None:
555
+ checkpoint = last_checkpoint
556
+ train_result = trainer.train(resume_from_checkpoint=checkpoint)
557
+ trainer.save_model() # Saves the feature extractor too for easy upload
558
+
559
+ metrics = train_result.metrics
560
+ if data_args.max_train_samples:
561
+ metrics["train_samples"] = data_args.max_train_samples
562
+ trainer.log_metrics("train", metrics)
563
+ trainer.save_metrics("train", metrics)
564
+ trainer.save_state()
565
+
566
+ # 13. Evaluation
567
+ results = {}
568
+ if training_args.do_eval:
569
+ logger.info("*** Evaluate ***")
570
+ metrics = trainer.evaluate(
571
+ metric_key_prefix="eval",
572
+ max_length=training_args.generation_max_length,
573
+ num_beams=training_args.generation_num_beams,
574
+ )
575
+ if data_args.max_eval_samples:
576
+ metrics["eval_samples"] = data_args.max_eval_samples
577
+
578
+ trainer.log_metrics("eval", metrics)
579
+ trainer.save_metrics("eval", metrics)
580
+
581
+ # 14. Write Training Stats
582
+ kwargs = {
583
+ "finetuned_from": model_args.model_name_or_path,
584
+ "tasks": "automatic-speech-recognition",
585
+ "tags": "whisper-event",
586
+ }
587
+ if data_args.dataset_name is not None:
588
+ kwargs["dataset_tags"] = data_args.dataset_name
589
+ if data_args.dataset_config_name is not None:
590
+ kwargs["dataset"] = f"{data_args.dataset_name} {data_args.dataset_config_name}"
591
+ else:
592
+ kwargs["dataset"] = data_args.dataset_name
593
+ if "common_voice" in data_args.dataset_name:
594
+ kwargs["language"] = data_args.dataset_config_name
595
+ if model_args.model_index_name is not None:
596
+ kwargs["model_name"] = model_args.model_index_name
597
+
598
+ if training_args.push_to_hub:
599
+ trainer.push_to_hub(**kwargs)
600
+ else:
601
+ trainer.create_model_card(**kwargs)
602
+
603
+ return results
604
+
605
+
606
+ if __name__ == "__main__":
607
+ main()
run_speech_recognition_seq2seq_mixed_mgb2-cv1.py ADDED
@@ -0,0 +1,802 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # coding=utf-8
3
+ # Copyright 2022 The HuggingFace Team. All rights reserved.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ """
17
+ Fine-tuning the library models for sequence to sequence speech recognition
18
+ with 🤗 Datasets' streaming mode.
19
+ """
20
+ # You can also adapt this script for your own sequence to sequence speech
21
+ # recognition task. Pointers for this are left as comments.
22
+
23
+ import logging
24
+ import os
25
+ import sys
26
+ from dataclasses import dataclass, field
27
+ from typing import Any, Dict, List, Optional, Union
28
+
29
+ import datasets
30
+ import torch
31
+ from datasets import DatasetDict, IterableDatasetDict, interleave_datasets, load_dataset
32
+ from datasets import Audio, interleave_datasets, IterableDataset
33
+ from torch.utils.data import IterableDataset
34
+
35
+ import evaluate
36
+ import transformers
37
+ from transformers import (
38
+ AutoConfig,
39
+ AutoFeatureExtractor,
40
+ AutoModelForSpeechSeq2Seq,
41
+ AutoProcessor,
42
+ AutoTokenizer,
43
+ HfArgumentParser,
44
+ Seq2SeqTrainer,
45
+ Seq2SeqTrainingArguments,
46
+ TrainerCallback,
47
+ set_seed,
48
+ )
49
+ from transformers.models.whisper.english_normalizer import BasicTextNormalizer
50
+ from transformers.trainer_pt_utils import IterableDatasetShard
51
+ from transformers.trainer_utils import get_last_checkpoint, is_main_process
52
+ from transformers.utils import check_min_version, send_example_telemetry
53
+ from transformers.utils.versions import require_version
54
+
55
+
56
+ # Will error if the minimal version of Transformers is not installed. Remove at your own risks.
57
+ check_min_version("4.25.0.dev0")
58
+
59
+ require_version(
60
+ "datasets>=1.18.2",
61
+ "To fix: pip install -r examples/pytorch/speech-recognition/requirements.txt",
62
+ )
63
+
64
+ logger = logging.getLogger(__name__)
65
+
66
+
67
+ @dataclass
68
+ class ModelArguments:
69
+ """
70
+ Arguments pertaining to which model/config/tokenizer we are going to fine-tune from.
71
+ """
72
+
73
+ model_name_or_path: str = field(
74
+ metadata={
75
+ "help": "Path to pretrained model or model identifier from huggingface.co/models"
76
+ }
77
+ )
78
+ config_name: Optional[str] = field(
79
+ default=None,
80
+ metadata={
81
+ "help": "Pretrained config name or path if not the same as model_name"
82
+ },
83
+ )
84
+ tokenizer_name: Optional[str] = field(
85
+ default=None,
86
+ metadata={
87
+ "help": "Pretrained tokenizer name or path if not the same as model_name"
88
+ },
89
+ )
90
+ feature_extractor_name: Optional[str] = field(
91
+ default=None,
92
+ metadata={
93
+ "help": "feature extractor name or path if not the same as model_name"
94
+ },
95
+ )
96
+ cache_dir: Optional[str] = field(
97
+ default=None,
98
+ metadata={
99
+ "help": "Where to store the pretrained models downloaded from huggingface.co"
100
+ },
101
+ )
102
+ use_fast_tokenizer: bool = field(
103
+ default=True,
104
+ metadata={
105
+ "help": "Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."
106
+ },
107
+ )
108
+ model_revision: str = field(
109
+ default="main",
110
+ metadata={
111
+ "help": "The specific model version to use (can be a branch name, tag name or commit id)."
112
+ },
113
+ )
114
+ use_auth_token: bool = field(
115
+ default=False,
116
+ metadata={
117
+ "help": (
118
+ "Will use the token generated when running `huggingface-cli login` (necessary to use this script "
119
+ "with private models)."
120
+ )
121
+ },
122
+ )
123
+ freeze_feature_encoder: bool = field(
124
+ default=True,
125
+ metadata={"help": "Whether to freeze the feature encoder layers of the model."},
126
+ )
127
+ freeze_encoder: bool = field(
128
+ default=False,
129
+ metadata={"help": "Whether to freeze the entire encoder of the seq2seq model."},
130
+ )
131
+ forced_decoder_ids: List[List[int]] = field(
132
+ default=None,
133
+ metadata={
134
+ "help": (
135
+ "A list of pairs of integers which indicates a mapping from generation indices to token indices "
136
+ "that will be forced before sampling. For example, [[0, 123]] means the first generated token "
137
+ "will always be a token of index 123."
138
+ )
139
+ },
140
+ )
141
+ suppress_tokens: List[int] = field(
142
+ default=None,
143
+ metadata={"help": "A list of tokens that will be suppressed at generation."},
144
+ )
145
+ model_index_name: str = field(
146
+ default=None, metadata={"help": "Pretty name for the model card."}
147
+ )
148
+
149
+
150
+ @dataclass
151
+ class DataTrainingArguments:
152
+ """
153
+ Arguments pertaining to what data we are going to input our model for training and eval.
154
+ """
155
+
156
+ dataset_name: str = field(
157
+ default=None,
158
+ metadata={"help": "The name of the dataset to use (via the datasets library)."},
159
+ )
160
+ dataset_config_name: Optional[str] = field(
161
+ default=None,
162
+ metadata={
163
+ "help": "The configuration name of the dataset to use (via the datasets library)."
164
+ },
165
+ )
166
+ text_column: Optional[str] = field(
167
+ default=None,
168
+ metadata={
169
+ "help": "The name of the column in the datasets containing the full texts (for summarization)."
170
+ },
171
+ )
172
+ max_train_samples: Optional[int] = field(
173
+ default=None,
174
+ metadata={
175
+ "help": (
176
+ "For debugging purposes or quicker training, truncate the number of training examples to this "
177
+ "value if set."
178
+ )
179
+ },
180
+ )
181
+ max_eval_samples: Optional[int] = field(
182
+ default=None,
183
+ metadata={
184
+ "help": (
185
+ "For debugging purposes or quicker training, truncate the number of evaluation examples to this "
186
+ "value if set."
187
+ )
188
+ },
189
+ )
190
+ audio_column_name: str = field(
191
+ default="audio",
192
+ metadata={
193
+ "help": "The name of the dataset column containing the audio data. Defaults to 'audio'"
194
+ },
195
+ )
196
+ text_column_name: str = field(
197
+ default="text",
198
+ metadata={
199
+ "help": "The name of the dataset column containing the text data. Defaults to 'text'"
200
+ },
201
+ )
202
+ max_duration_in_seconds: float = field(
203
+ default=20.0,
204
+ metadata={
205
+ "help": (
206
+ "Truncate audio files that are longer than `max_duration_in_seconds` seconds to"
207
+ " 'max_duration_in_seconds`"
208
+ )
209
+ },
210
+ )
211
+ min_duration_in_seconds: float = field(
212
+ default=0.0,
213
+ metadata={
214
+ "help": "Filter audio files that are shorter than `min_duration_in_seconds` seconds"
215
+ },
216
+ )
217
+ train_split_name: str = field(
218
+ default="train",
219
+ metadata={
220
+ "help": "The name of the training data set split to use (via the datasets library). Defaults to 'train'"
221
+ },
222
+ )
223
+ eval_split_name: str = field(
224
+ default="test",
225
+ metadata={
226
+ "help": "The name of the training data set split to use (via the datasets library). Defaults to 'train'"
227
+ },
228
+ )
229
+ do_lower_case: bool = field(
230
+ default=False,
231
+ metadata={"help": "Whether the target text should be lower cased."},
232
+ )
233
+ do_remove_punctuation: bool = field(
234
+ default=False,
235
+ metadata={"help": "Whether the target text should be striped of punctuation."},
236
+ )
237
+ do_normalize_eval: bool = field(
238
+ default=True,
239
+ metadata={
240
+ "help": "Whether to normalise the references and predictions in the eval WER calculation."
241
+ },
242
+ )
243
+ language: str = field(
244
+ default=None,
245
+ metadata={
246
+ "help": (
247
+ "Language for multilingual fine-tuning. This argument should be set for multilingual fine-tuning "
248
+ "only. For English speech recognition, it should be set to `None`."
249
+ )
250
+ },
251
+ )
252
+ task: str = field(
253
+ default="transcribe",
254
+ metadata={
255
+ "help": "Task, either `transcribe` for speech recognition or `translate` for speech translation."
256
+ },
257
+ )
258
+ shuffle_buffer_size: Optional[int] = field(
259
+ default=500,
260
+ metadata={
261
+ "help": (
262
+ "The number of streamed examples to download before shuffling them. The large the buffer, "
263
+ "the closer it is to real offline shuffling."
264
+ )
265
+ },
266
+ )
267
+ streaming: bool = field(
268
+ default=True,
269
+ metadata={
270
+ "help": "Whether to use streaming mode to load and pre-process the data."
271
+ },
272
+ )
273
+
274
+
275
+ @dataclass
276
+ class DataCollatorSpeechSeq2SeqWithPadding:
277
+ """
278
+ Data collator that will dynamically pad the inputs received.
279
+ Args:
280
+ processor ([`WhisperProcessor`])
281
+ The processor used for processing the data.
282
+ decoder_start_token_id (`int`)
283
+ The begin-of-sentence of the decoder.
284
+ """
285
+
286
+ processor: Any
287
+ decoder_start_token_id: int
288
+
289
+ def __call__(
290
+ self, features: List[Dict[str, Union[List[int], torch.Tensor]]]
291
+ ) -> Dict[str, torch.Tensor]:
292
+ # split inputs and labels since they have to be of different lengths and need
293
+ # different padding methods
294
+ model_input_name = self.processor.model_input_names[0]
295
+ input_features = [
296
+ {model_input_name: feature[model_input_name]} for feature in features
297
+ ]
298
+ label_features = [{"input_ids": feature["labels"]} for feature in features]
299
+
300
+ batch = self.processor.feature_extractor.pad(
301
+ input_features, return_tensors="pt"
302
+ )
303
+
304
+ labels_batch = self.processor.tokenizer.pad(label_features, return_tensors="pt")
305
+
306
+ # replace padding with -100 to ignore loss correctly
307
+ labels = labels_batch["input_ids"].masked_fill(
308
+ labels_batch.attention_mask.ne(1), -100
309
+ )
310
+
311
+ # if bos token is appended in previous tokenization step,
312
+ # cut bos token here as it's append later anyways
313
+ if (labels[:, 0] == self.decoder_start_token_id).all().cpu().item():
314
+ labels = labels[:, 1:]
315
+
316
+ batch["labels"] = labels
317
+
318
+ return batch
319
+
320
+
321
+ def load_maybe_streaming_dataset(
322
+ dataset_name, dataset_config_name, split="train", streaming=True, **kwargs
323
+ ):
324
+ """
325
+ Utility function to load a dataset in streaming mode. For datasets with multiple splits,
326
+ each split is loaded individually and then splits combined by taking alternating examples from
327
+ each (interleaving).
328
+ """
329
+ if "+" in split:
330
+ # load multiple splits separated by the `+` symbol with streaming mode
331
+ dataset_splits = [
332
+ load_dataset(
333
+ dataset_name,
334
+ dataset_config_name,
335
+ split=split_name,
336
+ streaming=streaming,
337
+ **kwargs,
338
+ )
339
+ for split_name in split.split("+")
340
+ ]
341
+ # interleave multiple splits to form one dataset
342
+ interleaved_dataset = interleave_datasets(dataset_splits)
343
+ return interleaved_dataset
344
+ else:
345
+ # load a single split *with* streaming mode
346
+ dataset = load_dataset(
347
+ dataset_name,
348
+ dataset_config_name,
349
+ split=split,
350
+ streaming=streaming,
351
+ **kwargs,
352
+ )
353
+ return dataset
354
+
355
+ def load_multiple_streaming_datasets(
356
+ dataset_names: List,
357
+ dataset_config_names: List,
358
+ splits: Optional[List] = None,
359
+ text_column_names: Optional[List] = None,
360
+ sampling_rate: Optional[int] = 16000,
361
+ stopping_strategy: Optional[str] = "first_exhausted",
362
+ **kwargs
363
+ ) -> IterableDataset:
364
+
365
+ if len(dataset_names) != len(dataset_config_names):
366
+ raise ValueError(
367
+ f"Ensure one config is passed for each dataset, got {len(dataset_names)} datasets and"
368
+ f" {len(dataset_config_names)} configs."
369
+ )
370
+
371
+ if splits is not None and len(splits) != len(dataset_names):
372
+ raise ValueError(
373
+ f"Ensure one split is passed for each dataset, got {len(dataset_names)} datasets and {len(splits)} splits."
374
+ )
375
+
376
+ if text_column_names is not None and len(text_column_names) != len(dataset_names):
377
+ raise ValueError(
378
+ f"Ensure one text column name is passed for each dataset, got {len(dataset_names)} datasets and"
379
+ f" {len(text_column_names)} text column names."
380
+ )
381
+
382
+ splits = splits if splits is not None else ["train" for i in range(len(dataset_names))]
383
+ text_column_names = (
384
+ text_column_names if text_column_names is not None else ["text" for i in range(len(dataset_names))]
385
+ )
386
+
387
+ all_datasets = []
388
+ # iterate over the datasets we want to interleave
389
+ for i, dataset_name in enumerate(dataset_names):
390
+ dataset = load_dataset(dataset_name, dataset_config_names[i], split=splits[i], streaming=True, **kwargs)
391
+ print(dataset)
392
+ # resample to specified sampling rate
393
+ dataset = dataset.cast_column("audio", Audio(sampling_rate))
394
+ # normalise columns to ["audio", "sentence"]
395
+ if text_column_names[i] != "sentence":
396
+ dataset = dataset.rename_column(text_column_names[i], "sentence")
397
+ dataset = dataset.remove_columns(set(dataset.features.keys()) - set(["audio", "sentence"]))
398
+ all_datasets.append(dataset)
399
+ print("DATASET:",dataset.features.keys())
400
+ interleaved_dataset = interleave_datasets(all_datasets, stopping_strategy=stopping_strategy)
401
+ return interleaved_dataset
402
+
403
+
404
+ def main():
405
+ # 1. Parse input arguments
406
+ # See all possible arguments in src/transformers/training_args.py
407
+ # or by passing the --help flag to this script.
408
+ # We now keep distinct sets of args, for a cleaner separation of concerns.
409
+ parser = HfArgumentParser(
410
+ (ModelArguments, DataTrainingArguments, Seq2SeqTrainingArguments)
411
+ )
412
+
413
+ if len(sys.argv) == 2 and sys.argv[1].endswith(".json"):
414
+ # If we pass only one argument to the script and it's the path to a json file,
415
+ # let's parse it to get our arguments.
416
+ model_args, data_args, training_args = parser.parse_json_file(
417
+ json_file=os.path.abspath(sys.argv[1])
418
+ )
419
+ else:
420
+ model_args, data_args, training_args = parser.parse_args_into_dataclasses()
421
+
422
+ # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
423
+ # information sent is the one passed as arguments along with your Python/PyTorch versions.
424
+ send_example_telemetry(
425
+ "run_speech_recognition_seq2seq_streaming", model_args, data_args
426
+ )
427
+
428
+ # 2. Setup logging
429
+ logging.basicConfig(
430
+ format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
431
+ datefmt="%m/%d/%Y %H:%M:%S",
432
+ handlers=[logging.StreamHandler(sys.stdout)],
433
+ )
434
+ log_level = training_args.get_process_log_level()
435
+ logger.setLevel(log_level)
436
+ datasets.utils.logging.set_verbosity(log_level)
437
+ transformers.utils.logging.set_verbosity(log_level)
438
+ transformers.utils.logging.enable_default_handler()
439
+ transformers.utils.logging.enable_explicit_format()
440
+
441
+ logger.setLevel(
442
+ logging.INFO if is_main_process(training_args.local_rank) else logging.WARN
443
+ )
444
+
445
+ # Log on each process the small summary:
446
+ logger.warning(
447
+ f"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}"
448
+ f"distributed training: {bool(training_args.local_rank != -1)}, 16-bits training: {training_args.fp16}"
449
+ )
450
+ logger.info(f"Training/evaluation parameters {training_args}")
451
+
452
+ # Set the verbosity to info of the Transformers logger (on main process only):
453
+ if is_main_process(training_args.local_rank):
454
+ transformers.utils.logging.set_verbosity_info()
455
+ logger.info("Training/evaluation parameters %s", training_args)
456
+
457
+ # 3. Detecting last checkpoint and eventually continue from last checkpoint
458
+ last_checkpoint = None
459
+ if (
460
+ os.path.isdir(training_args.output_dir)
461
+ and training_args.do_train
462
+ and not training_args.overwrite_output_dir
463
+ ):
464
+ last_checkpoint = get_last_checkpoint(training_args.output_dir)
465
+ if last_checkpoint is None and len(os.listdir(training_args.output_dir)) > 0:
466
+ raise ValueError(
467
+ f"Output directory ({training_args.output_dir}) already exists and is not empty. "
468
+ "Use --overwrite_output_dir to overcome."
469
+ )
470
+ elif (
471
+ last_checkpoint is not None and training_args.resume_from_checkpoint is None
472
+ ):
473
+ logger.info(
474
+ f"Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change "
475
+ "the `--output_dir` or add `--overwrite_output_dir` to train from scratch."
476
+ )
477
+
478
+ # Set seed before initializing model.
479
+ set_seed(training_args.seed)
480
+
481
+ # 4. Load dataset
482
+ raw_datasets = IterableDatasetDict()
483
+
484
+ dataset_names = ["mozilla-foundation/common_voice_11_0", "arbml/mgb2_speech", ]
485
+ dataset_config_names = ["ar", "ar", ]
486
+ text_column_names = ["sentence", "text",]
487
+
488
+ if training_args.do_train:
489
+ raw_datasets["train"] = load_multiple_streaming_datasets(
490
+ dataset_names,
491
+ dataset_config_names=dataset_config_names,
492
+ text_column_names=text_column_names,
493
+ splits=["train","train"],
494
+ use_auth_token=True
495
+ )
496
+
497
+ if training_args.do_eval:
498
+ raw_datasets["eval"] = load_multiple_streaming_datasets(
499
+ dataset_names,
500
+ dataset_config_names=dataset_config_names,
501
+ text_column_names=text_column_names,
502
+ splits=["validation","validation"],
503
+ use_auth_token=True
504
+ )
505
+
506
+ raw_datasets_features = list(next(iter(raw_datasets.values())).features.keys())
507
+
508
+ if data_args.audio_column_name not in raw_datasets_features:
509
+ raise ValueError(
510
+ f"--audio_column_name '{data_args.audio_column_name}' not found in dataset '{data_args.dataset_name}'. "
511
+ "Make sure to set `--audio_column_name` to the correct audio column - one of "
512
+ f"{', '.join(raw_datasets_features)}."
513
+ )
514
+
515
+ # if data_args.text_column_name not in raw_datasets_features:
516
+ # print("raw_datasets_features:",raw_datasets_features)
517
+ # raise ValueError(
518
+ # f"--text_column_name {data_args.text_column_name} not found in dataset '{data_args.dataset_name}'. "
519
+ # "Make sure to set `--text_column_name` to the correct text column - one of "
520
+ # f"{', '.join(raw_datasets_features)}."
521
+ # )
522
+
523
+ # 5. Load pretrained model, tokenizer, and feature extractor
524
+ #
525
+ # Distributed training:
526
+ # The .from_pretrained methods guarantee that only one local process can concurrently
527
+ config = AutoConfig.from_pretrained(
528
+ model_args.config_name
529
+ if model_args.config_name
530
+ else model_args.model_name_or_path,
531
+ cache_dir=model_args.cache_dir,
532
+ revision=model_args.model_revision,
533
+ use_auth_token=True if model_args.use_auth_token else None,
534
+ )
535
+
536
+ config.update(
537
+ {
538
+ "forced_decoder_ids": model_args.forced_decoder_ids,
539
+ "suppress_tokens": model_args.suppress_tokens,
540
+ }
541
+ )
542
+
543
+ if training_args.gradient_checkpointing:
544
+ config.update({"use_cache": False})
545
+
546
+ feature_extractor = AutoFeatureExtractor.from_pretrained(
547
+ model_args.feature_extractor_name
548
+ if model_args.feature_extractor_name
549
+ else model_args.model_name_or_path,
550
+ cache_dir=model_args.cache_dir,
551
+ revision=model_args.model_revision,
552
+ use_auth_token=True if model_args.use_auth_token else None,
553
+ )
554
+ tokenizer = AutoTokenizer.from_pretrained(
555
+ model_args.tokenizer_name
556
+ if model_args.tokenizer_name
557
+ else model_args.model_name_or_path,
558
+ cache_dir=model_args.cache_dir,
559
+ use_fast=model_args.use_fast_tokenizer,
560
+ revision=model_args.model_revision,
561
+ use_auth_token=True if model_args.use_auth_token else None,
562
+ )
563
+ model = AutoModelForSpeechSeq2Seq.from_pretrained(
564
+ model_args.model_name_or_path,
565
+ config=config,
566
+ cache_dir=model_args.cache_dir,
567
+ revision=model_args.model_revision,
568
+ use_auth_token=True if model_args.use_auth_token else None,
569
+ )
570
+
571
+ if model.config.decoder_start_token_id is None:
572
+ raise ValueError(
573
+ "Make sure that `config.decoder_start_token_id` is correctly defined"
574
+ )
575
+
576
+ max_label_length = model.config.max_length
577
+
578
+ if model_args.freeze_feature_encoder:
579
+ model.freeze_feature_encoder()
580
+
581
+ if model_args.freeze_encoder:
582
+ model.freeze_encoder()
583
+ model.model.encoder.gradient_checkpointing = False
584
+
585
+ if data_args.language is not None:
586
+ # We only need to set the task id when the language is specified (i.e. in a multilingual setting)
587
+ tokenizer.set_prefix_tokens(language=data_args.language, task=data_args.task)
588
+
589
+ # 6. Resample speech dataset if necessary
590
+ dataset_sampling_rate = (
591
+ next(iter(raw_datasets.values()))
592
+ .features[data_args.audio_column_name]
593
+ .sampling_rate
594
+ )
595
+ if dataset_sampling_rate != feature_extractor.sampling_rate:
596
+ raw_datasets = raw_datasets.cast_column(
597
+ data_args.audio_column_name,
598
+ datasets.features.Audio(sampling_rate=feature_extractor.sampling_rate),
599
+ )
600
+
601
+ # 7. Preprocessing the datasets.
602
+ # We need to read the audio files as arrays and tokenize the targets.
603
+ max_input_length = (
604
+ data_args.max_duration_in_seconds * feature_extractor.sampling_rate
605
+ )
606
+ min_input_length = (
607
+ data_args.min_duration_in_seconds * feature_extractor.sampling_rate
608
+ )
609
+ audio_column_name = data_args.audio_column_name
610
+ text_column_name = data_args.text_column_name
611
+ model_input_name = feature_extractor.model_input_names[0]
612
+ do_lower_case = data_args.do_lower_case
613
+ do_remove_punctuation = data_args.do_remove_punctuation
614
+ normalizer = BasicTextNormalizer() # 'official' text normalizer from OpenAI
615
+
616
+ if data_args.max_train_samples is not None:
617
+ raw_datasets["train"] = raw_datasets["train"].take(data_args.max_train_samples)
618
+
619
+ if data_args.max_eval_samples is not None:
620
+ raw_datasets["eval"] = raw_datasets["eval"].select(
621
+ range(data_args.max_eval_samples)
622
+ )
623
+
624
+ def prepare_dataset(batch):
625
+ # process audio
626
+ sample = batch[audio_column_name]
627
+ inputs = feature_extractor(
628
+ sample["array"], sampling_rate=sample["sampling_rate"]
629
+ )
630
+ # process audio length
631
+ batch[model_input_name] = inputs.get(model_input_name)[0]
632
+ batch["input_length"] = len(sample["array"])
633
+
634
+ # process targets
635
+ input_str = (
636
+ batch[text_column_name].lower()
637
+ if do_lower_case
638
+ else batch[text_column_name]
639
+ )
640
+ if do_remove_punctuation:
641
+ input_str = normalizer(input_str).strip()
642
+ batch["labels"] = tokenizer(input_str).input_ids
643
+ return batch
644
+
645
+ with training_args.main_process_first(desc="dataset map pre-processing"):
646
+ vectorized_datasets = raw_datasets.map(
647
+ prepare_dataset,
648
+ remove_columns=raw_datasets_features,
649
+ ).with_format("torch")
650
+
651
+ if training_args.do_train:
652
+ vectorized_datasets["train"] = vectorized_datasets["train"].shuffle(
653
+ buffer_size=data_args.shuffle_buffer_size,
654
+ seed=training_args.seed,
655
+ )
656
+
657
+ # filter training data that is shorter than min_input_length or longer than
658
+ # max_input_length
659
+ def is_audio_in_length_range(length):
660
+ return min_input_length < length < max_input_length
661
+
662
+ vectorized_datasets["train"] = vectorized_datasets["train"].filter(
663
+ is_audio_in_length_range,
664
+ input_columns=["input_length"],
665
+ )
666
+
667
+ def filter_labels(labels):
668
+ """Filter label sequences longer than max length"""
669
+ return len(labels) < max_label_length
670
+
671
+ vectorized_datasets = vectorized_datasets.filter(
672
+ filter_labels, input_columns=["labels"]
673
+ )
674
+
675
+ # 8. Load Metric
676
+ metric = evaluate.load("wer")
677
+ do_normalize_eval = data_args.do_normalize_eval
678
+
679
+ def compute_metrics(pred):
680
+ pred_ids = pred.predictions
681
+
682
+ pred.label_ids[pred.label_ids == -100] = tokenizer.pad_token_id
683
+
684
+ pred_str = tokenizer.batch_decode(pred_ids, skip_special_tokens=True)
685
+ # we do not want to group tokens when computing the metrics
686
+ label_str = tokenizer.batch_decode(pred.label_ids, skip_special_tokens=True)
687
+
688
+ if do_normalize_eval:
689
+ pred_str = [normalizer(pred) for pred in pred_str]
690
+ label_str = [normalizer(label) for label in label_str]
691
+ # filtering step to only evaluate the samples that correspond to non-zero references:
692
+ pred_str = [
693
+ pred_str[i] for i in range(len(pred_str)) if len(label_str[i]) > 0
694
+ ]
695
+ label_str = [
696
+ label_str[i] for i in range(len(label_str)) if len(label_str[i]) > 0
697
+ ]
698
+
699
+ wer = 100 * metric.compute(predictions=pred_str, references=label_str)
700
+
701
+ return {"wer": wer}
702
+
703
+ # 9. Create a single speech processor
704
+ if is_main_process(training_args.local_rank):
705
+ # save feature extractor, tokenizer and config
706
+ feature_extractor.save_pretrained(training_args.output_dir)
707
+ tokenizer.save_pretrained(training_args.output_dir)
708
+ config.save_pretrained(training_args.output_dir)
709
+
710
+ processor = AutoProcessor.from_pretrained(training_args.output_dir)
711
+
712
+ # 10. Define data collator
713
+ data_collator = DataCollatorSpeechSeq2SeqWithPadding(
714
+ processor=processor,
715
+ decoder_start_token_id=model.config.decoder_start_token_id,
716
+ )
717
+
718
+ # 11. Configure Trainer
719
+ # Trainer callback to reinitialise and reshuffle the streamable datasets at the beginning of each epoch
720
+ # Only required for streaming: Trainer automatically shuffles non-streaming datasets
721
+ class ShuffleCallback(TrainerCallback):
722
+ def on_epoch_begin(self, args, state, control, train_dataloader, **kwargs):
723
+ if isinstance(train_dataloader.dataset, IterableDatasetShard):
724
+ pass # set_epoch() is handled by the Trainer
725
+ elif isinstance(train_dataloader.dataset, IterableDataset):
726
+ train_dataloader.dataset.set_epoch(train_dataloader.dataset._epoch + 1)
727
+
728
+ # Initialize Trainer
729
+ trainer = Seq2SeqTrainer(
730
+ model=model,
731
+ args=training_args,
732
+ train_dataset=vectorized_datasets["train"] if training_args.do_train else None,
733
+ eval_dataset=vectorized_datasets["eval"] if training_args.do_eval else None,
734
+ tokenizer=feature_extractor,
735
+ data_collator=data_collator,
736
+ compute_metrics=compute_metrics
737
+ if training_args.predict_with_generate
738
+ else None,
739
+ callbacks=[ShuffleCallback()],
740
+ )
741
+
742
+ # 12. Training
743
+ if training_args.do_train:
744
+ checkpoint = None
745
+ if training_args.resume_from_checkpoint is not None:
746
+ checkpoint = training_args.resume_from_checkpoint
747
+ elif last_checkpoint is not None:
748
+ checkpoint = last_checkpoint
749
+ train_result = trainer.train(resume_from_checkpoint=checkpoint)
750
+ trainer.save_model() # Saves the feature extractor too for easy upload
751
+
752
+ metrics = train_result.metrics
753
+ if data_args.max_train_samples:
754
+ metrics["train_samples"] = data_args.max_train_samples
755
+ trainer.log_metrics("train", metrics)
756
+ trainer.save_metrics("train", metrics)
757
+ trainer.save_state()
758
+
759
+ # 13. Evaluation
760
+ results = {}
761
+ if training_args.do_eval:
762
+ logger.info("*** Evaluate ***")
763
+ metrics = trainer.evaluate(
764
+ metric_key_prefix="eval",
765
+ max_length=training_args.generation_max_length,
766
+ num_beams=training_args.generation_num_beams,
767
+ )
768
+ if data_args.max_eval_samples:
769
+ metrics["eval_samples"] = data_args.max_eval_samples
770
+
771
+ trainer.log_metrics("eval", metrics)
772
+ trainer.save_metrics("eval", metrics)
773
+
774
+ # 14. Write Training Stats
775
+ kwargs = {
776
+ "finetuned_from": model_args.model_name_or_path,
777
+ "tasks": "automatic-speech-recognition",
778
+ "tags": "whisper-event",
779
+ }
780
+ if data_args.dataset_name is not None:
781
+ kwargs["dataset_tags"] = data_args.dataset_name
782
+ if data_args.dataset_config_name is not None:
783
+ kwargs[
784
+ "dataset"
785
+ ] = f"{data_args.dataset_name} {data_args.dataset_config_name}"
786
+ else:
787
+ kwargs["dataset"] = data_args.dataset_name
788
+ if "common_voice" in data_args.dataset_name:
789
+ kwargs["language"] = data_args.dataset_config_name[:2]
790
+ if model_args.model_index_name is not None:
791
+ kwargs["model_name"] = model_args.model_index_name
792
+
793
+ if training_args.push_to_hub:
794
+ trainer.push_to_hub(**kwargs)
795
+ else:
796
+ trainer.create_model_card(**kwargs)
797
+
798
+ return results
799
+
800
+
801
+ if __name__ == "__main__":
802
+ main()
run_speech_recognition_seq2seq_mixed_mgb2.py ADDED
@@ -0,0 +1,748 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # coding=utf-8
3
+ # Copyright 2022 The HuggingFace Team. All rights reserved.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ """
17
+ Fine-tuning the library models for sequence to sequence speech recognition
18
+ with 🤗 Datasets' streaming mode.
19
+ """
20
+ # You can also adapt this script for your own sequence to sequence speech
21
+ # recognition task. Pointers for this are left as comments.
22
+
23
+ import logging
24
+ import os
25
+ import sys
26
+ from dataclasses import dataclass, field
27
+ from typing import Any, Dict, List, Optional, Union
28
+
29
+ import datasets
30
+ import torch
31
+ from datasets import DatasetDict, IterableDatasetDict, interleave_datasets, load_dataset
32
+ from torch.utils.data import IterableDataset
33
+
34
+ import evaluate
35
+ import transformers
36
+ from transformers import (
37
+ AutoConfig,
38
+ AutoFeatureExtractor,
39
+ AutoModelForSpeechSeq2Seq,
40
+ AutoProcessor,
41
+ AutoTokenizer,
42
+ HfArgumentParser,
43
+ Seq2SeqTrainer,
44
+ Seq2SeqTrainingArguments,
45
+ TrainerCallback,
46
+ set_seed,
47
+ )
48
+ from transformers.models.whisper.english_normalizer import BasicTextNormalizer
49
+ from transformers.trainer_pt_utils import IterableDatasetShard
50
+ from transformers.trainer_utils import get_last_checkpoint, is_main_process
51
+ from transformers.utils import check_min_version, send_example_telemetry
52
+ from transformers.utils.versions import require_version
53
+
54
+
55
+ # Will error if the minimal version of Transformers is not installed. Remove at your own risks.
56
+ check_min_version("4.25.0.dev0")
57
+
58
+ require_version(
59
+ "datasets>=1.18.2",
60
+ "To fix: pip install -r examples/pytorch/speech-recognition/requirements.txt",
61
+ )
62
+
63
+ logger = logging.getLogger(__name__)
64
+
65
+
66
+ @dataclass
67
+ class ModelArguments:
68
+ """
69
+ Arguments pertaining to which model/config/tokenizer we are going to fine-tune from.
70
+ """
71
+
72
+ model_name_or_path: str = field(
73
+ metadata={
74
+ "help": "Path to pretrained model or model identifier from huggingface.co/models"
75
+ }
76
+ )
77
+ config_name: Optional[str] = field(
78
+ default=None,
79
+ metadata={
80
+ "help": "Pretrained config name or path if not the same as model_name"
81
+ },
82
+ )
83
+ tokenizer_name: Optional[str] = field(
84
+ default=None,
85
+ metadata={
86
+ "help": "Pretrained tokenizer name or path if not the same as model_name"
87
+ },
88
+ )
89
+ feature_extractor_name: Optional[str] = field(
90
+ default=None,
91
+ metadata={
92
+ "help": "feature extractor name or path if not the same as model_name"
93
+ },
94
+ )
95
+ cache_dir: Optional[str] = field(
96
+ default=None,
97
+ metadata={
98
+ "help": "Where to store the pretrained models downloaded from huggingface.co"
99
+ },
100
+ )
101
+ use_fast_tokenizer: bool = field(
102
+ default=True,
103
+ metadata={
104
+ "help": "Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."
105
+ },
106
+ )
107
+ model_revision: str = field(
108
+ default="main",
109
+ metadata={
110
+ "help": "The specific model version to use (can be a branch name, tag name or commit id)."
111
+ },
112
+ )
113
+ use_auth_token: bool = field(
114
+ default=False,
115
+ metadata={
116
+ "help": (
117
+ "Will use the token generated when running `huggingface-cli login` (necessary to use this script "
118
+ "with private models)."
119
+ )
120
+ },
121
+ )
122
+ freeze_feature_encoder: bool = field(
123
+ default=True,
124
+ metadata={"help": "Whether to freeze the feature encoder layers of the model."},
125
+ )
126
+ freeze_encoder: bool = field(
127
+ default=False,
128
+ metadata={"help": "Whether to freeze the entire encoder of the seq2seq model."},
129
+ )
130
+ forced_decoder_ids: List[List[int]] = field(
131
+ default=None,
132
+ metadata={
133
+ "help": (
134
+ "A list of pairs of integers which indicates a mapping from generation indices to token indices "
135
+ "that will be forced before sampling. For example, [[0, 123]] means the first generated token "
136
+ "will always be a token of index 123."
137
+ )
138
+ },
139
+ )
140
+ suppress_tokens: List[int] = field(
141
+ default=None,
142
+ metadata={"help": "A list of tokens that will be suppressed at generation."},
143
+ )
144
+ model_index_name: str = field(
145
+ default=None, metadata={"help": "Pretty name for the model card."}
146
+ )
147
+
148
+
149
+ @dataclass
150
+ class DataTrainingArguments:
151
+ """
152
+ Arguments pertaining to what data we are going to input our model for training and eval.
153
+ """
154
+
155
+ dataset_name: str = field(
156
+ default=None,
157
+ metadata={"help": "The name of the dataset to use (via the datasets library)."},
158
+ )
159
+ dataset_config_name: Optional[str] = field(
160
+ default=None,
161
+ metadata={
162
+ "help": "The configuration name of the dataset to use (via the datasets library)."
163
+ },
164
+ )
165
+ text_column: Optional[str] = field(
166
+ default=None,
167
+ metadata={
168
+ "help": "The name of the column in the datasets containing the full texts (for summarization)."
169
+ },
170
+ )
171
+ max_train_samples: Optional[int] = field(
172
+ default=None,
173
+ metadata={
174
+ "help": (
175
+ "For debugging purposes or quicker training, truncate the number of training examples to this "
176
+ "value if set."
177
+ )
178
+ },
179
+ )
180
+ max_eval_samples: Optional[int] = field(
181
+ default=None,
182
+ metadata={
183
+ "help": (
184
+ "For debugging purposes or quicker training, truncate the number of evaluation examples to this "
185
+ "value if set."
186
+ )
187
+ },
188
+ )
189
+ audio_column_name: str = field(
190
+ default="audio",
191
+ metadata={
192
+ "help": "The name of the dataset column containing the audio data. Defaults to 'audio'"
193
+ },
194
+ )
195
+ text_column_name: str = field(
196
+ default="text",
197
+ metadata={
198
+ "help": "The name of the dataset column containing the text data. Defaults to 'text'"
199
+ },
200
+ )
201
+ max_duration_in_seconds: float = field(
202
+ default=20.0,
203
+ metadata={
204
+ "help": (
205
+ "Truncate audio files that are longer than `max_duration_in_seconds` seconds to"
206
+ " 'max_duration_in_seconds`"
207
+ )
208
+ },
209
+ )
210
+ min_duration_in_seconds: float = field(
211
+ default=0.0,
212
+ metadata={
213
+ "help": "Filter audio files that are shorter than `min_duration_in_seconds` seconds"
214
+ },
215
+ )
216
+ train_split_name: str = field(
217
+ default="train",
218
+ metadata={
219
+ "help": "The name of the training data set split to use (via the datasets library). Defaults to 'train'"
220
+ },
221
+ )
222
+ eval_split_name: str = field(
223
+ default="test",
224
+ metadata={
225
+ "help": "The name of the training data set split to use (via the datasets library). Defaults to 'train'"
226
+ },
227
+ )
228
+ do_lower_case: bool = field(
229
+ default=False,
230
+ metadata={"help": "Whether the target text should be lower cased."},
231
+ )
232
+ do_remove_punctuation: bool = field(
233
+ default=False,
234
+ metadata={"help": "Whether the target text should be striped of punctuation."},
235
+ )
236
+ do_normalize_eval: bool = field(
237
+ default=True,
238
+ metadata={
239
+ "help": "Whether to normalise the references and predictions in the eval WER calculation."
240
+ },
241
+ )
242
+ language: str = field(
243
+ default=None,
244
+ metadata={
245
+ "help": (
246
+ "Language for multilingual fine-tuning. This argument should be set for multilingual fine-tuning "
247
+ "only. For English speech recognition, it should be set to `None`."
248
+ )
249
+ },
250
+ )
251
+ task: str = field(
252
+ default="transcribe",
253
+ metadata={
254
+ "help": "Task, either `transcribe` for speech recognition or `translate` for speech translation."
255
+ },
256
+ )
257
+ shuffle_buffer_size: Optional[int] = field(
258
+ default=500,
259
+ metadata={
260
+ "help": (
261
+ "The number of streamed examples to download before shuffling them. The large the buffer, "
262
+ "the closer it is to real offline shuffling."
263
+ )
264
+ },
265
+ )
266
+ streaming: bool = field(
267
+ default=True,
268
+ metadata={
269
+ "help": "Whether to use streaming mode to load and pre-process the data."
270
+ },
271
+ )
272
+
273
+
274
+ @dataclass
275
+ class DataCollatorSpeechSeq2SeqWithPadding:
276
+ """
277
+ Data collator that will dynamically pad the inputs received.
278
+ Args:
279
+ processor ([`WhisperProcessor`])
280
+ The processor used for processing the data.
281
+ decoder_start_token_id (`int`)
282
+ The begin-of-sentence of the decoder.
283
+ """
284
+
285
+ processor: Any
286
+ decoder_start_token_id: int
287
+
288
+ def __call__(
289
+ self, features: List[Dict[str, Union[List[int], torch.Tensor]]]
290
+ ) -> Dict[str, torch.Tensor]:
291
+ # split inputs and labels since they have to be of different lengths and need
292
+ # different padding methods
293
+ model_input_name = self.processor.model_input_names[0]
294
+ input_features = [
295
+ {model_input_name: feature[model_input_name]} for feature in features
296
+ ]
297
+ label_features = [{"input_ids": feature["labels"]} for feature in features]
298
+
299
+ batch = self.processor.feature_extractor.pad(
300
+ input_features, return_tensors="pt"
301
+ )
302
+
303
+ labels_batch = self.processor.tokenizer.pad(label_features, return_tensors="pt")
304
+
305
+ # replace padding with -100 to ignore loss correctly
306
+ labels = labels_batch["input_ids"].masked_fill(
307
+ labels_batch.attention_mask.ne(1), -100
308
+ )
309
+
310
+ # if bos token is appended in previous tokenization step,
311
+ # cut bos token here as it's append later anyways
312
+ if (labels[:, 0] == self.decoder_start_token_id).all().cpu().item():
313
+ labels = labels[:, 1:]
314
+
315
+ batch["labels"] = labels
316
+
317
+ return batch
318
+
319
+
320
+ def load_maybe_streaming_dataset(
321
+ dataset_name, dataset_config_name, split="train", streaming=True, **kwargs
322
+ ):
323
+ """
324
+ Utility function to load a dataset in streaming mode. For datasets with multiple splits,
325
+ each split is loaded individually and then splits combined by taking alternating examples from
326
+ each (interleaving).
327
+ """
328
+ if "+" in split:
329
+ # load multiple splits separated by the `+` symbol with streaming mode
330
+ dataset_splits = [
331
+ load_dataset(
332
+ dataset_name,
333
+ dataset_config_name,
334
+ split=split_name,
335
+ streaming=streaming,
336
+ **kwargs,
337
+ )
338
+ for split_name in split.split("+")
339
+ ]
340
+ # interleave multiple splits to form one dataset
341
+ interleaved_dataset = interleave_datasets(dataset_splits)
342
+ return interleaved_dataset
343
+ else:
344
+ # load a single split *with* streaming mode
345
+ dataset = load_dataset(
346
+ dataset_name,
347
+ dataset_config_name,
348
+ split=split,
349
+ streaming=streaming,
350
+ **kwargs,
351
+ )
352
+ return dataset
353
+
354
+
355
+ def main():
356
+ # 1. Parse input arguments
357
+ # See all possible arguments in src/transformers/training_args.py
358
+ # or by passing the --help flag to this script.
359
+ # We now keep distinct sets of args, for a cleaner separation of concerns.
360
+ parser = HfArgumentParser(
361
+ (ModelArguments, DataTrainingArguments, Seq2SeqTrainingArguments)
362
+ )
363
+
364
+ if len(sys.argv) == 2 and sys.argv[1].endswith(".json"):
365
+ # If we pass only one argument to the script and it's the path to a json file,
366
+ # let's parse it to get our arguments.
367
+ model_args, data_args, training_args = parser.parse_json_file(
368
+ json_file=os.path.abspath(sys.argv[1])
369
+ )
370
+ else:
371
+ model_args, data_args, training_args = parser.parse_args_into_dataclasses()
372
+
373
+ # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
374
+ # information sent is the one passed as arguments along with your Python/PyTorch versions.
375
+ send_example_telemetry(
376
+ "run_speech_recognition_seq2seq_streaming", model_args, data_args
377
+ )
378
+
379
+ # 2. Setup logging
380
+ logging.basicConfig(
381
+ format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
382
+ datefmt="%m/%d/%Y %H:%M:%S",
383
+ handlers=[logging.StreamHandler(sys.stdout)],
384
+ )
385
+ log_level = training_args.get_process_log_level()
386
+ logger.setLevel(log_level)
387
+ datasets.utils.logging.set_verbosity(log_level)
388
+ transformers.utils.logging.set_verbosity(log_level)
389
+ transformers.utils.logging.enable_default_handler()
390
+ transformers.utils.logging.enable_explicit_format()
391
+
392
+ logger.setLevel(
393
+ logging.INFO if is_main_process(training_args.local_rank) else logging.WARN
394
+ )
395
+
396
+ # Log on each process the small summary:
397
+ logger.warning(
398
+ f"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}"
399
+ f"distributed training: {bool(training_args.local_rank != -1)}, 16-bits training: {training_args.fp16}"
400
+ )
401
+ logger.info(f"Training/evaluation parameters {training_args}")
402
+
403
+ # Set the verbosity to info of the Transformers logger (on main process only):
404
+ if is_main_process(training_args.local_rank):
405
+ transformers.utils.logging.set_verbosity_info()
406
+ logger.info("Training/evaluation parameters %s", training_args)
407
+
408
+ # 3. Detecting last checkpoint and eventually continue from last checkpoint
409
+ last_checkpoint = None
410
+ if (
411
+ os.path.isdir(training_args.output_dir)
412
+ and training_args.do_train
413
+ and not training_args.overwrite_output_dir
414
+ ):
415
+ last_checkpoint = get_last_checkpoint(training_args.output_dir)
416
+ if last_checkpoint is None and len(os.listdir(training_args.output_dir)) > 0:
417
+ raise ValueError(
418
+ f"Output directory ({training_args.output_dir}) already exists and is not empty. "
419
+ "Use --overwrite_output_dir to overcome."
420
+ )
421
+ elif (
422
+ last_checkpoint is not None and training_args.resume_from_checkpoint is None
423
+ ):
424
+ logger.info(
425
+ f"Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change "
426
+ "the `--output_dir` or add `--overwrite_output_dir` to train from scratch."
427
+ )
428
+
429
+ # Set seed before initializing model.
430
+ set_seed(training_args.seed)
431
+
432
+ # 4. Load dataset
433
+ raw_datasets = IterableDatasetDict()
434
+
435
+ if training_args.do_train:
436
+ raw_datasets["train"] = load_maybe_streaming_dataset(
437
+ data_args.dataset_name,
438
+ data_args.dataset_config_name,
439
+ split=data_args.train_split_name,
440
+ streaming=True,
441
+ use_auth_token=True if model_args.use_auth_token else None,
442
+ )
443
+
444
+ if training_args.do_eval:
445
+ raw_datasets["eval"] = load_maybe_streaming_dataset(
446
+ "arbml/mgb3",
447
+ data_args.dataset_config_name,
448
+ split="train",
449
+ streaming=False,
450
+ use_auth_token=True if model_args.use_auth_token else None,
451
+ )
452
+
453
+ raw_datasets_features = list(next(iter(raw_datasets.values())).features.keys())
454
+
455
+ if data_args.audio_column_name not in raw_datasets_features:
456
+ raise ValueError(
457
+ f"--audio_column_name '{data_args.audio_column_name}' not found in dataset '{data_args.dataset_name}'. "
458
+ "Make sure to set `--audio_column_name` to the correct audio column - one of "
459
+ f"{', '.join(raw_datasets_features)}."
460
+ )
461
+
462
+ if data_args.text_column_name not in raw_datasets_features:
463
+ raise ValueError(
464
+ f"--text_column_name {data_args.text_column_name} not found in dataset '{data_args.dataset_name}'. "
465
+ "Make sure to set `--text_column_name` to the correct text column - one of "
466
+ f"{', '.join(raw_datasets_features)}."
467
+ )
468
+
469
+ # 5. Load pretrained model, tokenizer, and feature extractor
470
+ #
471
+ # Distributed training:
472
+ # The .from_pretrained methods guarantee that only one local process can concurrently
473
+ config = AutoConfig.from_pretrained(
474
+ model_args.config_name
475
+ if model_args.config_name
476
+ else model_args.model_name_or_path,
477
+ cache_dir=model_args.cache_dir,
478
+ revision=model_args.model_revision,
479
+ use_auth_token=True if model_args.use_auth_token else None,
480
+ )
481
+
482
+ config.update(
483
+ {
484
+ "forced_decoder_ids": model_args.forced_decoder_ids,
485
+ "suppress_tokens": model_args.suppress_tokens,
486
+ }
487
+ )
488
+
489
+ if training_args.gradient_checkpointing:
490
+ config.update({"use_cache": False})
491
+
492
+ feature_extractor = AutoFeatureExtractor.from_pretrained(
493
+ model_args.feature_extractor_name
494
+ if model_args.feature_extractor_name
495
+ else model_args.model_name_or_path,
496
+ cache_dir=model_args.cache_dir,
497
+ revision=model_args.model_revision,
498
+ use_auth_token=True if model_args.use_auth_token else None,
499
+ )
500
+ tokenizer = AutoTokenizer.from_pretrained(
501
+ model_args.tokenizer_name
502
+ if model_args.tokenizer_name
503
+ else model_args.model_name_or_path,
504
+ cache_dir=model_args.cache_dir,
505
+ use_fast=model_args.use_fast_tokenizer,
506
+ revision=model_args.model_revision,
507
+ use_auth_token=True if model_args.use_auth_token else None,
508
+ )
509
+ model = AutoModelForSpeechSeq2Seq.from_pretrained(
510
+ model_args.model_name_or_path,
511
+ config=config,
512
+ cache_dir=model_args.cache_dir,
513
+ revision=model_args.model_revision,
514
+ use_auth_token=True if model_args.use_auth_token else None,
515
+ )
516
+
517
+ if model.config.decoder_start_token_id is None:
518
+ raise ValueError(
519
+ "Make sure that `config.decoder_start_token_id` is correctly defined"
520
+ )
521
+
522
+ max_label_length = model.config.max_length
523
+
524
+ if model_args.freeze_feature_encoder:
525
+ model.freeze_feature_encoder()
526
+
527
+ if model_args.freeze_encoder:
528
+ model.freeze_encoder()
529
+ model.model.encoder.gradient_checkpointing = False
530
+
531
+ if data_args.language is not None:
532
+ # We only need to set the task id when the language is specified (i.e. in a multilingual setting)
533
+ tokenizer.set_prefix_tokens(language=data_args.language, task=data_args.task)
534
+
535
+ # 6. Resample speech dataset if necessary
536
+ dataset_sampling_rate = (
537
+ next(iter(raw_datasets.values()))
538
+ .features[data_args.audio_column_name]
539
+ .sampling_rate
540
+ )
541
+ if dataset_sampling_rate != feature_extractor.sampling_rate:
542
+ raw_datasets = raw_datasets.cast_column(
543
+ data_args.audio_column_name,
544
+ datasets.features.Audio(sampling_rate=feature_extractor.sampling_rate),
545
+ )
546
+
547
+ # 7. Preprocessing the datasets.
548
+ # We need to read the audio files as arrays and tokenize the targets.
549
+ max_input_length = (
550
+ data_args.max_duration_in_seconds * feature_extractor.sampling_rate
551
+ )
552
+ min_input_length = (
553
+ data_args.min_duration_in_seconds * feature_extractor.sampling_rate
554
+ )
555
+ audio_column_name = data_args.audio_column_name
556
+ text_column_name = data_args.text_column_name
557
+ model_input_name = feature_extractor.model_input_names[0]
558
+ do_lower_case = data_args.do_lower_case
559
+ do_remove_punctuation = data_args.do_remove_punctuation
560
+ normalizer = BasicTextNormalizer() # 'official' text normalizer from OpenAI
561
+
562
+ if data_args.max_train_samples is not None:
563
+ raw_datasets["train"] = raw_datasets["train"].take(data_args.max_train_samples)
564
+
565
+ if data_args.max_eval_samples is not None:
566
+ raw_datasets["eval"] = raw_datasets["eval"].select(
567
+ range(data_args.max_eval_samples)
568
+ )
569
+
570
+ def prepare_dataset(batch):
571
+ # process audio
572
+ sample = batch[audio_column_name]
573
+ inputs = feature_extractor(
574
+ sample["array"], sampling_rate=sample["sampling_rate"]
575
+ )
576
+ # process audio length
577
+ batch[model_input_name] = inputs.get(model_input_name)[0]
578
+ batch["input_length"] = len(sample["array"])
579
+
580
+ # process targets
581
+ input_str = (
582
+ batch[text_column_name].lower()
583
+ if do_lower_case
584
+ else batch[text_column_name]
585
+ )
586
+ if do_remove_punctuation:
587
+ input_str = normalizer(input_str).strip()
588
+ batch["labels"] = tokenizer(input_str).input_ids
589
+ return batch
590
+
591
+ with training_args.main_process_first(desc="dataset map pre-processing"):
592
+ vectorized_datasets = raw_datasets.map(
593
+ prepare_dataset,
594
+ remove_columns=raw_datasets_features,
595
+ ).with_format("torch")
596
+
597
+ if training_args.do_train:
598
+ vectorized_datasets["train"] = vectorized_datasets["train"].shuffle(
599
+ buffer_size=data_args.shuffle_buffer_size,
600
+ seed=training_args.seed,
601
+ )
602
+
603
+ # filter training data that is shorter than min_input_length or longer than
604
+ # max_input_length
605
+ def is_audio_in_length_range(length):
606
+ return min_input_length < length < max_input_length
607
+
608
+ vectorized_datasets["train"] = vectorized_datasets["train"].filter(
609
+ is_audio_in_length_range,
610
+ input_columns=["input_length"],
611
+ )
612
+
613
+ def filter_labels(labels):
614
+ """Filter label sequences longer than max length"""
615
+ return len(labels) < max_label_length
616
+
617
+ vectorized_datasets = vectorized_datasets.filter(
618
+ filter_labels, input_columns=["labels"]
619
+ )
620
+
621
+ # 8. Load Metric
622
+ metric = evaluate.load("wer")
623
+ do_normalize_eval = data_args.do_normalize_eval
624
+
625
+ def compute_metrics(pred):
626
+ pred_ids = pred.predictions
627
+
628
+ pred.label_ids[pred.label_ids == -100] = tokenizer.pad_token_id
629
+
630
+ pred_str = tokenizer.batch_decode(pred_ids, skip_special_tokens=True)
631
+ # we do not want to group tokens when computing the metrics
632
+ label_str = tokenizer.batch_decode(pred.label_ids, skip_special_tokens=True)
633
+
634
+ if do_normalize_eval:
635
+ pred_str = [normalizer(pred) for pred in pred_str]
636
+ label_str = [normalizer(label) for label in label_str]
637
+ # filtering step to only evaluate the samples that correspond to non-zero references:
638
+ pred_str = [
639
+ pred_str[i] for i in range(len(pred_str)) if len(label_str[i]) > 0
640
+ ]
641
+ label_str = [
642
+ label_str[i] for i in range(len(label_str)) if len(label_str[i]) > 0
643
+ ]
644
+
645
+ wer = 100 * metric.compute(predictions=pred_str, references=label_str)
646
+
647
+ return {"wer": wer}
648
+
649
+ # 9. Create a single speech processor
650
+ if is_main_process(training_args.local_rank):
651
+ # save feature extractor, tokenizer and config
652
+ feature_extractor.save_pretrained(training_args.output_dir)
653
+ tokenizer.save_pretrained(training_args.output_dir)
654
+ config.save_pretrained(training_args.output_dir)
655
+
656
+ processor = AutoProcessor.from_pretrained(training_args.output_dir)
657
+
658
+ # 10. Define data collator
659
+ data_collator = DataCollatorSpeechSeq2SeqWithPadding(
660
+ processor=processor,
661
+ decoder_start_token_id=model.config.decoder_start_token_id,
662
+ )
663
+
664
+ # 11. Configure Trainer
665
+ # Trainer callback to reinitialise and reshuffle the streamable datasets at the beginning of each epoch
666
+ # Only required for streaming: Trainer automatically shuffles non-streaming datasets
667
+ class ShuffleCallback(TrainerCallback):
668
+ def on_epoch_begin(self, args, state, control, train_dataloader, **kwargs):
669
+ if isinstance(train_dataloader.dataset, IterableDatasetShard):
670
+ pass # set_epoch() is handled by the Trainer
671
+ elif isinstance(train_dataloader.dataset, IterableDataset):
672
+ train_dataloader.dataset.set_epoch(train_dataloader.dataset._epoch + 1)
673
+
674
+ # Initialize Trainer
675
+ trainer = Seq2SeqTrainer(
676
+ model=model,
677
+ args=training_args,
678
+ train_dataset=vectorized_datasets["train"] if training_args.do_train else None,
679
+ eval_dataset=vectorized_datasets["eval"] if training_args.do_eval else None,
680
+ tokenizer=feature_extractor,
681
+ data_collator=data_collator,
682
+ compute_metrics=compute_metrics
683
+ if training_args.predict_with_generate
684
+ else None,
685
+ callbacks=[ShuffleCallback()],
686
+ )
687
+
688
+ # 12. Training
689
+ if training_args.do_train:
690
+ checkpoint = None
691
+ if training_args.resume_from_checkpoint is not None:
692
+ checkpoint = training_args.resume_from_checkpoint
693
+ elif last_checkpoint is not None:
694
+ checkpoint = last_checkpoint
695
+ train_result = trainer.train(resume_from_checkpoint=checkpoint)
696
+ trainer.save_model() # Saves the feature extractor too for easy upload
697
+
698
+ metrics = train_result.metrics
699
+ if data_args.max_train_samples:
700
+ metrics["train_samples"] = data_args.max_train_samples
701
+ trainer.log_metrics("train", metrics)
702
+ trainer.save_metrics("train", metrics)
703
+ trainer.save_state()
704
+
705
+ # 13. Evaluation
706
+ results = {}
707
+ if training_args.do_eval:
708
+ logger.info("*** Evaluate ***")
709
+ metrics = trainer.evaluate(
710
+ metric_key_prefix="eval",
711
+ max_length=training_args.generation_max_length,
712
+ num_beams=training_args.generation_num_beams,
713
+ )
714
+ if data_args.max_eval_samples:
715
+ metrics["eval_samples"] = data_args.max_eval_samples
716
+
717
+ trainer.log_metrics("eval", metrics)
718
+ trainer.save_metrics("eval", metrics)
719
+
720
+ # 14. Write Training Stats
721
+ kwargs = {
722
+ "finetuned_from": model_args.model_name_or_path,
723
+ "tasks": "automatic-speech-recognition",
724
+ "tags": "whisper-event",
725
+ }
726
+ if data_args.dataset_name is not None:
727
+ kwargs["dataset_tags"] = data_args.dataset_name
728
+ if data_args.dataset_config_name is not None:
729
+ kwargs[
730
+ "dataset"
731
+ ] = f"{data_args.dataset_name} {data_args.dataset_config_name}"
732
+ else:
733
+ kwargs["dataset"] = data_args.dataset_name
734
+ if "common_voice" in data_args.dataset_name:
735
+ kwargs["language"] = data_args.dataset_config_name[:2]
736
+ if model_args.model_index_name is not None:
737
+ kwargs["model_name"] = model_args.model_index_name
738
+
739
+ if training_args.push_to_hub:
740
+ trainer.push_to_hub(**kwargs)
741
+ else:
742
+ trainer.create_model_card(**kwargs)
743
+
744
+ return results
745
+
746
+
747
+ if __name__ == "__main__":
748
+ main()
run_speech_recognition_seq2seq_streaming.py ADDED
@@ -0,0 +1,608 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # coding=utf-8
3
+ # Copyright 2022 The HuggingFace Team. All rights reserved.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ """
17
+ Fine-tuning the library models for sequence to sequence speech recognition
18
+ with 🤗 Datasets' streaming mode.
19
+ """
20
+ # You can also adapt this script for your own sequence to sequence speech
21
+ # recognition task. Pointers for this are left as comments.
22
+
23
+ import logging
24
+ import os
25
+ import sys
26
+ from dataclasses import dataclass, field
27
+ from typing import Any, Dict, List, Optional, Union
28
+
29
+ import datasets
30
+ import torch
31
+ from datasets import IterableDatasetDict, interleave_datasets, load_dataset
32
+ from torch.utils.data import IterableDataset
33
+
34
+ import evaluate
35
+ import transformers
36
+ from transformers import (
37
+ AutoConfig,
38
+ AutoFeatureExtractor,
39
+ AutoModelForSpeechSeq2Seq,
40
+ AutoProcessor,
41
+ AutoTokenizer,
42
+ HfArgumentParser,
43
+ Seq2SeqTrainer,
44
+ Seq2SeqTrainingArguments,
45
+ TrainerCallback,
46
+ set_seed,
47
+ )
48
+ from transformers.trainer_pt_utils import IterableDatasetShard
49
+ from transformers.trainer_utils import get_last_checkpoint, is_main_process
50
+ from transformers.utils import check_min_version, send_example_telemetry
51
+ from transformers.utils.versions import require_version
52
+ from transformers.models.whisper.english_normalizer import BasicTextNormalizer
53
+ import os
54
+ os.environ['LD_LIBRARY_PATH'] = '/usr/lib/x86_64-linux-gnu'
55
+ # Will error if the minimal version of Transformers is not installed. Remove at your own risks.
56
+ check_min_version("4.25.0.dev0")
57
+
58
+ require_version("datasets>=1.18.2", "To fix: pip install -r examples/pytorch/speech-recognition/requirements.txt")
59
+
60
+ logger = logging.getLogger(__name__)
61
+
62
+
63
+ @dataclass
64
+ class ModelArguments:
65
+ """
66
+ Arguments pertaining to which model/config/tokenizer we are going to fine-tune from.
67
+ """
68
+
69
+ model_name_or_path: str = field(
70
+ metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"}
71
+ )
72
+ config_name: Optional[str] = field(
73
+ default=None, metadata={"help": "Pretrained config name or path if not the same as model_name"}
74
+ )
75
+ tokenizer_name: Optional[str] = field(
76
+ default=None, metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"}
77
+ )
78
+ feature_extractor_name: Optional[str] = field(
79
+ default=None, metadata={"help": "feature extractor name or path if not the same as model_name"}
80
+ )
81
+ cache_dir: Optional[str] = field(
82
+ default=None,
83
+ metadata={"help": "Where to store the pretrained models downloaded from huggingface.co"},
84
+ )
85
+ use_fast_tokenizer: bool = field(
86
+ default=True,
87
+ metadata={"help": "Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."},
88
+ )
89
+ model_revision: str = field(
90
+ default="main",
91
+ metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."},
92
+ )
93
+ use_auth_token: bool = field(
94
+ default=False,
95
+ metadata={
96
+ "help": (
97
+ "Will use the token generated when running `huggingface-cli login` (necessary to use this script "
98
+ "with private models)."
99
+ )
100
+ },
101
+ )
102
+ freeze_feature_encoder: bool = field(
103
+ default=True, metadata={"help": "Whether to freeze the feature encoder layers of the model."}
104
+ )
105
+ freeze_encoder: bool = field(
106
+ default=False, metadata={"help": "Whether to freeze the entire encoder of the seq2seq model."}
107
+ )
108
+ forced_decoder_ids: List[List[int]] = field(
109
+ default=None,
110
+ metadata={
111
+ "help": (
112
+ "A list of pairs of integers which indicates a mapping from generation indices to token indices "
113
+ "that will be forced before sampling. For example, [[0, 123]] means the first generated token "
114
+ "will always be a token of index 123."
115
+ )
116
+ },
117
+ )
118
+ suppress_tokens: List[int] = field(
119
+ default=None, metadata={"help": "A list of tokens that will be suppressed at generation."}
120
+ )
121
+ model_index_name: str = field(default=None, metadata={"help": "Pretty name for the model card."})
122
+
123
+
124
+ @dataclass
125
+ class DataTrainingArguments:
126
+ """
127
+ Arguments pertaining to what data we are going to input our model for training and eval.
128
+ """
129
+
130
+ dataset_name: str = field(
131
+ default=None, metadata={"help": "The name of the dataset to use (via the datasets library)."}
132
+ )
133
+ dataset_config_name: Optional[str] = field(
134
+ default=None, metadata={"help": "The configuration name of the dataset to use (via the datasets library)."}
135
+ )
136
+ text_column: Optional[str] = field(
137
+ default=None,
138
+ metadata={"help": "The name of the column in the datasets containing the full texts (for summarization)."},
139
+ )
140
+ max_train_samples: Optional[int] = field(
141
+ default=None,
142
+ metadata={
143
+ "help": (
144
+ "For debugging purposes or quicker training, truncate the number of training examples to this "
145
+ "value if set."
146
+ )
147
+ },
148
+ )
149
+ max_eval_samples: Optional[int] = field(
150
+ default=None,
151
+ metadata={
152
+ "help": (
153
+ "For debugging purposes or quicker training, truncate the number of evaluation examples to this "
154
+ "value if set."
155
+ )
156
+ },
157
+ )
158
+ audio_column_name: str = field(
159
+ default="audio",
160
+ metadata={"help": "The name of the dataset column containing the audio data. Defaults to 'audio'"},
161
+ )
162
+ text_column_name: str = field(
163
+ default="text",
164
+ metadata={"help": "The name of the dataset column containing the text data. Defaults to 'text'"},
165
+ )
166
+ max_duration_in_seconds: float = field(
167
+ default=20.0,
168
+ metadata={
169
+ "help": (
170
+ "Truncate audio files that are longer than `max_duration_in_seconds` seconds to"
171
+ " 'max_duration_in_seconds`"
172
+ )
173
+ },
174
+ )
175
+ min_duration_in_seconds: float = field(
176
+ default=0.0, metadata={"help": "Filter audio files that are shorter than `min_duration_in_seconds` seconds"}
177
+ )
178
+ train_split_name: str = field(
179
+ default="train",
180
+ metadata={
181
+ "help": "The name of the training data set split to use (via the datasets library). Defaults to 'train'"
182
+ },
183
+ )
184
+ eval_split_name: str = field(
185
+ default="test",
186
+ metadata={
187
+ "help": "The name of the training data set split to use (via the datasets library). Defaults to 'train'"
188
+ },
189
+ )
190
+ do_lower_case: bool = field(
191
+ default=False,
192
+ metadata={"help": "Whether the target text should be lower cased."},
193
+ )
194
+ do_remove_punctuation: bool = field(
195
+ default=False,
196
+ metadata={"help": "Whether the target text should be striped of punctuation."},
197
+ )
198
+ do_normalize_eval: bool = field(
199
+ default=True,
200
+ metadata={"help": "Whether to normalise the references and predictions in the eval WER calculation."},
201
+ )
202
+ language: str = field(
203
+ default=None,
204
+ metadata={
205
+ "help": (
206
+ "Language for multilingual fine-tuning. This argument should be set for multilingual fine-tuning "
207
+ "only. For English speech recognition, it should be set to `None`."
208
+ )
209
+ },
210
+ )
211
+ task: str = field(
212
+ default="transcribe",
213
+ metadata={"help": "Task, either `transcribe` for speech recognition or `translate` for speech translation."},
214
+ )
215
+ shuffle_buffer_size: Optional[int] = field(
216
+ default=500,
217
+ metadata={
218
+ "help": (
219
+ "The number of streamed examples to download before shuffling them. The large the buffer, "
220
+ "the closer it is to real offline shuffling."
221
+ )
222
+ },
223
+ )
224
+
225
+
226
+ @dataclass
227
+ class DataCollatorSpeechSeq2SeqWithPadding:
228
+ """
229
+ Data collator that will dynamically pad the inputs received.
230
+ Args:
231
+ processor ([`WhisperProcessor`])
232
+ The processor used for processing the data.
233
+ decoder_start_token_id (`int`)
234
+ The begin-of-sentence of the decoder.
235
+ """
236
+
237
+ processor: Any
238
+ decoder_start_token_id: int
239
+
240
+ def __call__(self, features: List[Dict[str, Union[List[int], torch.Tensor]]]) -> Dict[str, torch.Tensor]:
241
+ # split inputs and labels since they have to be of different lengths and need
242
+ # different padding methods
243
+ model_input_name = self.processor.model_input_names[0]
244
+ input_features = [{model_input_name: feature[model_input_name]} for feature in features]
245
+ label_features = [{"input_ids": feature["labels"]} for feature in features]
246
+
247
+ batch = self.processor.feature_extractor.pad(input_features, return_tensors="pt")
248
+
249
+ labels_batch = self.processor.tokenizer.pad(label_features, return_tensors="pt")
250
+
251
+ # replace padding with -100 to ignore loss correctly
252
+ labels = labels_batch["input_ids"].masked_fill(labels_batch.attention_mask.ne(1), -100)
253
+
254
+ # if bos token is appended in previous tokenization step,
255
+ # cut bos token here as it's append later anyways
256
+ if (labels[:, 0] == self.decoder_start_token_id).all().cpu().item():
257
+ labels = labels[:, 1:]
258
+
259
+ batch["labels"] = labels
260
+
261
+ return batch
262
+
263
+
264
+ def load_streaming_dataset(dataset_name, dataset_config_name, split="train", **kwargs):
265
+ """
266
+ Utility function to load a dataset in streaming mode. For datasets with multiple splits,
267
+ each split is loaded individually and then splits combined by taking alternating examples from
268
+ each (interleaving).
269
+ """
270
+ if "+" in split:
271
+ # load multiple splits separated by the `+` symbol with streaming mode
272
+ dataset_splits = [
273
+ load_dataset(dataset_name, dataset_config_name, split=split_name, streaming=True, **kwargs)
274
+ for split_name in split.split("+")
275
+ ]
276
+ # interleave multiple splits to form one dataset
277
+ interleaved_dataset = interleave_datasets(dataset_splits)
278
+ return interleaved_dataset
279
+ else:
280
+ # load a single split *with* streaming mode
281
+ dataset = load_dataset(dataset_name, dataset_config_name, split=split, streaming=True, **kwargs)
282
+ return dataset
283
+
284
+
285
+ def main():
286
+ # 1. Parse input arguments
287
+ # See all possible arguments in src/transformers/training_args.py
288
+ # or by passing the --help flag to this script.
289
+ # We now keep distinct sets of args, for a cleaner separation of concerns.
290
+ parser = HfArgumentParser((ModelArguments, DataTrainingArguments, Seq2SeqTrainingArguments))
291
+
292
+ if len(sys.argv) == 2 and sys.argv[1].endswith(".json"):
293
+ # If we pass only one argument to the script and it's the path to a json file,
294
+ # let's parse it to get our arguments.
295
+ model_args, data_args, training_args = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]))
296
+ else:
297
+ model_args, data_args, training_args = parser.parse_args_into_dataclasses()
298
+
299
+ # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
300
+ # information sent is the one passed as arguments along with your Python/PyTorch versions.
301
+ send_example_telemetry("run_speech_recognition_seq2seq_streaming", model_args, data_args)
302
+
303
+ # 2. Setup logging
304
+ logging.basicConfig(
305
+ format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
306
+ datefmt="%m/%d/%Y %H:%M:%S",
307
+ handlers=[logging.StreamHandler(sys.stdout)],
308
+ )
309
+ log_level = training_args.get_process_log_level()
310
+ logger.setLevel(log_level)
311
+ datasets.utils.logging.set_verbosity(log_level)
312
+ transformers.utils.logging.set_verbosity(log_level)
313
+ transformers.utils.logging.enable_default_handler()
314
+ transformers.utils.logging.enable_explicit_format()
315
+
316
+ logger.setLevel(logging.INFO if is_main_process(training_args.local_rank) else logging.WARN)
317
+
318
+ # Log on each process the small summary:
319
+ logger.warning(
320
+ f"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}"
321
+ f"distributed training: {bool(training_args.local_rank != -1)}, 16-bits training: {training_args.fp16}"
322
+ )
323
+ logger.info(f"Training/evaluation parameters {training_args}")
324
+
325
+ # Set the verbosity to info of the Transformers logger (on main process only):
326
+ if is_main_process(training_args.local_rank):
327
+ transformers.utils.logging.set_verbosity_info()
328
+ logger.info("Training/evaluation parameters %s", training_args)
329
+
330
+ # 3. Detecting last checkpoint and eventually continue from last checkpoint
331
+ last_checkpoint = None
332
+ if os.path.isdir(training_args.output_dir) and training_args.do_train and not training_args.overwrite_output_dir:
333
+ last_checkpoint = get_last_checkpoint(training_args.output_dir)
334
+ if last_checkpoint is None and len(os.listdir(training_args.output_dir)) > 0:
335
+ raise ValueError(
336
+ f"Output directory ({training_args.output_dir}) already exists and is not empty. "
337
+ "Use --overwrite_output_dir to overcome."
338
+ )
339
+ elif last_checkpoint is not None and training_args.resume_from_checkpoint is None:
340
+ logger.info(
341
+ f"Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change "
342
+ "the `--output_dir` or add `--overwrite_output_dir` to train from scratch."
343
+ )
344
+
345
+ # Set seed before initializing model.
346
+ set_seed(training_args.seed)
347
+
348
+ # 4. Load dataset
349
+ raw_datasets = IterableDatasetDict()
350
+
351
+ if training_args.do_train:
352
+ raw_datasets["train"] = load_streaming_dataset(
353
+ data_args.dataset_name,
354
+ data_args.dataset_config_name,
355
+ split=data_args.train_split_name,
356
+ use_auth_token=True if model_args.use_auth_token else None,
357
+ )
358
+
359
+ if training_args.do_eval:
360
+ raw_datasets["eval"] = load_streaming_dataset(
361
+ data_args.dataset_name,
362
+ data_args.dataset_config_name,
363
+ split=data_args.eval_split_name,
364
+ use_auth_token=True if model_args.use_auth_token else None,
365
+ )
366
+
367
+ raw_datasets_features = list(next(iter(raw_datasets.values())).features.keys())
368
+
369
+ if data_args.audio_column_name not in raw_datasets_features:
370
+ raise ValueError(
371
+ f"--audio_column_name '{data_args.audio_column_name}' not found in dataset '{data_args.dataset_name}'. "
372
+ "Make sure to set `--audio_column_name` to the correct audio column - one of "
373
+ f"{', '.join(raw_datasets_features)}."
374
+ )
375
+
376
+ if data_args.text_column_name not in raw_datasets_features:
377
+ raise ValueError(
378
+ f"--text_column_name {data_args.text_column_name} not found in dataset '{data_args.dataset_name}'. "
379
+ "Make sure to set `--text_column_name` to the correct text column - one of "
380
+ f"{', '.join(raw_datasets_features)}."
381
+ )
382
+
383
+ # 5. Load pretrained model, tokenizer, and feature extractor
384
+ #
385
+ # Distributed training:
386
+ # The .from_pretrained methods guarantee that only one local process can concurrently
387
+ config = AutoConfig.from_pretrained(
388
+ model_args.config_name if model_args.config_name else model_args.model_name_or_path,
389
+ cache_dir=model_args.cache_dir,
390
+ revision=model_args.model_revision,
391
+ use_auth_token=True if model_args.use_auth_token else None,
392
+ )
393
+
394
+ config.update({"forced_decoder_ids": model_args.forced_decoder_ids, "suppress_tokens": model_args.suppress_tokens})
395
+
396
+ feature_extractor = AutoFeatureExtractor.from_pretrained(
397
+ model_args.feature_extractor_name if model_args.feature_extractor_name else model_args.model_name_or_path,
398
+ cache_dir=model_args.cache_dir,
399
+ revision=model_args.model_revision,
400
+ use_auth_token=True if model_args.use_auth_token else None,
401
+ )
402
+ tokenizer = AutoTokenizer.from_pretrained(
403
+ model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path,
404
+ cache_dir=model_args.cache_dir,
405
+ use_fast=model_args.use_fast_tokenizer,
406
+ revision=model_args.model_revision,
407
+ use_auth_token=True if model_args.use_auth_token else None,
408
+ )
409
+ model = AutoModelForSpeechSeq2Seq.from_pretrained(
410
+ model_args.model_name_or_path,
411
+ config=config,
412
+ cache_dir=model_args.cache_dir,
413
+ revision=model_args.model_revision,
414
+ use_auth_token=True if model_args.use_auth_token else None,
415
+ )
416
+ model.config.use_cache = False
417
+
418
+ if model.config.decoder_start_token_id is None:
419
+ raise ValueError("Make sure that `config.decoder_start_token_id` is correctly defined")
420
+
421
+ if model_args.freeze_feature_encoder:
422
+ model.freeze_feature_encoder()
423
+
424
+ if model_args.freeze_encoder:
425
+ model.freeze_encoder()
426
+ model.model.encoder.gradient_checkpointing = False
427
+
428
+ if data_args.language is not None:
429
+ # We only need to set the task id when the language is specified (i.e. in a multilingual setting)
430
+ tokenizer.set_prefix_tokens(language=data_args.language, task=data_args.task)
431
+
432
+ # 6. Resample speech dataset if necessary
433
+ dataset_sampling_rate = next(iter(raw_datasets.values())).features[data_args.audio_column_name].sampling_rate
434
+ if dataset_sampling_rate != feature_extractor.sampling_rate:
435
+ raw_datasets = raw_datasets.cast_column(
436
+ data_args.audio_column_name, datasets.features.Audio(sampling_rate=feature_extractor.sampling_rate)
437
+ )
438
+
439
+ # 7. Preprocessing the datasets.
440
+ # We need to read the audio files as arrays and tokenize the targets.
441
+ max_input_length = data_args.max_duration_in_seconds * feature_extractor.sampling_rate
442
+ min_input_length = data_args.min_duration_in_seconds * feature_extractor.sampling_rate
443
+ audio_column_name = data_args.audio_column_name
444
+ text_column_name = data_args.text_column_name
445
+ model_input_name = feature_extractor.model_input_names[0]
446
+ do_lower_case = data_args.do_lower_case
447
+ do_remove_punctuation = data_args.do_remove_punctuation
448
+ normalizer = BasicTextNormalizer() # 'official' text normalizer from OpenAI
449
+
450
+ if data_args.max_train_samples is not None:
451
+ raw_datasets["train"] = raw_datasets["train"].take(data_args.max_train_samples)
452
+
453
+ if data_args.max_eval_samples is not None:
454
+ raw_datasets["eval"] = raw_datasets["eval"].take(data_args.max_eval_samples)
455
+
456
+ def prepare_dataset(batch):
457
+ # process audio
458
+ sample = batch[audio_column_name]
459
+ inputs = feature_extractor(sample["array"], sampling_rate=sample["sampling_rate"])
460
+ # process audio length
461
+ batch[model_input_name] = inputs.get(model_input_name)[0]
462
+ batch["input_length"] = len(sample["array"])
463
+
464
+ # process targets
465
+ input_str = batch[text_column_name].lower() if do_lower_case else batch[text_column_name]
466
+ if do_remove_punctuation:
467
+ input_str = normalizer(input_str).strip()
468
+ batch["labels"] = tokenizer(input_str).input_ids
469
+ return batch
470
+
471
+ with training_args.main_process_first(desc="dataset map pre-processing"):
472
+ vectorized_datasets = raw_datasets.map(
473
+ prepare_dataset,
474
+ remove_columns=raw_datasets_features,
475
+ ).with_format("torch")
476
+
477
+ if training_args.do_train:
478
+ vectorized_datasets["train"] = vectorized_datasets["train"].shuffle(
479
+ buffer_size=data_args.shuffle_buffer_size,
480
+ seed=training_args.seed,
481
+ )
482
+
483
+ # filter training data that is shorter than min_input_length or longer than
484
+ # max_input_length
485
+ def is_audio_in_length_range(length):
486
+ return min_input_length < length < max_input_length
487
+
488
+ vectorized_datasets["train"] = vectorized_datasets["train"].filter(
489
+ is_audio_in_length_range,
490
+ input_columns=["input_length"],
491
+ )
492
+
493
+ # 8. Load Metric
494
+ metric = evaluate.load("wer")
495
+ do_normalize_eval = data_args.do_normalize_eval
496
+
497
+ def compute_metrics(pred):
498
+ pred_ids = pred.predictions
499
+
500
+ pred.label_ids[pred.label_ids == -100] = tokenizer.pad_token_id
501
+
502
+ pred_str = tokenizer.batch_decode(pred_ids, skip_special_tokens=True)
503
+ # we do not want to group tokens when computing the metrics
504
+ label_str = tokenizer.batch_decode(pred.label_ids, skip_special_tokens=True)
505
+
506
+ if do_normalize_eval:
507
+ pred_str = [normalizer(pred) for pred in pred_str]
508
+ label_str = [normalizer(label) for label in label_str]
509
+
510
+ wer = 100 * metric.compute(predictions=pred_str, references=label_str)
511
+
512
+ return {"wer": wer}
513
+
514
+ # 9. Create a single speech processor
515
+ if is_main_process(training_args.local_rank):
516
+ # save feature extractor, tokenizer and config
517
+ feature_extractor.save_pretrained(training_args.output_dir)
518
+ tokenizer.save_pretrained(training_args.output_dir)
519
+ config.save_pretrained(training_args.output_dir)
520
+
521
+ processor = AutoProcessor.from_pretrained(training_args.output_dir)
522
+
523
+ # 10. Define data collator
524
+ data_collator = DataCollatorSpeechSeq2SeqWithPadding(
525
+ processor=processor,
526
+ decoder_start_token_id=model.config.decoder_start_token_id,
527
+ )
528
+
529
+ # 11. Configure Trainer
530
+ # Trainer callback to reinitialise and reshuffle the streamable datasets at the beginning of each epoch
531
+ class ShuffleCallback(TrainerCallback):
532
+ def on_epoch_begin(self, args, state, control, train_dataloader, **kwargs):
533
+ if isinstance(train_dataloader.dataset, IterableDatasetShard):
534
+ pass # set_epoch() is handled by the Trainer
535
+ elif isinstance(train_dataloader.dataset, IterableDataset):
536
+ train_dataloader.dataset.set_epoch(train_dataloader.dataset._epoch + 1)
537
+
538
+ # Initialize Trainer
539
+ trainer = Seq2SeqTrainer(
540
+ model=model,
541
+ args=training_args,
542
+ train_dataset=vectorized_datasets["train"] if training_args.do_train else None,
543
+ eval_dataset=vectorized_datasets["eval"] if training_args.do_eval else None,
544
+ tokenizer=feature_extractor,
545
+ data_collator=data_collator,
546
+ compute_metrics=compute_metrics if training_args.predict_with_generate else None,
547
+ callbacks=[ShuffleCallback()],
548
+ )
549
+
550
+ # 12. Training
551
+ if training_args.do_train:
552
+ checkpoint = None
553
+ if training_args.resume_from_checkpoint is not None:
554
+ checkpoint = training_args.resume_from_checkpoint
555
+ elif last_checkpoint is not None:
556
+ checkpoint = last_checkpoint
557
+ train_result = trainer.train(resume_from_checkpoint=checkpoint)
558
+ trainer.save_model() # Saves the feature extractor too for easy upload
559
+
560
+ metrics = train_result.metrics
561
+ if data_args.max_train_samples:
562
+ metrics["train_samples"] = data_args.max_train_samples
563
+ trainer.log_metrics("train", metrics)
564
+ trainer.save_metrics("train", metrics)
565
+ trainer.save_state()
566
+
567
+ # 13. Evaluation
568
+ results = {}
569
+ if training_args.do_eval:
570
+ logger.info("*** Evaluate ***")
571
+ metrics = trainer.evaluate(
572
+ metric_key_prefix="eval",
573
+ max_length=training_args.generation_max_length,
574
+ num_beams=training_args.generation_num_beams,
575
+ )
576
+ if data_args.max_eval_samples:
577
+ metrics["eval_samples"] = data_args.max_eval_samples
578
+
579
+ trainer.log_metrics("eval", metrics)
580
+ trainer.save_metrics("eval", metrics)
581
+
582
+ # 14. Write Training Stats
583
+ kwargs = {
584
+ "finetuned_from": model_args.model_name_or_path,
585
+ "tasks": "automatic-speech-recognition",
586
+ "tags": "whisper-event",
587
+ }
588
+ if data_args.dataset_name is not None:
589
+ kwargs["dataset_tags"] = data_args.dataset_name
590
+ if data_args.dataset_config_name is not None:
591
+ kwargs["dataset"] = f"{data_args.dataset_name} {data_args.dataset_config_name}"
592
+ else:
593
+ kwargs["dataset"] = data_args.dataset_name
594
+ if "common_voice" in data_args.dataset_name:
595
+ kwargs["language"] = data_args.dataset_config_name
596
+ if model_args.model_index_name is not None:
597
+ kwargs["model_name"] = model_args.model_index_name
598
+
599
+ if training_args.push_to_hub:
600
+ trainer.push_to_hub(**kwargs)
601
+ else:
602
+ trainer.create_model_card(**kwargs)
603
+
604
+ return results
605
+
606
+
607
+ if __name__ == "__main__":
608
+ main()
runs/Dec16_20-24-38_129-146-160-68/1671222292.263272/events.out.tfevents.1671222292.129-146-160-68.394631.1 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:bbb5de04b87d9d39bcbcf398bb0ea62df668dbfffa1e93e116c0513ed0eaf54d
3
+ size 5876
runs/Dec16_20-24-38_129-146-160-68/events.out.tfevents.1671222292.129-146-160-68.394631.0 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f6ca756f5e0cb3bbc0818998fbb6512f85a7c0ba932c38d7ca3098791e7daa5c
3
+ size 4272
runs/Dec16_20-26-39_129-146-160-68/1671222412.8615997/events.out.tfevents.1671222412.129-146-160-68.394809.1 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6217fe548e67929a91b1b4fe1fa5e22c30713b8bc554e0b54ec3847303a31974
3
+ size 5876
runs/Dec16_20-26-39_129-146-160-68/events.out.tfevents.1671222412.129-146-160-68.394809.0 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c84aa2cfe13290997faf976c65487b8b968b603c6d685898f9d7429884bf1a54
3
+ size 5670
runs/Dec16_21-21-11_129-146-160-68/1671226550.1156573/events.out.tfevents.1671226550.129-146-160-68.395790.1 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:95a0a3442849d1c71f5aba8be7a53374713edde84d6d2bb84388307070f3f284
3
+ size 5876
runs/Dec16_21-21-11_129-146-160-68/events.out.tfevents.1671226550.129-146-160-68.395790.0 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c359f30b1b4312d7c01d778968d2dc9a3af5e838c0fd9dde00998c3a8540f8c9
3
+ size 4272
runs/Dec16_21-57-02_129-146-160-68/1671227839.103308/events.out.tfevents.1671227839.129-146-160-68.396724.1 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8fa5523efc0511261b61eb93a79263f01cae0b061a92cc17a96ea76192e37014
3
+ size 5876
runs/Dec16_21-57-02_129-146-160-68/events.out.tfevents.1671227839.129-146-160-68.396724.0 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:345c8130fc74f3ee98e4e8a40d6ac1a5e9a128e9838441a92bddbc4021c8319c
3
+ size 10855
setup_env.sh ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ cd ~
2
+ sudo add-apt-repository -y ppa:jonathonf/ffmpeg-4
3
+ sudo apt update
4
+ sudo apt install -y ffmpeg
5
+ sudo apt-get install git-lfs
6
+ env_name=whisper
7
+ python3 -m venv $env_name
8
+ echo "source ~/$env_name/bin/activate" >> ~/.bashrc
9
+ cd whisper_sprint
10
+ bash
setup_jupyter.sh ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ pip install jupyterlab
2
+ python -m ipykernel install --user --name=whisper
3
+ tmux new -s mysession
4
+ jupyter lab --port 8888
setup_libs.sh ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ pip install -r requirements.txt
2
+ git lfs install
3
+ python -c "import torch; print(torch.cuda.is_available())"
4
+ git config --global credential.helper store
5
+ huggingface-cli login
6
+ huggingface-cli repo create $2
7
+ git clone https://huggingface.co/$1/$2
8
+ cd $2
9
+ cp ../**.py .
10
+ cp ../**.sh .
11
+ cp ../**.ipynb .
12
+ cp ../ds_config.json .
13
+ wget https://raw.githubusercontent.com/huggingface/community-events/main/whisper-fine-tuning-event/fine-tune-whisper-non-streaming.ipynb
setup_libs_colab.sh ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ pip install -r requirements_colab.txt
2
+ git lfs install
3
+ python -c "import torch; print(torch.cuda.is_available())"
4
+ git config --global credential.helper store
5
+ huggingface-cli login
6
+ huggingface-cli repo create $2
7
+ git clone https://huggingface.co/$1/$2
8
+ cd $2
9
+ cp ../**.py .
10
+ cp ../**.sh .
11
+ cp ../**.ipynb .
12
+ cp ../ds_config.js .
special_tokens_map.json ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "additional_special_tokens": [
3
+ "<|endoftext|>",
4
+ "<|startoftranscript|>",
5
+ "<|en|>",
6
+ "<|zh|>",
7
+ "<|de|>",
8
+ "<|es|>",
9
+ "<|ru|>",
10
+ "<|ko|>",
11
+ "<|fr|>",
12
+ "<|ja|>",
13
+ "<|pt|>",
14
+ "<|tr|>",
15
+ "<|pl|>",
16
+ "<|ca|>",
17
+ "<|nl|>",
18
+ "<|ar|>",
19
+ "<|sv|>",
20
+ "<|it|>",
21
+ "<|id|>",
22
+ "<|hi|>",
23
+ "<|fi|>",
24
+ "<|vi|>",
25
+ "<|iw|>",
26
+ "<|uk|>",
27
+ "<|el|>",
28
+ "<|ms|>",
29
+ "<|cs|>",
30
+ "<|ro|>",
31
+ "<|da|>",
32
+ "<|hu|>",
33
+ "<|ta|>",
34
+ "<|no|>",
35
+ "<|th|>",
36
+ "<|ur|>",
37
+ "<|hr|>",
38
+ "<|bg|>",
39
+ "<|lt|>",
40
+ "<|la|>",
41
+ "<|mi|>",
42
+ "<|ml|>",
43
+ "<|cy|>",
44
+ "<|sk|>",
45
+ "<|te|>",
46
+ "<|fa|>",
47
+ "<|lv|>",
48
+ "<|bn|>",
49
+ "<|sr|>",
50
+ "<|az|>",
51
+ "<|sl|>",
52
+ "<|kn|>",
53
+ "<|et|>",
54
+ "<|mk|>",
55
+ "<|br|>",
56
+ "<|eu|>",
57
+ "<|is|>",
58
+ "<|hy|>",
59
+ "<|ne|>",
60
+ "<|mn|>",
61
+ "<|bs|>",
62
+ "<|kk|>",
63
+ "<|sq|>",
64
+ "<|sw|>",
65
+ "<|gl|>",
66
+ "<|mr|>",
67
+ "<|pa|>",
68
+ "<|si|>",
69
+ "<|km|>",
70
+ "<|sn|>",
71
+ "<|yo|>",
72
+ "<|so|>",
73
+ "<|af|>",
74
+ "<|oc|>",
75
+ "<|ka|>",
76
+ "<|be|>",
77
+ "<|tg|>",
78
+ "<|sd|>",
79
+ "<|gu|>",
80
+ "<|am|>",
81
+ "<|yi|>",
82
+ "<|lo|>",
83
+ "<|uz|>",
84
+ "<|fo|>",
85
+ "<|ht|>",
86
+ "<|ps|>",
87
+ "<|tk|>",
88
+ "<|nn|>",
89
+ "<|mt|>",
90
+ "<|sa|>",
91
+ "<|lb|>",
92
+ "<|my|>",
93
+ "<|bo|>",
94
+ "<|tl|>",
95
+ "<|mg|>",
96
+ "<|as|>",
97
+ "<|tt|>",
98
+ "<|haw|>",
99
+ "<|ln|>",
100
+ "<|ha|>",
101
+ "<|ba|>",
102
+ "<|jw|>",
103
+ "<|su|>",
104
+ "<|translate|>",
105
+ "<|transcribe|>",
106
+ "<|startoflm|>",
107
+ "<|startofprev|>",
108
+ "<|nocaptions|>",
109
+ "<|notimestamps|>"
110
+ ],
111
+ "bos_token": {
112
+ "content": "<|endoftext|>",
113
+ "lstrip": false,
114
+ "normalized": true,
115
+ "rstrip": false,
116
+ "single_word": false
117
+ },
118
+ "eos_token": {
119
+ "content": "<|endoftext|>",
120
+ "lstrip": false,
121
+ "normalized": true,
122
+ "rstrip": false,
123
+ "single_word": false
124
+ },
125
+ "pad_token": "<|endoftext|>",
126
+ "unk_token": {
127
+ "content": "",
128
+ "lstrip": false,
129
+ "normalized": true,
130
+ "rstrip": false,
131
+ "single_word": false
132
+ }
133
+ }
split_mgb2_test.py ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import soundfile as sf
2
+ import os
3
+
4
+ os.makedirs("dataset", exist_ok=True)
5
+ archive_path = "test"
6
+ wav_dir = os.path.join(archive_path, "wav")
7
+ segments_file = os.path.join(archive_path, "text.all")
8
+ with open(segments_file, "r", encoding="utf-8") as f:
9
+ for _id, line in enumerate(f):
10
+ segment = line.split(" ")[0]
11
+ text = " ".join(line.split(" ")[1:])
12
+ wav_name, _, time = segment.split("_")
13
+ time = time.replace("seg-", "")
14
+ start, stop = time.split(":")
15
+ start = int(int(start) / 100 * 16_000)
16
+ stop = int(int(stop) / 100 * 16_000)
17
+ wav_path = os.path.join(wav_dir, wav_name + ".wav")
18
+ sound, _ = sf.read(wav_path, start=start, stop=stop)
19
+ sf.write(f"dataset/{segment}.wav", sound, 16_000)
20
+ open(f"dataset/{segment}.txt", "w").write(text)