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 8.9 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
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
  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, tokenize_line
  15. def get_parser():
  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=None, help='target language')
  21. parser.add_argument('--validpref', metavar='FP', default=None, help='comma separated, valid language prefixes')
  22. parser.add_argument('--testpref', metavar='FP', default=None, 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. parser.add_argument('--joined-dictionary', action='store_true', help='Generate joined dictionary')
  36. parser.add_argument('--only-source', action='store_true', help='Only process the source language')
  37. parser.add_argument('--padding-factor', metavar='N', default=8, type=int,
  38. help='Pad dictionary size to be multiple of N')
  39. return parser
  40. def main(args):
  41. print(args)
  42. os.makedirs(args.destdir, exist_ok=True)
  43. target = not args.only_source
  44. def build_dictionary(filenames):
  45. d = dictionary.Dictionary()
  46. for filename in filenames:
  47. Tokenizer.add_file_to_dictionary(filename, d, tokenize_line)
  48. return d
  49. if args.joined_dictionary:
  50. assert not args.srcdict, 'cannot combine --srcdict and --joined-dictionary'
  51. assert not args.tgtdict, 'cannot combine --tgtdict and --joined-dictionary'
  52. src_dict = build_dictionary([
  53. '{}.{}'.format(args.trainpref, lang)
  54. for lang in [args.source_lang, args.target_lang]
  55. ])
  56. tgt_dict = src_dict
  57. else:
  58. if args.srcdict:
  59. src_dict = dictionary.Dictionary.load(args.srcdict)
  60. else:
  61. assert args.trainpref, "--trainpref must be set if --srcdict is not specified"
  62. src_dict = build_dictionary(['{}.{}'.format(args.trainpref, args.source_lang)])
  63. if target:
  64. if args.tgtdict:
  65. tgt_dict = dictionary.Dictionary.load(args.tgtdict)
  66. else:
  67. assert args.trainpref, "--trainpref must be set if --tgtdict is not specified"
  68. tgt_dict = build_dictionary(['{}.{}'.format(args.trainpref, args.target_lang)])
  69. src_dict.finalize(
  70. threshold=args.thresholdsrc,
  71. nwords=args.nwordssrc,
  72. padding_factor=args.padding_factor,
  73. )
  74. src_dict.save(os.path.join(args.destdir, 'dict.{}.txt'.format(args.source_lang)))
  75. if target:
  76. if not args.joined_dictionary:
  77. tgt_dict.finalize(
  78. threshold=args.thresholdtgt,
  79. nwords=args.nwordstgt,
  80. padding_factor=args.padding_factor,
  81. )
  82. tgt_dict.save(os.path.join(args.destdir, 'dict.{}.txt'.format(args.target_lang)))
  83. def make_binary_dataset(input_prefix, output_prefix, lang):
  84. dict = dictionary.Dictionary.load(os.path.join(args.destdir, 'dict.{}.txt'.format(lang)))
  85. print('| [{}] Dictionary: {} types'.format(lang, len(dict) - 1))
  86. ds = indexed_dataset.IndexedDatasetBuilder(
  87. '{}/{}.{}-{}.{}.bin'.format(args.destdir, output_prefix, args.source_lang,
  88. args.target_lang, lang)
  89. )
  90. def consumer(tensor):
  91. ds.add_item(tensor)
  92. input_file = '{}.{}'.format(input_prefix, lang)
  93. res = Tokenizer.binarize(input_file, dict, consumer)
  94. print('| [{}] {}: {} sents, {} tokens, {:.3}% replaced by {}'.format(
  95. lang, input_file, res['nseq'], res['ntok'],
  96. 100 * res['nunk'] / res['ntok'], dict.unk_word))
  97. ds.finalize('{}/{}.{}-{}.{}.idx'.format(
  98. args.destdir, output_prefix,
  99. args.source_lang, args.target_lang, lang))
  100. def make_dataset(input_prefix, output_prefix, lang, output_format='binary'):
  101. if output_format == 'binary':
  102. make_binary_dataset(input_prefix, output_prefix, lang)
  103. elif output_format == 'raw':
  104. # Copy original text file to destination folder
  105. output_text_file = os.path.join(args.destdir, '{}.{}'.format(output_prefix, lang))
  106. shutil.copyfile('{}.{}'.format(input_prefix, lang), output_text_file)
  107. def make_all(args, make_dataset, lang):
  108. if args.trainpref:
  109. make_dataset(args.trainpref, 'train', lang, args.output_format)
  110. if args.validpref:
  111. for k, validpref in enumerate(args.validpref.split(',')):
  112. outprefix = 'valid{}'.format(k) if k > 0 else 'valid'
  113. make_dataset(validpref, outprefix, lang, args.output_format)
  114. if args.testpref:
  115. for k, testpref in enumerate(args.testpref.split(',')):
  116. outprefix = 'test{}'.format(k) if k > 0 else 'test'
  117. make_dataset(testpref, outprefix, lang, args.output_format)
  118. make_all(args, make_dataset, args.source_lang)
  119. if target:
  120. make_all(args, make_dataset, args.target_lang)
  121. print('| Wrote preprocessed data to {}'.format(args.destdir))
  122. if args.alignfile:
  123. assert args.trainpref, "--trainpref must be set if --alignfile is specified"
  124. src_file_name = '{}.{}'.format(args.trainpref, args.source_lang)
  125. tgt_file_name = '{}.{}'.format(args.trainpref, args.target_lang)
  126. src_dict = dictionary.Dictionary.load(os.path.join(args.destdir, 'dict.{}.txt'.format(args.source_lang)))
  127. tgt_dict = dictionary.Dictionary.load(os.path.join(args.destdir, 'dict.{}.txt'.format(args.target_lang)))
  128. freq_map = {}
  129. with open(args.alignfile, 'r') as align_file:
  130. with open(src_file_name, 'r') as src_file:
  131. with open(tgt_file_name, 'r') as tgt_file:
  132. for a, s, t in zip_longest(align_file, src_file, tgt_file):
  133. si = Tokenizer.tokenize(s, src_dict, add_if_not_exist=False)
  134. ti = Tokenizer.tokenize(t, tgt_dict, add_if_not_exist=False)
  135. ai = list(map(lambda x: tuple(x.split('-')), a.split()))
  136. for sai, tai in ai:
  137. srcidx = si[int(sai)]
  138. tgtidx = ti[int(tai)]
  139. if srcidx != src_dict.unk() and tgtidx != tgt_dict.unk():
  140. assert srcidx != src_dict.pad()
  141. assert srcidx != src_dict.eos()
  142. assert tgtidx != tgt_dict.pad()
  143. assert tgtidx != tgt_dict.eos()
  144. if srcidx not in freq_map:
  145. freq_map[srcidx] = {}
  146. if tgtidx not in freq_map[srcidx]:
  147. freq_map[srcidx][tgtidx] = 1
  148. else:
  149. freq_map[srcidx][tgtidx] += 1
  150. align_dict = {}
  151. for srcidx in freq_map.keys():
  152. align_dict[srcidx] = max(freq_map[srcidx], key=freq_map[srcidx].get)
  153. with open(os.path.join(args.destdir, 'alignment.{}-{}.txt'.format(
  154. args.source_lang, args.target_lang)), 'w') as f:
  155. for k, v in align_dict.items():
  156. print('{} {}'.format(src_dict[k], tgt_dict[v]), file=f)
  157. if __name__ == '__main__':
  158. parser = get_parser()
  159. args = parser.parse_args()
  160. main(args)
Tip!

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

Comments

Loading...