wmt14.py 5.6 KB
Newer Older
H
Helin Wang 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
# Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Q
qijun 已提交
15
WMT14 dataset.
Q
qijun 已提交
16 17
The original WMT14 dataset is too large and a small set of data for set is
provided. This module will download dataset from
Q
qijun 已提交
18
http://paddlepaddle.cdn.bcebos.com/demo/wmt_shrinked_data/wmt14.tgz and
Q
qijun 已提交
19
parse training set and test set into paddle reader creators.
Q
qijun 已提交
20

H
Helin Wang 已提交
21
"""
22
import six
Q
qiaolongfei 已提交
23
import tarfile
L
Luo Tao 已提交
24
import gzip
Q
qiaolongfei 已提交
25

26
import paddle.dataset.common
27
import paddle.fluid.compat as cpt
H
Helin Wang 已提交
28

Y
ying 已提交
29 30 31 32 33 34
__all__ = [
    'train',
    'test',
    'get_dict',
    'convert',
]
H
Helin Wang 已提交
35

Y
ying 已提交
36 37
URL_DEV_TEST = ('http://www-lium.univ-lemans.fr/~schwenk/'
                'cslm_joint_paper/data/dev+test.tgz')
H
Helin Wang 已提交
38
MD5_DEV_TEST = '7d7897317ddd8ba0ae5c5fa7248d3ff5'
Y
ying 已提交
39 40 41 42
# this is a small set of data for test. The original data is too large and
# will be add later.
URL_TRAIN = ('http://paddlepaddle.cdn.bcebos.com/demo/'
             'wmt_shrinked_data/wmt14.tgz')
L
Luo Tao 已提交
43
MD5_TRAIN = '0791583d57d5beb693b9414c5b36798c'
44
# BLEU of this trained model is 26.92
45 46
URL_MODEL = 'http://paddlemodels.bj.bcebos.com/wmt/wmt14.tgz'
MD5_MODEL = '0791583d57d5beb693b9414c5b36798c'
Q
qiaolongfei 已提交
47 48 49 50 51 52

START = "<s>"
END = "<e>"
UNK = "<unk>"
UNK_IDX = 2

Q
qiaolongfei 已提交
53

Y
ying 已提交
54 55
def __read_to_dict(tar_file, dict_size):
    def __to_dict(fd, size):
Q
qiaolongfei 已提交
56
        out_dict = dict()
Q
qiaolongfei 已提交
57 58
        for line_count, line in enumerate(fd):
            if line_count < size:
59
                out_dict[cpt.to_literal_str(line.strip())] = line_count
Q
qiaolongfei 已提交
60 61
            else:
                break
Q
qiaolongfei 已提交
62 63 64 65 66 67 68 69
        return out_dict

    with tarfile.open(tar_file, mode='r') as f:
        names = [
            each_item.name for each_item in f
            if each_item.name.endswith("src.dict")
        ]
        assert len(names) == 1
Y
ying 已提交
70
        src_dict = __to_dict(f.extractfile(names[0]), dict_size)
Q
qiaolongfei 已提交
71 72 73 74 75
        names = [
            each_item.name for each_item in f
            if each_item.name.endswith("trg.dict")
        ]
        assert len(names) == 1
Y
ying 已提交
76
        trg_dict = __to_dict(f.extractfile(names[0]), dict_size)
Q
qiaolongfei 已提交
77 78 79 80 81
        return src_dict, trg_dict


def reader_creator(tar_file, file_name, dict_size):
    def reader():
Y
ying 已提交
82
        src_dict, trg_dict = __read_to_dict(tar_file, dict_size)
Q
qiaolongfei 已提交
83 84 85 86
        with tarfile.open(tar_file, mode='r') as f:
            names = [
                each_item.name for each_item in f
                if each_item.name.endswith(file_name)
H
Helin Wang 已提交
87
            ]
Q
qiaolongfei 已提交
88 89
            for name in names:
                for line in f.extractfile(name):
90
                    line_split = line.strip().split(six.b('\t'))
Q
qiaolongfei 已提交
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
                    if len(line_split) != 2:
                        continue
                    src_seq = line_split[0]  # one source sequence
                    src_words = src_seq.split()
                    src_ids = [
                        src_dict.get(w, UNK_IDX)
                        for w in [START] + src_words + [END]
                    ]

                    trg_seq = line_split[1]  # one target sequence
                    trg_words = trg_seq.split()
                    trg_ids = [trg_dict.get(w, UNK_IDX) for w in trg_words]

                    # remove sequence whose length > 80 in training mode
                    if len(src_ids) > 80 or len(trg_ids) > 80:
                        continue
                    trg_ids_next = trg_ids + [trg_dict[END]]
                    trg_ids = [trg_dict[START]] + trg_ids

                    yield src_ids, trg_ids, trg_ids_next

    return reader


def train(dict_size):
Q
qijun 已提交
116
    """
