File size: 34,120 Bytes
7934b29
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "bd9c257a",
   "metadata": {},
   "source": [
    "Instructions for setting up Colab are as follows:\n",
    "1. Open a new Python 3 notebook.\n",
    "2. Import this notebook from GitHub (File -> Upload Notebook -> \"GITHUB\" tab -> copy/paste GitHub URL)\n",
    "3. Connect to an instance with a GPU (Runtime -> Change runtime type -> select \"GPU\" for hardware accelerator)\n",
    "4. Run this cell to set up dependencies.\n",
    "5. Restart the runtime (Runtime -> Restart Runtime) for any upgraded packages to take effect"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0075e98c",
   "metadata": {},
   "source": [
    "# Data Preprocessing & Cleaning for NMT\n",
    "\n",
    "This notebook contains a tutorial of data processing and cleaning for NMT (Neural Machine Translation) to train translation models with the [NeMo framework](https://github.com/NVIDIA/NeMo).\n",
    "\n",
    "A pre-requisite to train supervised neural machine translation systems is the availability of *parallel corpora* of reasonable quality.\n",
    "\n",
    "A parallel corpus is a collection of sentences or documents that are translations of each other in 2 or more languages.\n",
    "\n",
    "For example,\n",
    "\n",
    "| English                                                                            | Russian |\n",
    "| :-: | :-: |\n",
    "| To date, a total of 43 participants from 15 countries have completed the training. | К настоящему времени подготовку прошли в общей сложности 43 участника из 15 стран . |\n",
    "| M-Sport Bentley writes a new piece of Bentley history at Silverstone | M-Sport Bentley открывает новую страницу в истории Bentley в Сильверстоуне |\n",
    "| Information in the application was not true. | Информация в заявлении не была достоверна. |\n",
    "\n",
    "This notebook will cover the following data pre-processing and data cleaning techniques for such corpora.\n",
    "\n",
    "## The importance of data cleaning\n",
    "\n",
    "The presence of noise in the training dataset can adversely affect model quality (https://arxiv.org/abs/1805.12282). Webcrawled and automatically aligned data sources in particular, such as [Paracrawl](https://paracrawl.eu/), [WikiMatrix](https://arxiv.org/abs/1907.05791), [CC-Aligned](https://arxiv.org/abs/1911.06154) and [CC-Matrix](https://arxiv.org/abs/1911.04944) can be extremely noisy.\n",
    "\n",
    "## Cleaning\n",
    "1. Downloading and filtering publicly available datasets based on confidence thresholds (if available). For example, [WikiMatrix](https://arxiv.org/abs/1907.05791) filtering based on [LASER](https://arxiv.org/abs/1812.10464) confidence scores.\n",
    "2. Language ID filtering using a pre-trained [fastText classifier](https://fasttext.cc/docs/en/language-identification.html). This step will remove all sentences from the parallel corpus that our classifier predicts as not being in the appropriate language (ex: sentences in the English column that aren't in English or sentences in Russian column that aren't in Russian).\n",
    "3. Length and Length-ratio filtering. This steps removes all sentences that are 1) too long 2) too short or 3) have a ratio between their lengths greater than a certain factor (this typically removes partial translations).\n",
    "4. [Bicleaner](https://github.com/bitextor/bicleaner) classifier-based cleaning. Bicleaner identifies noisy parallel sentences using a classifier that leverages multiple features such as n-gram language model likelihood scores, word alignment scores and other heuristics.\n",
    "\n",
    "## Pre-processing\n",
    "5. [Moses Punctuation Normalization](https://github.com/moses-smt/mosesdecoder/blob/master/scripts/tokenizer/normalize-punctuation.perl). This step standardizes punctuation. For example the less common way to write apostrophes Tiffany`s will be standardized to Tiffany's.\n",
    "6. Unicode standardization. There exist some unicode characters that aren't punctuation that need to be standardized for example, this step normalizes the number 4 to 4.\n",
    "7. [Moses Tokenization](https://github.com/moses-smt/mosesdecoder/blob/master/scripts/tokenizer/tokenizer.perl) or text segmentation for Chinese/Japanese with [Jieba](https://github.com/fxsjy/jieba) and [mecab](https://github.com/taku910/mecab). For languages like Chinese and Japanese that do not have explicit word segmentation markers (like spaces), we use these tools to introduce spaces into the text that will let us split the string into words. For other languages, we use Moses to separate punctuation markers from words so that they become separate tokens.\n",
    "8. Deduplication - This step removes duplicate translation pairs from the corpus.\n",
    "9. Shuffling - This step shuffles the order of occurrence of translation pairs.\n",
    "\n",
    "## Tarred Datasets for Large Corpora\n",
    "10. Large datasets with over 50M sentence pairs when batched and pickled can be up to 60GB in size. Loading them entirely into CPU memory when using say 8 or 16 workers with DistributedDataParallel training uses 480-960GB of RAM which is often impractical and inefficient. Instead, we use [Webdataset](https://github.com/webdataset/webdataset) to allow training while keeping datasets on disk and let webddataset handle pre-loading and fetching of data into CPU RAM.\n",
    "\n",
    "\n",
    "## Disclaimer\n",
    "\n",
    "The data cleaning techniques used in this notebook are only meant to be loose guidelines and are not guaranteed to produced clean parallel corpora at the end of it. Not all of these steps are a necessity for every dataset, "
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bb0eb698",
   "metadata": {},
   "source": [
    "![NMT Data Pipeline](images/nmt_data_pipeline.png)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4a9fd8d3",
   "metadata": {},
   "source": [
    "# Downloading Publicly Available Data\n",
    "\n",
    "## WikiMatrix (https://arxiv.org/abs/1907.05791)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "78984523",
   "metadata": {},
   "outputs": [],
   "source": [
    "!mkdir -p data\n",
    "print('Downloading data ...')\n",
    "!wget https://dl.fbaipublicfiles.com/laser/WikiMatrix/v1/WikiMatrix.en-ru.tsv.gz -O data/WikiMatrix.en-ru.tsv.gz\n",
    "print('---------------------')\n",
    "print('Unzipping file ...')\n",
    "!gunzip -k -f data/WikiMatrix.en-ru.tsv.gz\n",
    "print('---------------------')\n",
    "print('Peek into the file')\n",
    "!head -10 data/WikiMatrix.en-ru.tsv\n",
    "print('---------------------')\n",
    "print('File length ...')\n",
    "!wc -l data/WikiMatrix.en-ru.tsv\n",
    "print('---------------------')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b9a62f9e",
   "metadata": {},
   "source": [
    "## Filter Based on LASER Confidence\n",
    "\n",
    "LASER (https://arxiv.org/abs/1812.10464) is a multi-lingual neural sentence embedding model that is often used for cross-lingual sentence/document retrieval. Similarities in the embedding space are often used as proxies for cross-lingual similarities."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "21608388",
   "metadata": {},
   "outputs": [],
   "source": [
    "from tqdm import tqdm\n",
    "import numpy as np\n",
    "\n",
    "def num_lines_in_file(fname):\n",
    "    \"\"\"\n",
    "    Returns the number of lines in a file.\n",
    "    \"\"\"\n",
    "    with open(fname, 'r') as f:\n",
    "        for i, _ in enumerate(f):\n",
    "            pass\n",
    "    return i + 1\n",
    "\n",
    "def filter_tsv_with_conf(\n",
    "    input_file, output_file_lang_1, output_file_lang_2,\n",
    "    confidence_threshold=None, confidence_column=None\n",
    "):\n",
    "    \"\"\"\n",
    "    Filters a tsv file that has confidence scores associated with each parallel example.\n",
    "\n",
    "    For example:\n",
    "\n",
    "    1.23 \\t This is a sentence in lang1 \\t This is a sentence in lang2\n",
    "    \"\"\"\n",
    "    print()\n",
    "    print('====================================')\n",
    "    print('======= TSV Conf Filtering =========')\n",
    "    print('====================================')\n",
    "    print()\n",
    "    num_lines = num_lines_in_file(input_file)\n",
    "    scores = []\n",
    "    num_output_lines = 0\n",
    "    lang_1_col = 0\n",
    "    lang_2_col = 1\n",
    "    with open(input_file, 'r') as f, \\\n",
    "        open(output_file_lang_1, 'w') as f_out_1, \\\n",
    "        open(output_file_lang_2, 'w') as f_out_2:\n",
    "        for line in tqdm(f, total=num_lines, desc=f\"Filtering file by confidence {confidence_threshold}\"):\n",
    "            if line.strip() == '':\n",
    "                continue\n",
    "            line = line.strip().split('\\t')\n",
    "            if len(line) < 2:\n",
    "                continue\n",
    "            if confidence_threshold is not None and float(line[confidence_column]) < confidence_threshold:\n",
    "                continue\n",
    "            else:\n",
    "                if confidence_threshold is not None:\n",
    "                    scores.append(float(line[confidence_column]))\n",
    "                    if confidence_column == 0:\n",
    "                        lang_1_col, lang_2_col = 1, 2\n",
    "                    elif confidence_column == 2:\n",
    "                        lang_1_col, lang_2_col = 0, 1\n",
    "                    elif confidence_column == 1:\n",
    "                        lang_1_col, lang_2_col = 0, 2\n",
    "                    else:\n",
    "                        raise ValueError(f\"Invalid Column for confidence {confidence_column}\")\n",
    "                f_out_1.write(line[lang_1_col] + '\\n')\n",
    "                f_out_2.write(line[lang_2_col] + '\\n')\n",
    "                num_output_lines += 1\n",
    "\n",
    "    if confidence_threshold is not None:\n",
    "        print(f'Confidence score average  : {np.mean(scores)}')\n",
    "        print(f'Confidence score variance : {np.var(scores)}')\n",
    "        print(f'Kept {num_output_lines} out of {num_lines} after conversion ({(num_output_lines / num_lines) * 100}%)')\n",
    "        print('====================================')\n",
    "\n",
    "filter_tsv_with_conf(\n",
    "    'data/WikiMatrix.en-ru.tsv',\n",
    "    'data/WikiMatrix.en-ru.en', \n",
    "    'data/WikiMatrix.en-ru.ru',\n",
    "    confidence_threshold=1.04, confidence_column=0\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "18a171d1",
   "metadata": {},
   "source": [
    "## Language ID filtering with fastText\n",
    "\n",
    "Noisy parallel corpora often contain sentences that are not in the intended language. A classifier that determines the language in which a sentence is written can be used to filter out sentences that aren't in the appropriate language."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d58b7148",
   "metadata": {},
   "outputs": [],
   "source": [
    "!wget https://dl.fbaipublicfiles.com/fasttext/supervised-models/lid.176.bin -O data/lid.176.bin\n",
    "print()\n",
    "print('====================================')\n",
    "print('====== Language ID Filtering =======')\n",
    "print('====================================')\n",
    "print()\n",
    "\n",
    "\n",
    "!wget https://raw.github.com/NVIDIA/NeMo/main/scripts/neural_machine_translation/filter_langs_nmt.py \\\n",
    "    -O filter_langs_nmt.py\n",
    "\n",
    "!python filter_langs_nmt.py \\\n",
    "    --input-src data/WikiMatrix.en-ru.en  \\\n",
    "    --input-tgt data/WikiMatrix.en-ru.ru \\\n",
    "    --output-src data/WikiMatrix.en-ru.langidfilter.en  \\\n",
    "    --output-tgt data/WikiMatrix.en-ru.langidfilter.ru  \\\n",
    "    --source-lang en \\\n",
    "    --target-lang ru \\\n",
    "    --removed-src data/WikiMatrix.en-ru.langidfilter.removed.en  \\\n",
    "    --removed-tgt data/WikiMatrix.en-ru.langidfilter.removed.ru  \\\n",
    "    --fasttext-model data/lid.176.bin\n",
    "\n",
    "print()\n",
    "print('-----------------------------------------')\n",
    "print('Number of removed sentences:')\n",
    "print('-----------------------------------------')\n",
    "print()\n",
    "!wc -l data/WikiMatrix.en-ru.langidfilter.removed.ru\n",
    "\n",
    "print()\n",
    "print('-----------------------------------------')\n",
    "print('Examples of removed sentences')\n",
    "print('-----------------------------------------')\n",
    "print()\n",
    "\n",
    "!paste -d \"\\t\" \\\n",
    "    data/WikiMatrix.en-ru.langidfilter.removed.en \\\n",
    "    data/WikiMatrix.en-ru.langidfilter.removed.ru \\\n",
    "    | head -10\n",
    "print('-----------------------------------------')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ffb42e92",
   "metadata": {},
   "source": [
    "## Length and Ratio Filtering\n",
    "\n",
    "This step filters out sentences based on their lengths and the ratio between source and target lengths. If (a) src_len / tgt_len or tgt_len / src_len exceed 1.3 or (b) source or target sequence lengths are less than 1 or greater than 250, the sentence pair will be removed."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "52ff172a",
   "metadata": {},
   "outputs": [],
   "source": [
    "!git clone https://github.com/moses-smt/mosesdecoder data/mosesdecoder\n",
    "!cd data/mosesdecoder && git checkout RELEASE-4.0 && cd ../..\n",
    "!perl data/mosesdecoder/scripts/training/clean-corpus-n.perl -ratio 1.3 \\\n",
    "    data/WikiMatrix.en-ru.langidfilter \\\n",
    "    en ru \\\n",
    "    data/WikiMatrix.en-ru.langidfilter.lengthratio \\\n",
    "    1 250"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "28de44eb",
   "metadata": {},
   "source": [
    "<font color='red'>THE FOLLOWING CELLS REQUIRE THE INSTALLATION OF BICLEANER, WHICH REQUIRES COMPILING PACKAGES FROM SOURCE AND IS TRICKY TO GET WORKING INSIDE THIS CONTAINER. PLEASE INSTALL BICLEANER FROM THE REPOSITORY - https://github.com/bitextor/bicleaner OR FOLLOW INSTRUCTIONS BELOW. CELLS FOLLOWING THIS WILL NOT RUN IF BICLEANER IS NOT INSTALLED.</font>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4ea62d2c",
   "metadata": {},
   "source": [
    "You can run either this notebook locally (if you have all the dependencies and a GPU) or on Google Colab.\n",
    "\n",
    "## Install dependencies\n",
    "\n",
    "!pip install wget\n",
    "!apt-get install libboost-all-dev\n",
    "!apt-get install gawk\n",
    "\n",
    "## Install NeMo\n",
    "\n",
    "BRANCH = 'r1.17.0'\n",
    "!python -m pip install git+https://github.com/NVIDIA/NeMo.git@$BRANCH#egg=nemo_toolkit[all]\n",
    "\n",
    "!pip uninstall -y sacrebleu\n",
    "!pip install sacrebleu[ja]\n",
    "!pip install xxhash\n",
    "\n",
    "## Install kenlm with 7-gram support\n",
    "!mkdir -p data\n",
    "!rm -rf data/kenlm\n",
    "!git clone https://github.com/kpu/kenlm data/kenlm\n",
    "!cd data/kenlm \\\n",
    "    && pip install . --install-option=\"--max_order 7\" \\\n",
    "    && mkdir -p build \\\n",
    "    && cd build \\\n",
    "    && cmake .. -DKENLM_MAX_ORDER=7 -DCMAKE_INSTALL_PREFIX:PATH=../../kenlm_install \\\n",
    "    && make -j all install && cd ../../kenlm_install \\\n",
    "    && export PATH=$PATH:$PWD\n",
    "\n",
    "# Install bicleaner\n",
    "\n",
    "!pip install bicleaner"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f3c0cf69",
   "metadata": {},
   "outputs": [],
   "source": [
    "try:\n",
    "    import bicleaner\n",
    "except ImportError:\n",
    "    raise ImportError(f\"You need to install Bicleaner to proceed. Could not import the bicleaner package.\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "01f2b589",
   "metadata": {},
   "source": [
    "## Bicleaner Filtering\n",
    "\n",
    "Bicleaner (https://aclanthology.org/W18-6488/ and https://aclanthology.org/2020.eamt-1.31/) is a tool to identify noisy parallel sentences in translation corpora. It applies 3 different filtering steps:\n",
    "\n",
    "1. Pre-filtering based on 37 rules.\n",
    "2. Language model fluency scores based on n-gram language models trained with kenlm.\n",
    "3. Random forest classifier that uses all examples filtered out in steps 1 & 2 as \"negative\" examples."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9be8d4ca",
   "metadata": {},
   "outputs": [],
   "source": [
    "print('Downloading En-Ru Bicleaner models.')\n",
    "!git clone https://github.com/bitextor/bicleaner data/bicleaner\n",
    "!cd data/bicleaner && git checkout bicleaner-0.15 && cd ../..\n",
    "!data/bicleaner/utils/download-pack.sh en ru\n",
    "\n",
    "print('Generating Bicleaner scores ...')\n",
    "!gawk '{{print \"-\\t-\"}}' \\\n",
    "    data/WikiMatrix.en-ru.langidfilter.lengthratio.en | \\\n",
    "    paste -d \"\\t\" - data/WikiMatrix.en-ru.langidfilter.lengthratio.en \\\n",
    "    data/WikiMatrix.en-ru.langidfilter.lengthratio.ru | \\\n",
    "    bicleaner-classify - - en-ru/en-ru.yaml \\\n",
    "    > data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.scores"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "43059b8a",
   "metadata": {},
   "outputs": [],
   "source": [
    "print('Score file ...')\n",
    "!head -10 data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.scores\n",
    "\n",
    "print()\n",
    "print('-----------------------------------------')\n",
    "print('Filtering based on Bicleaner scores > 0.6 ...')\n",
    "print('-----------------------------------------')\n",
    "print()\n",
    "\n",
    "print('Filtering out English ...')\n",
    "!gawk -F \"\\t\" '{if ($5>0.6) {print $3}}' \\\n",
    "    data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.scores > \\\n",
    "    data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.en\n",
    "\n",
    "print('Filtering out Russian ...')\n",
    "!gawk -F \"\\t\" '{if ($5>0.6) {print $4}}' \\\n",
    "    data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.scores > \\\n",
    "    data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.ru\n",
    "\n",
    "!paste -d \"\\t\" \\\n",
    "    data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.en \\\n",
    "    data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.ru \\\n",
    "    | head -10"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0726510c",
   "metadata": {},
   "source": [
    "## Normalize Punctuation\n",
    "\n",
    "Punctuation can vary across languages and even between ascii and unicode variants of the same punctuation marker. For example, across languages. For example, in German, quotes are often written as „ and “ while in English we typically just use \". This step normalizes such punctuation differences to use the same character everywhere.\n",
    "\n",
    "We use [moses](https://github.com/moses-smt/mosesdecoder) or [sacremoses](https://github.com/alvations/sacremoses) to normalize punctuation. The moses implementation is in perl while sacremoses is in python with a CLI interface. The perl implementation is buffered and works better for large corpora that may not fit into CPU memory all at once while sacremoses is unbuffered and multi-processed."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e73670d6",
   "metadata": {},
   "source": [
    "### Sacremoses"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "597e041a",
   "metadata": {},
   "outputs": [],
   "source": [
    "print('Normalizing English ...')\n",
    "!sacremoses -j 4 normalize \\\n",
    "    < data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.en > \\\n",
    "    data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.sacremoses.norm.en\n",
    "\n",
    "print('Normalizing Russian ...')\n",
    "!sacremoses -j 4 normalize \\\n",
    "    < data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.ru > \\\n",
    "    data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.sacremoses.norm.ru\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "240b0a1f",
   "metadata": {},
   "source": [
    "## Moses\n",
    "\n",
    "Punctuation can vary across languages and even between ascii and unicode variants of the same punctuation marker. For example, across languages. For example, in German, quotes are often written as „ and “ while in English we typically just use \". This step normalizes such punctuation differences to use the same character everywhere.\n",
    "\n",
    "We use [moses](https://github.com/moses-smt/mosesdecoder) or [sacremoses](https://github.com/alvations/sacremoses) to normalize punctuation. The moses implementation is in perl while sacremoses is in python with a CLI interface. The perl implementation is buffered and works better for large corpora that may not fit into CPU memory all at once while sacremoses is unbuffered and multi-processed."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1f5adaa4",
   "metadata": {},
   "outputs": [],
   "source": [
    "print('Normalizing English ...')\n",
    "!perl data/mosesdecoder/scripts/tokenizer/normalize-punctuation.perl -l en \\\n",
    "    < data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.en > \\\n",
    "    data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.moses.norm.en\n",
    "\n",
    "print('Normalizing Russian ...')\n",
    "!perl data/mosesdecoder/scripts/tokenizer/normalize-punctuation.perl -l ru \\\n",
    "    < data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.ru > \\\n",
    "    data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.moses.norm.ru\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b8bfad64",
   "metadata": {},
   "source": [
    "## Tokenize\n",
    "\n",
    "Tokenization splits a string into a sequence of tokens. A naive way of doing this would be to simply split the string on spaces (for languages where this is possible). This however, will result in punctuation being \"attached\" to the neighboring word when tokenizing. For example, \n",
    "\n",
    "\"This is a sentence.\" will be tokenized as [\"This, is, a, sentence.\"].\n",
    "\n",
    "However, we'd typically like punctuation to be separate tokens for example,\n",
    "\n",
    "\"This is a sentence.\" will be tokenized my moses or sacremoses as [\", This, is, a, sentence, ., \"]."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "06c60b90",
   "metadata": {},
   "source": [
    "### Sacremoses"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7bb4c631",
   "metadata": {},
   "outputs": [],
   "source": [
    "print('Tokenizing English ...')\n",
    "!sacremoses -j 4 -l en tokenize -x \\\n",
    "    < data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.sacremoses.norm.en > \\\n",
    "    data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.sacremoses.norm.tok.en\n",
    "\n",
    "print('Tokenizing Russian ...')\n",
    "!sacremoses -j 4 -l ru tokenize -x \\\n",
    "    < data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.sacremoses.norm.ru > \\\n",
    "    data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.sacremoses.norm.tok.ru\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "444bebd7",
   "metadata": {},
   "source": [
    "### Moses"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "21333e27",
   "metadata": {},
   "outputs": [],
   "source": [
    "print('Tokenizing English ...')\n",
    "!perl data/mosesdecoder/scripts/tokenizer/tokenizer.perl -l en -no-escape -threads 4 \\\n",
    "    < data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.moses.norm.en > \\\n",
    "    data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.moses.norm.tok.en\n",
    "\n",
    "print('Tokenizing Russian ...')\n",
    "!perl data/mosesdecoder/scripts/tokenizer/tokenizer.perl -l ru -no-escape -threads 4 \\\n",
    "    < data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.moses.norm.ru > \\\n",
    "    data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.moses.norm.tok.ru\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b28df2bb",
   "metadata": {},
   "outputs": [],
   "source": [
    "print()\n",
    "print('-----------------------------------------')\n",
    "print('Tokenized Russian Sentences ...')\n",
    "print('-----------------------------------------')\n",
    "print()\n",
    "\n",
    "!head -10 data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.moses.norm.tok.ru\n",
    "\n",
    "print()\n",
    "print('-----------------------------------------')\n",
    "print('Tokenized English Sentences ...')\n",
    "print('-----------------------------------------')\n",
    "print()\n",
    "\n",
    "!head -10 data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.moses.norm.tok.en"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "dee5409d",
   "metadata": {},
   "source": [
    "## Segmenting Chinese and Japanese\n",
    "\n",
    "### Jieba segmentation for Chinese"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "41b4cc91",
   "metadata": {},
   "outputs": [],
   "source": [
    "import jieba\n",
    "\n",
    "!wget https://dl.fbaipublicfiles.com/laser/WikiMatrix/v1/WikiMatrix.en-zh.tsv.gz -O data/WikiMatrix.en-zh.tsv.gz\n",
    "!gunzip -k -f data/WikiMatrix.en-zh.tsv.gz\n",
    "\n",
    "print()\n",
    "print('-----------------------------------------')\n",
    "print('Chinese text before segmentation ...')\n",
    "print('-----------------------------------------')\n",
    "print()\n",
    "\n",
    "!awk -F \"\\t\" '{print $3}' data/WikiMatrix.en-zh.tsv | head -10\n",
    "print()\n",
    "print('-----------------------------------------')\n",
    "print('Segmenting Chinese text ...')\n",
    "print('-----------------------------------------')\n",
    "print()\n",
    "\n",
    "zh_lines = []\n",
    "with open('data/WikiMatrix.en-zh.tsv', 'r') as f:\n",
    "    for idx, line in enumerate(f):\n",
    "        line = line.strip().split('\\t')[2]\n",
    "        zh_lines.append(' '.join(jieba.cut(line)))\n",
    "        if idx == 100:\n",
    "            break\n",
    "print()\n",
    "print('-----------------------------------------')\n",
    "print('Chinese text after segmentation ...')\n",
    "print('\\n'.join(zh_lines[:10]))\n",
    "print('-----------------------------------------')\n",
    "print()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "489bd915",
   "metadata": {},
   "outputs": [],
   "source": [
    "import MeCab\n",
    "import ipadic\n",
    "\n",
    "!wget https://dl.fbaipublicfiles.com/laser/WikiMatrix/v1/WikiMatrix.en-ja.tsv.gz -O data/WikiMatrix.en-ja.tsv.gz\n",
    "!gunzip -k -f data/WikiMatrix.en-ja.tsv.gz\n",
    "\n",
    "print()\n",
    "print('-----------------------------------------')\n",
    "print('Japanese text before segmentation ...')\n",
    "print('-----------------------------------------')\n",
    "print()\n",
    "\n",
    "!awk -F \"\\t\" '{print $3}' data/WikiMatrix.en-ja.tsv | head -10\n",
    "\n",
    "print()\n",
    "print('-----------------------------------------')\n",
    "print('Segmenting Japanese text ...')\n",
    "print('-----------------------------------------')\n",
    "print()\n",
    "\n",
    "mecab_tokenizer = MeCab.Tagger(ipadic.MECAB_ARGS + \" -Owakati\")\n",
    "\n",
    "ja_lines = []\n",
    "with open('data/WikiMatrix.en-ja.tsv', 'r') as f:\n",
    "    for idx, line in enumerate(f):\n",
    "        line = line.strip().split('\\t')[2]\n",
    "        ja_lines.append(mecab_tokenizer.parse(line))\n",
    "        if idx == 100:\n",
    "            break\n",
    "print()\n",
    "print('-----------------------------------------')\n",
    "print('Japanese text after segmentation ...')\n",
    "print('\\n'.join(ja_lines[:10]))\n",
    "print('-----------------------------------------')\n",
    "print()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4a079efe",
   "metadata": {},
   "source": [
    "## Deduplicate"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "55d98bf3",
   "metadata": {},
   "outputs": [],
   "source": [
    "import xxhash\n",
    "\n",
    "def dedup_file(input_file_lang_1, input_file_lang_2, output_file_lang_1, output_file_lang_2):\n",
    "    print()\n",
    "    print('====================================')\n",
    "    print('========== De-duplicate ============')\n",
    "    print('====================================')\n",
    "    print()\n",
    "    num_lines = num_lines_in_file(input_file_lang_1)\n",
    "    hashes = set()\n",
    "    num_output_lines = 0\n",
    "    with open(input_file_lang_1, 'r') as f_lang1, \\\n",
    "        open(input_file_lang_2, 'r')  as f_lang2, \\\n",
    "        open(output_file_lang_1, 'w') as f_out_lang1, \\\n",
    "        open(output_file_lang_2, 'w') as f_out_lang2:\n",
    "        for line_1, line_2 in tqdm(zip(f_lang1, f_lang2), total=num_lines, desc=f\"Deduplicating files\"):\n",
    "            parallel_hash = xxhash.xxh64((line_1.strip() + '\\t' + line_2.strip()).encode('utf-8')).hexdigest()\n",
    "            if parallel_hash not in hashes:\n",
    "                hashes.add(parallel_hash)\n",
    "                f_out_lang1.write(line_1.strip() + '\\n')\n",
    "                f_out_lang2.write(line_2.strip() + '\\n')\n",
    "                num_output_lines += 1\n",
    "\n",
    "    print(f\"Kept {num_output_lines} out of {num_lines} after deduplication\")\n",
    "\n",
    "dedup_file(\n",
    "    'data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.moses.norm.tok.en',\n",
    "    'data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.moses.norm.tok.ru',\n",
    "    'data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.moses.norm.tok.dedup.en',\n",
    "    'data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.moses.norm.tok.dedup.ru'\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "da4c181a",
   "metadata": {},
   "source": [
    "## Shuffle"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "413734bd",
   "metadata": {},
   "outputs": [],
   "source": [
    "!shuf --random-source=data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.moses.norm.tok.dedup.en \\\n",
    "    data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.moses.norm.tok.dedup.en > \\\n",
    "    data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.moses.norm.tok.dedup.shuf.en\n",
    "\n",
    "!shuf --random-source=data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.moses.norm.tok.dedup.en \\\n",
    "    data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.moses.norm.tok.dedup.ru > \\\n",
    "    data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.moses.norm.tok.dedup.shuf.ru\n",
    "\n",
    "!paste -d \"\\t\" \\\n",
    "    data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.moses.norm.tok.dedup.shuf.en \\\n",
    "    data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.moses.norm.tok.dedup.shuf.ru \\\n",
    "    | head -10"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5f3b3640",
   "metadata": {},
   "outputs": [],
   "source": [
    "!rm -rf data/tarred_dataset_en_ru_8k_tokens"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "844a9f26",
   "metadata": {},
   "source": [
    "## Tarred Dataset Creation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2b045df5",
   "metadata": {},
   "outputs": [],
   "source": [
    "!wget https://raw.github.com/NVIDIA/NeMo/main/examples/nlp/machine_translation/create_tarred_parallel_dataset.py \\\n",
    "    -O create_tarred_parallel_dataset.py\n",
    "\n",
    "!python create_tarred_parallel_dataset.py \\\n",
    "    --src_fname data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.moses.norm.tok.dedup.shuf.en \\\n",
    "    --tgt_fname data/WikiMatrix.en-ru.langidfilter.lengthratio.bicleaner.60.moses.norm.tok.dedup.shuf.ru \\\n",
    "    --out_dir data/tarred_dataset_en_ru_8k_tokens \\\n",
    "    --clean \\\n",
    "    --encoder_tokenizer_name yttm \\\n",
    "    --encoder_tokenizer_vocab_size 32000 \\\n",
    "    --encoder_tokenizer_coverage 0.999 \\\n",
    "    --encoder_tokenizer_bpe_dropout 0.1 \\\n",
    "    --decoder_tokenizer_name yttm \\\n",
    "    --decoder_tokenizer_vocab_size 32000 \\\n",
    "    --decoder_tokenizer_coverage 0.999 \\\n",
    "    --decoder_tokenizer_bpe_dropout 0.1 \\\n",
    "    --max_seq_length 512 \\\n",
    "    --min_seq_length 1 \\\n",
    "    --tokens_in_batch 8000 \\\n",
    "    --lines_per_dataset_fragment 100000 \\\n",
    "    --num_batches_per_tarfile 20\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "990265e5",
   "metadata": {},
   "outputs": [],
   "source": [
    "!ls data/tarred_dataset_en_ru_8k_tokens"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cc5e123b",
   "metadata": {},
   "outputs": [],
   "source": [
    "!cat data/tarred_dataset_en_ru_8k_tokens/metadata.tokens.8000.json"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.13"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}