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

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

Comments

Loading...