wmt_utils.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  1. # Copyright 2015 Google Inc. All Rights Reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. # ==============================================================================
  15. """Utilities for downloading data from WMT, tokenizing, vocabularies."""
  16. import gzip
  17. import os
  18. import re
  19. import tarfile
  20. from six.moves import urllib
  21. import tensorflow as tf
  22. # Special vocabulary symbols - we always put them at the start.
  23. _PAD = b"_PAD"
  24. _GO = b"_GO"
  25. _EOS = b"_EOS"
  26. _UNK = b"_CHAR_UNK"
  27. _SPACE = b"_SPACE"
  28. _START_VOCAB = [_PAD, _GO, _EOS, _UNK, _SPACE]
  29. PAD_ID = 0
  30. GO_ID = 1
  31. EOS_ID = 2
  32. UNK_ID = 3
  33. SPACE_ID = 4
  34. # Regular expressions used to tokenize.
  35. _CHAR_MARKER = "_CHAR_"
  36. _CHAR_MARKER_LEN = len(_CHAR_MARKER)
  37. _SPEC_CHARS = "" + chr(226) + chr(153) + chr(128)
  38. _PUNCTUATION = "][.,!?\"':;%$#@&*+}{|><=/^~)(_`,0123456789" + _SPEC_CHARS + "-"
  39. _WORD_SPLIT = re.compile(b"([" + _PUNCTUATION + "])")
  40. _OLD_WORD_SPLIT = re.compile(b"([.,!?\"':;)(])")
  41. _DIGIT_RE = re.compile(br"\d")
  42. # URLs for WMT data.
  43. _WMT_ENFR_TRAIN_URL = "http://www.statmt.org/wmt10/training-giga-fren.tar"
  44. _WMT_ENFR_DEV_URL = "http://www.statmt.org/wmt15/dev-v2.tgz"
  45. def maybe_download(directory, filename, url):
  46. """Download filename from url unless it's already in directory."""
  47. if not tf.gfile.Exists(directory):
  48. print "Creating directory %s" % directory
  49. os.mkdir(directory)
  50. filepath = os.path.join(directory, filename)
  51. if not tf.gfile.Exists(filepath):
  52. print "Downloading %s to %s" % (url, filepath)
  53. filepath, _ = urllib.request.urlretrieve(url, filepath)
  54. statinfo = os.stat(filepath)
  55. print "Successfully downloaded", filename, statinfo.st_size, "bytes"
  56. return filepath
  57. def gunzip_file(gz_path, new_path):
  58. """Unzips from gz_path into new_path."""
  59. print "Unpacking %s to %s" % (gz_path, new_path)
  60. with gzip.open(gz_path, "rb") as gz_file:
  61. with open(new_path, "wb") as new_file:
  62. for line in gz_file:
  63. new_file.write(line)
  64. def get_wmt_enfr_train_set(directory):
  65. """Download the WMT en-fr training corpus to directory unless it's there."""
  66. train_path = os.path.join(directory, "giga-fren.release2.fixed")
  67. if not (tf.gfile.Exists(train_path +".fr") and
  68. tf.gfile.Exists(train_path +".en")):
  69. corpus_file = maybe_download(directory, "training-giga-fren.tar",
  70. _WMT_ENFR_TRAIN_URL)
  71. print "Extracting tar file %s" % corpus_file
  72. with tarfile.open(corpus_file, "r") as corpus_tar:
  73. corpus_tar.extractall(directory)
  74. gunzip_file(train_path + ".fr.gz", train_path + ".fr")
  75. gunzip_file(train_path + ".en.gz", train_path + ".en")
  76. return train_path
  77. def get_wmt_enfr_dev_set(directory):
  78. """Download the WMT en-fr training corpus to directory unless it's there."""
  79. dev_name = "newstest2013"
  80. dev_path = os.path.join(directory, dev_name)
  81. if not (tf.gfile.Exists(dev_path + ".fr") and
  82. tf.gfile.Exists(dev_path + ".en")):
  83. dev_file = maybe_download(directory, "dev-v2.tgz", _WMT_ENFR_DEV_URL)
  84. print "Extracting tgz file %s" % dev_file
  85. with tarfile.open(dev_file, "r:gz") as dev_tar:
  86. fr_dev_file = dev_tar.getmember("dev/" + dev_name + ".fr")
  87. en_dev_file = dev_tar.getmember("dev/" + dev_name + ".en")
  88. fr_dev_file.name = dev_name + ".fr" # Extract without "dev/" prefix.
  89. en_dev_file.name = dev_name + ".en"
  90. dev_tar.extract(fr_dev_file, directory)
  91. dev_tar.extract(en_dev_file, directory)
  92. return dev_path
  93. def is_char(token):
  94. if len(token) > _CHAR_MARKER_LEN:
  95. if token[:_CHAR_MARKER_LEN] == _CHAR_MARKER:
  96. return True
  97. return False
  98. def basic_detokenizer(tokens):
  99. """Reverse the process of the basic tokenizer below."""
  100. result = []
  101. previous_nospace = True
  102. for t in tokens:
  103. if is_char(t):
  104. result.append(t[_CHAR_MARKER_LEN:])
  105. previous_nospace = True
  106. elif t == _SPACE:
  107. result.append(" ")
  108. previous_nospace = True
  109. elif previous_nospace:
  110. result.append(t)
  111. previous_nospace = False
  112. else:
  113. result.extend([" ", t])
  114. previous_nospace = False
  115. return "".join(result)
  116. old_style = False
  117. def basic_tokenizer(sentence):
  118. """Very basic tokenizer: split the sentence into a list of tokens."""
  119. words = []
  120. if old_style:
  121. for space_separated_fragment in sentence.strip().split():
  122. words.extend(re.split(_OLD_WORD_SPLIT, space_separated_fragment))
  123. return [w for w in words if w]
  124. for space_separated_fragment in sentence.strip().split():
  125. tokens = [t for t in re.split(_WORD_SPLIT, space_separated_fragment) if t]
  126. first_is_char = False
  127. for i, t in enumerate(tokens):
  128. if len(t) == 1 and t in _PUNCTUATION:
  129. tokens[i] = _CHAR_MARKER + t
  130. if i == 0:
  131. first_is_char = True
  132. if words and words[-1] != _SPACE and (first_is_char or is_char(words[-1])):
  133. tokens = [_SPACE] + tokens
  134. spaced_tokens = []
  135. for i, tok in enumerate(tokens):
  136. spaced_tokens.append(tokens[i])
  137. if i < len(tokens) - 1:
  138. if tok != _SPACE and not (is_char(tok) or is_char(tokens[i+1])):
  139. spaced_tokens.append(_SPACE)
  140. words.extend(spaced_tokens)
  141. return words
  142. def space_tokenizer(sentence):
  143. return sentence.strip().split()
  144. def is_pos_tag(token):
  145. """Check if token is a part-of-speech tag."""
  146. return(token in ["CC", "CD", "DT", "EX", "FW", "IN", "JJ", "JJR",
  147. "JJS", "LS", "MD", "NN", "NNS", "NNP", "NNPS", "PDT",
  148. "POS", "PRP", "PRP$", "RB", "RBR", "RBS", "RP", "SYM", "TO",
  149. "UH", "VB", "VBD", "VBG", "VBN", "VBP", "VBZ", "WDT", "WP",
  150. "WP$", "WRB", ".", ",", ":", ")", "-LRB-", "(", "-RRB-",
  151. "HYPH", "$", "``", "''", "ADD", "AFX", "QTR", "BES", "-DFL-",
  152. "GW", "HVS", "NFP"])
  153. def parse_constraints(inpt, res):
  154. ntags = len(res)
  155. nwords = len(inpt)
  156. npostags = len([x for x in res if is_pos_tag(x)])
  157. nclose = len([x for x in res if x[0] == "/"])
  158. nopen = ntags - nclose - npostags
  159. return (abs(npostags - nwords), abs(nclose - nopen))
  160. def create_vocabulary(vocabulary_path, data_path, max_vocabulary_size,
  161. tokenizer=None, normalize_digits=False):
  162. """Create vocabulary file (if it does not exist yet) from data file.
  163. Data file is assumed to contain one sentence per line. Each sentence is
  164. tokenized and digits are normalized (if normalize_digits is set).
  165. Vocabulary contains the most-frequent tokens up to max_vocabulary_size.
  166. We write it to vocabulary_path in a one-token-per-line format, so that later
  167. token in the first line gets id=0, second line gets id=1, and so on.
  168. Args:
  169. vocabulary_path: path where the vocabulary will be created.
  170. data_path: data file that will be used to create vocabulary.
  171. max_vocabulary_size: limit on the size of the created vocabulary.
  172. tokenizer: a function to use to tokenize each data sentence;
  173. if None, basic_tokenizer will be used.
  174. normalize_digits: Boolean; if true, all digits are replaced by 0s.
  175. """
  176. if not tf.gfile.Exists(vocabulary_path):
  177. print "Creating vocabulary %s from data %s" % (vocabulary_path, data_path)
  178. vocab, chars = {}, {}
  179. for c in _PUNCTUATION:
  180. chars[c] = 1
  181. # Read French file.
  182. with tf.gfile.GFile(data_path + ".fr", mode="rb") as f:
  183. counter = 0
  184. for line_in in f:
  185. line = " ".join(line_in.split())
  186. counter += 1
  187. if counter % 100000 == 0:
  188. print " processing fr line %d" % counter
  189. for c in line:
  190. if c in chars:
  191. chars[c] += 1
  192. else:
  193. chars[c] = 1
  194. tokens = tokenizer(line) if tokenizer else basic_tokenizer(line)
  195. tokens = [t for t in tokens if not is_char(t) and t != _SPACE]
  196. for w in tokens:
  197. word = re.sub(_DIGIT_RE, b"0", w) if normalize_digits else w
  198. if word in vocab:
  199. vocab[word] += 1000000000 # We want target words first.
  200. else:
  201. vocab[word] = 1000000000
  202. # Read English file.
  203. with tf.gfile.GFile(data_path + ".en", mode="rb") as f:
  204. counter = 0
  205. for line_in in f:
  206. line = " ".join(line_in.split())
  207. counter += 1
  208. if counter % 100000 == 0:
  209. print " processing en line %d" % counter
  210. for c in line:
  211. if c in chars:
  212. chars[c] += 1
  213. else:
  214. chars[c] = 1
  215. tokens = tokenizer(line) if tokenizer else basic_tokenizer(line)
  216. tokens = [t for t in tokens if not is_char(t) and t != _SPACE]
  217. for w in tokens:
  218. word = re.sub(_DIGIT_RE, b"0", w) if normalize_digits else w
  219. if word in vocab:
  220. vocab[word] += 1
  221. else:
  222. vocab[word] = 1
  223. sorted_vocab = sorted(vocab, key=vocab.get, reverse=True)
  224. sorted_chars = sorted(chars, key=vocab.get, reverse=True)
  225. sorted_chars = [_CHAR_MARKER + c for c in sorted_chars]
  226. vocab_list = _START_VOCAB + sorted_chars + sorted_vocab
  227. if tokenizer:
  228. vocab_list = _START_VOCAB + sorted_vocab
  229. if len(vocab_list) > max_vocabulary_size:
  230. vocab_list = vocab_list[:max_vocabulary_size]
  231. with tf.gfile.GFile(vocabulary_path, mode="wb") as vocab_file:
  232. for w in vocab_list:
  233. vocab_file.write(w + b"\n")
  234. def initialize_vocabulary(vocabulary_path):
  235. """Initialize vocabulary from file.
  236. We assume the vocabulary is stored one-item-per-line, so a file:
  237. dog
  238. cat
  239. will result in a vocabulary {"dog": 0, "cat": 1}, and this function will
  240. also return the reversed-vocabulary ["dog", "cat"].
  241. Args:
  242. vocabulary_path: path to the file containing the vocabulary.
  243. Returns:
  244. a pair: the vocabulary (a dictionary mapping string to integers), and
  245. the reversed vocabulary (a list, which reverses the vocabulary mapping).
  246. Raises:
  247. ValueError: if the provided vocabulary_path does not exist.
  248. """
  249. if tf.gfile.Exists(vocabulary_path):
  250. rev_vocab = []
  251. with tf.gfile.GFile(vocabulary_path, mode="rb") as f:
  252. rev_vocab.extend(f.readlines())
  253. rev_vocab = [line.strip() for line in rev_vocab]
  254. vocab = dict([(x, y) for (y, x) in enumerate(rev_vocab)])
  255. return vocab, rev_vocab
  256. else:
  257. raise ValueError("Vocabulary file %s not found.", vocabulary_path)
  258. def sentence_to_token_ids_raw(sentence, vocabulary,
  259. tokenizer=None, normalize_digits=old_style):
  260. """Convert a string to list of integers representing token-ids.
  261. For example, a sentence "I have a dog" may become tokenized into
  262. ["I", "have", "a", "dog"] and with vocabulary {"I": 1, "have": 2,
  263. "a": 4, "dog": 7"} this function will return [1, 2, 4, 7].
  264. Args:
  265. sentence: the sentence in bytes format to convert to token-ids.
  266. vocabulary: a dictionary mapping tokens to integers.
  267. tokenizer: a function to use to tokenize each sentence;
  268. if None, basic_tokenizer will be used.
  269. normalize_digits: Boolean; if true, all digits are replaced by 0s.
  270. Returns:
  271. a list of integers, the token-ids for the sentence.
  272. """
  273. if tokenizer:
  274. words = tokenizer(sentence)
  275. else:
  276. words = basic_tokenizer(sentence)
  277. result = []
  278. for w in words:
  279. if normalize_digits:
  280. w = re.sub(_DIGIT_RE, b"0", w)
  281. if w in vocabulary:
  282. result.append(vocabulary[w])
  283. else:
  284. if tokenizer:
  285. result.append(UNK_ID)
  286. else:
  287. result.append(SPACE_ID)
  288. for c in w:
  289. result.append(vocabulary.get(_CHAR_MARKER + c, UNK_ID))
  290. result.append(SPACE_ID)
  291. while result and result[0] == SPACE_ID:
  292. result = result[1:]
  293. while result and result[-1] == SPACE_ID:
  294. result = result[:-1]
  295. return result
  296. def sentence_to_token_ids(sentence, vocabulary,
  297. tokenizer=None, normalize_digits=old_style):
  298. """Convert a string to list of integers representing token-ids, tab=0."""
  299. tab_parts = sentence.strip().split("\t")
  300. toks = [sentence_to_token_ids_raw(t, vocabulary, tokenizer, normalize_digits)
  301. for t in tab_parts]
  302. res = []
  303. for t in toks:
  304. res.extend(t)
  305. res.append(0)
  306. return res[:-1]
  307. def data_to_token_ids(data_path, target_path, vocabulary_path,
  308. tokenizer=None, normalize_digits=False):
  309. """Tokenize data file and turn into token-ids using given vocabulary file.
  310. This function loads data line-by-line from data_path, calls the above
  311. sentence_to_token_ids, and saves the result to target_path. See comment
  312. for sentence_to_token_ids on the details of token-ids format.
  313. Args:
  314. data_path: path to the data file in one-sentence-per-line format.
  315. target_path: path where the file with token-ids will be created.
  316. vocabulary_path: path to the vocabulary file.
  317. tokenizer: a function to use to tokenize each sentence;
  318. if None, basic_tokenizer will be used.
  319. normalize_digits: Boolean; if true, all digits are replaced by 0s.
  320. """
  321. if not tf.gfile.Exists(target_path):
  322. print "Tokenizing data in %s" % data_path
  323. vocab, _ = initialize_vocabulary(vocabulary_path)
  324. with tf.gfile.GFile(data_path, mode="rb") as data_file:
  325. with tf.gfile.GFile(target_path, mode="w") as tokens_file:
  326. counter = 0
  327. for line in data_file:
  328. counter += 1
  329. if counter % 100000 == 0:
  330. print " tokenizing line %d" % counter
  331. token_ids = sentence_to_token_ids(line, vocab, tokenizer,
  332. normalize_digits)
  333. tokens_file.write(" ".join([str(tok) for tok in token_ids]) + "\n")
  334. def prepare_wmt_data(data_dir, vocabulary_size,
  335. tokenizer=None, normalize_digits=False):
  336. """Get WMT data into data_dir, create vocabularies and tokenize data.
  337. Args:
  338. data_dir: directory in which the data sets will be stored.
  339. vocabulary_size: size of the joint vocabulary to create and use.
  340. tokenizer: a function to use to tokenize each data sentence;
  341. if None, basic_tokenizer will be used.
  342. normalize_digits: Boolean; if true, all digits are replaced by 0s.
  343. Returns:
  344. A tuple of 6 elements:
  345. (1) path to the token-ids for English training data-set,
  346. (2) path to the token-ids for French training data-set,
  347. (3) path to the token-ids for English development data-set,
  348. (4) path to the token-ids for French development data-set,
  349. (5) path to the vocabulary file,
  350. (6) path to the vocabulary file (for compatibility with non-joint vocab).
  351. """
  352. # Get wmt data to the specified directory.
  353. train_path = get_wmt_enfr_train_set(data_dir)
  354. dev_path = get_wmt_enfr_dev_set(data_dir)
  355. # Create vocabularies of the appropriate sizes.
  356. vocab_path = os.path.join(data_dir, "vocab%d.txt" % vocabulary_size)
  357. create_vocabulary(vocab_path, train_path, vocabulary_size,
  358. tokenizer=tokenizer, normalize_digits=normalize_digits)
  359. # Create token ids for the training data.
  360. fr_train_ids_path = train_path + (".ids%d.fr" % vocabulary_size)
  361. en_train_ids_path = train_path + (".ids%d.en" % vocabulary_size)
  362. data_to_token_ids(train_path + ".fr", fr_train_ids_path, vocab_path,
  363. tokenizer=tokenizer, normalize_digits=normalize_digits)
  364. data_to_token_ids(train_path + ".en", en_train_ids_path, vocab_path,
  365. tokenizer=tokenizer, normalize_digits=normalize_digits)
  366. # Create token ids for the development data.
  367. fr_dev_ids_path = dev_path + (".ids%d.fr" % vocabulary_size)
  368. en_dev_ids_path = dev_path + (".ids%d.en" % vocabulary_size)
  369. data_to_token_ids(dev_path + ".fr", fr_dev_ids_path, vocab_path,
  370. tokenizer=tokenizer, normalize_digits=normalize_digits)
  371. data_to_token_ids(dev_path + ".en", en_dev_ids_path, vocab_path,
  372. tokenizer=tokenizer, normalize_digits=normalize_digits)
  373. return (en_train_ids_path, fr_train_ids_path,
  374. en_dev_ids_path, fr_dev_ids_path,
  375. vocab_path, vocab_path)