Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

preprocess.py 7.3 KB

You have to be logged in to leave a comment. Sign In
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
  1. #!/usr/bin/env python3
  2. # Copyright (c) 2017-present, Facebook, Inc.
  3. # All rights reserved.
  4. #
  5. # This source code is licensed under the license found in the LICENSE file in
  6. # the root directory of this source tree. An additional grant of patent rights
  7. # can be found in the PATENTS file in the same directory.
  8. #
  9. import argparse
  10. from itertools import zip_longest
  11. import os
  12. import shutil
  13. from fairseq import dictionary, indexed_dataset
  14. from fairseq.tokenizer import Tokenizer
  15. def main():
  16. parser = argparse.ArgumentParser(
  17. description='Data pre-processing: Create dictionary and store data in binary format')
  18. parser.add_argument('-s', '--source-lang', default=None, metavar='SRC', help='source language')
  19. parser.add_argument('-t', '--target-lang', default=None, metavar='TARGET', help='target language')
  20. parser.add_argument('--trainpref', metavar='FP', default='train', help='target language')
  21. parser.add_argument('--validpref', metavar='FP', default='valid', help='comma separated, valid language prefixes')
  22. parser.add_argument('--testpref', metavar='FP', default='test', help='comma separated, test language prefixes')
  23. parser.add_argument('--destdir', metavar='DIR', default='data-bin', help='destination dir')
  24. parser.add_argument('--thresholdtgt', metavar='N', default=0, type=int,
  25. help='map words appearing less than threshold times to unknown')
  26. parser.add_argument('--thresholdsrc', metavar='N', default=0, type=int,
  27. help='map words appearing less than threshold times to unknown')
  28. parser.add_argument('--tgtdict', metavar='FP', help='reuse given target dictionary')
  29. parser.add_argument('--srcdict', metavar='FP', help='reuse given source dictionary')
  30. parser.add_argument('--nwordstgt', metavar='N', default=-1, type=int, help='number of target words to retain')
  31. parser.add_argument('--nwordssrc', metavar='N', default=-1, type=int, help='number of source words to retain')
  32. parser.add_argument('--alignfile', metavar='ALIGN', default=None, help='an alignment file (optional)')
  33. parser.add_argument('--output-format', metavar='FORMAT', default='binary', choices=['binary', 'raw'],
  34. help='output format (optional)')
  35. args = parser.parse_args()
  36. print(args)
  37. os.makedirs(args.destdir, exist_ok=True)
  38. if args.srcdict:
  39. src_dict = dictionary.Dictionary.load(args.srcdict)
  40. else:
  41. src_dict = Tokenizer.build_dictionary(filename='{}.{}'.format(args.trainpref, args.source_lang))
  42. src_dict.save(os.path.join(args.destdir, 'dict.{}.txt'.format(args.source_lang)),
  43. threshold=args.thresholdsrc, nwords=args.nwordssrc)
  44. if args.tgtdict:
  45. tgt_dict = dictionary.Dictionary.load(args.tgtdict)
  46. else:
  47. tgt_dict = Tokenizer.build_dictionary(filename='{}.{}'.format(args.trainpref, args.target_lang))
  48. tgt_dict.save(os.path.join(args.destdir, 'dict.{}.txt'.format(args.target_lang)),
  49. threshold=args.thresholdtgt, nwords=args.nwordstgt)
  50. def make_binary_dataset(input_prefix, output_prefix, lang):
  51. dict = dictionary.Dictionary.load(os.path.join(args.destdir, 'dict.{}.txt'.format(lang)))
  52. print('| [{}] Dictionary: {} types'.format(lang, len(dict) - 1))
  53. ds = indexed_dataset.IndexedDatasetBuilder(
  54. '{}/{}.{}-{}.{}.bin'.format(args.destdir, output_prefix, args.source_lang,
  55. args.target_lang, lang)
  56. )
  57. def consumer(tensor):
  58. ds.add_item(tensor)
  59. input_file = '{}.{}'.format(input_prefix, lang)
  60. res = Tokenizer.binarize(input_file, dict, consumer)
  61. print('| [{}] {}: {} sents, {} tokens, {:.3}% replaced by {}'.format(
  62. lang, input_file, res['nseq'], res['ntok'],
  63. 100 * res['nunk'] / res['ntok'], dict.unk_word))
  64. ds.finalize('{}/{}.{}-{}.{}.idx'.format(
  65. args.destdir, output_prefix,
  66. args.source_lang, args.target_lang, lang))
  67. def make_dataset(input_prefix, output_prefix, lang, output_format='binary'):
  68. if output_format == 'binary':
  69. make_binary_dataset(input_prefix, output_prefix, lang)
  70. elif output_format == 'raw':
  71. # Copy original text file to destination folder
  72. output_text_file = os.path.join(args.destdir, '{}.{}'.format(output_prefix, lang))
  73. shutil.copyfile('{}.{}'.format(input_prefix, lang), output_text_file)
  74. make_dataset(args.trainpref, 'train', args.source_lang, args.output_format)
  75. make_dataset(args.trainpref, 'train', args.target_lang, args.output_format)
  76. for k, validpref in enumerate(args.validpref.split(',')):
  77. outprefix = 'valid{}'.format(k) if k > 0 else 'valid'
  78. make_dataset(validpref, outprefix, args.source_lang, args.output_format)
  79. make_dataset(validpref, outprefix, args.target_lang, args.output_format)
  80. for k, testpref in enumerate(args.testpref.split(',')):
  81. outprefix = 'test{}'.format(k) if k > 0 else 'test'
  82. make_dataset(testpref, outprefix, args.source_lang, args.output_format)
  83. make_dataset(testpref, outprefix, args.target_lang, args.output_format)
  84. print('| Wrote preprocessed data to {}'.format(args.destdir))
  85. if args.alignfile:
  86. src_file_name = '{}.{}'.format(args.trainpref, args.source_lang)
  87. tgt_file_name = '{}.{}'.format(args.trainpref, args.target_lang)
  88. src_dict = dictionary.Dictionary.load(os.path.join(args.destdir, 'dict.{}.txt'.format(args.source_lang)))
  89. tgt_dict = dictionary.Dictionary.load(os.path.join(args.destdir, 'dict.{}.txt'.format(args.target_lang)))
  90. freq_map = {}
  91. with open(args.alignfile, 'r') as align_file:
  92. with open(src_file_name, 'r') as src_file:
  93. with open(tgt_file_name, 'r') as tgt_file:
  94. for a, s, t in zip_longest(align_file, src_file, tgt_file):
  95. si = Tokenizer.tokenize(s, src_dict, add_if_not_exist=False)
  96. ti = Tokenizer.tokenize(t, tgt_dict, add_if_not_exist=False)
  97. ai = list(map(lambda x: tuple(x.split('-')), a.split()))
  98. for sai, tai in ai:
  99. srcidx = si[int(sai)]
  100. tgtidx = ti[int(tai)]
  101. if srcidx != src_dict.unk() and tgtidx != tgt_dict.unk():
  102. assert srcidx != src_dict.pad()
  103. assert srcidx != src_dict.eos()
  104. assert tgtidx != tgt_dict.pad()
  105. assert tgtidx != tgt_dict.eos()
  106. if srcidx not in freq_map:
  107. freq_map[srcidx] = {}
  108. if tgtidx not in freq_map[srcidx]:
  109. freq_map[srcidx][tgtidx] = 1
  110. else:
  111. freq_map[srcidx][tgtidx] += 1
  112. align_dict = {}
  113. for srcidx in freq_map.keys():
  114. align_dict[srcidx] = max(freq_map[srcidx], key=freq_map[srcidx].get)
  115. with open(os.path.join(args.destdir, 'alignment.{}-{}.txt'.format(
  116. args.source_lang, args.target_lang)), 'w') as f:
  117. for k, v in align_dict.items():
  118. print('{} {}'.format(src_dict[k], tgt_dict[v]), file=f)
  119. if __name__ == '__main__':
  120. main()
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...