Q
qijun 已提交
117
    WMT14 training set creator.
Q
qijun 已提交
118

Q
qijun 已提交
119 120 121
    It returns a reader creator, each sample in the reader is source language
    word ID sequence, target language word ID sequence and next word ID
    sequence.
Q
qijun 已提交
122

Q
qijun 已提交
123
    :return: Training reader creator
Q
qijun 已提交
124 125
    :rtype: callable
    """
Q
qiaolongfei 已提交
126
    return reader_creator(
127
        paddle.dataset.common.download(URL_TRAIN, 'wmt14', MD5_TRAIN),
R
root 已提交
128
        'train/train', dict_size)
Q
qiaolongfei 已提交
129 130 131


def test(dict_size):
Q
qijun 已提交
132 133 134
    """
    WMT14 test set creator.

Q
qijun 已提交
135 136 137
    It returns a reader creator, each sample in the reader is source language
    word ID sequence, target language word ID sequence and next word ID
    sequence.
Q
qijun 已提交
138

Q
qijun 已提交
139
    :return: Test reader creator
Q
qijun 已提交
140 141
    :rtype: callable
    """
Q
qiaolongfei 已提交
142
    return reader_creator(
143
        paddle.dataset.common.download(URL_TRAIN, 'wmt14', MD5_TRAIN),
R
root 已提交
144
        'test/test', dict_size)
Y
Yancey1989 已提交
145 146


L
Luo Tao 已提交
147 148
def gen(dict_size):
    return reader_creator(
149
        paddle.dataset.common.download(URL_TRAIN, 'wmt14', MD5_TRAIN),
R
root 已提交
150
        'gen/gen', dict_size)
L
Luo Tao 已提交
151 152 153 154 155


def get_dict(dict_size, reverse=True):
    # if reverse = False, return dict = {'a':'001', 'b':'002', ...}
    # else reverse = true, return dict = {'001':'a', '002':'b', ...}
156
    tar_file = paddle.dataset.common.download(URL_TRAIN, 'wmt14', MD5_TRAIN)
Y
ying 已提交
157
    src_dict, trg_dict = __read_to_dict(tar_file, dict_size)
L
Luo Tao 已提交
158
    if reverse:
M
minqiyang 已提交
159 160
        src_dict = {v: k for k, v in six.iteritems(src_dict)}
        trg_dict = {v: k for k, v in six.iteritems(trg_dict)}
L
Luo Tao 已提交
161
    return src_dict, trg_dict
L
Luo Tao 已提交
162 163


164
def fetch():
165 166
    paddle.dataset.common.download(URL_TRAIN, 'wmt14', MD5_TRAIN)
    paddle.dataset.common.download(URL_MODEL, 'wmt14', MD5_MODEL)
R
root 已提交
167 168 169 170 171 172 173


def convert(path):
    """
    Converts dataset to recordio format
    """
    dict_size = 30000
174 175
    paddle.dataset.common.convert(path, train(dict_size), 1000, "wmt14_train")
    paddle.dataset.common.convert(path, test(dict_size), 1000, "wmt14_test")