File size: 8,795 Bytes
bb22054
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eb0c0b7
bb22054
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
# coding=utf-8
# Copyright 2020 The HuggingFace Datasets Authors and the current dataset script contributor.
#
# 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.
"""Children's Book Test Dataset."""


import os

import datasets


_CITATION = """\
@misc{hill2016goldilocks,
      title={The Goldilocks Principle: Reading Children's Books with Explicit Memory Representations},
      author={Felix Hill and Antoine Bordes and Sumit Chopra and Jason Weston},
      year={2016},
      eprint={1511.02301},
      archivePrefix={arXiv},
      primaryClass={cs.CL}
}
"""


_DESCRIPTION = """\
The Children’s Book Test (CBT) is designed to measure directly
how well language models can exploit wider linguistic context.
The CBT is built from books that are freely available.
"""

_HOMEPAGE = "https://research.fb.com/downloads/babi/"

_LICENSE = """GNU Free Documentation License v1.3"""

ZIP_URL = "http://www.thespermwhale.com/jaseweston/babi/CBTest.tgz"
dir = "CBTest/data/"
paths = {
    "raw": {"train": dir + "cbt_train.txt", "valid": dir + "cbt_valid.txt", "test": dir + "cbt_test.txt"},
    "V": {
        "train": dir + "cbtest_V_train.txt",
        "valid": dir + "cbtest_V_valid_2000ex.txt",
        "test": dir + "cbtest_V_test_2500ex.txt",
    },
    "P": {
        "train": dir + "cbtest_P_train.txt",
        "valid": dir + "cbtest_P_valid_2000ex.txt",
        "test": dir + "cbtest_P_test_2500ex.txt",
    },
    "NE": {
        "train": dir + "cbtest_NE_train.txt",
        "valid": dir + "cbtest_NE_valid_2000ex.txt",
        "test": dir + "cbtest_NE_test_2500ex.txt",
    },
    "CN": {
        "train": dir + "cbtest_CN_train.txt",
        "valid": dir + "cbtest_CN_valid_2000ex.txt",
        "test": dir + "cbtest_CN_test_2500ex.txt",
    },
}


class Cbt(datasets.GeneratorBasedBuilder):
    """TODO: Short description of my dataset."""

    VERSION = datasets.Version("1.1.0")

    BUILDER_CONFIGS = [
        datasets.BuilderConfig(
            name="raw", version=VERSION, description="This part of my dataset covers the raw CBT books"
        ),
        datasets.BuilderConfig(
            name="V", version=VERSION, description="This part of my dataset covers the verb answer CBT dataset"
        ),
        datasets.BuilderConfig(
            name="P", version=VERSION, description="This part of my dataset covers the preposition answer CBT dataset"
        ),
        datasets.BuilderConfig(
            name="NE",
            version=VERSION,
            description="This part of my dataset covers the named entity answer CBT dataset",
        ),
        datasets.BuilderConfig(
            name="CN", version=VERSION, description="This part of my dataset covers the common noun answer CBT dataset"
        ),
    ]

    def _info(self):
        if self.config.name in ["V", "P", "NE", "CN"]:
            features = datasets.Features(
                {
                    "sentences": datasets.Sequence(datasets.Value("string")),  # There are 20 sentences
                    "question": datasets.Value("string"),
                    "answer": datasets.Value("string"),
                    "options": datasets.Sequence(datasets.Value("string")),
                }
            )
        else:  # This is an example to show how to have different features for "first_domain" and "second_domain"
            features = datasets.Features({"title": datasets.Value("string"), "content": datasets.Value("string")})
        return datasets.DatasetInfo(
            # This is the description that will appear on the datasets page.
            description=_DESCRIPTION,
            # This defines the different columns of the dataset and their types
            features=features,  # Here we define them above because they are different between the two configurations
            # If there's a common (input, target) tuple from the features,
            # specify them here. They'll be used if as_supervised=True in
            # builder.as_dataset.
            supervised_keys=None,
            # Homepage of the dataset for documentation
            homepage=_HOMEPAGE,
            # License for the dataset if available
            license=_LICENSE,
            # Citation for the dataset
            citation=_CITATION,
        )

    def _split_generators(self, dl_manager):
        """Returns SplitGenerators."""
        my_urls = ZIP_URL  # Cannot download just one single type as it is a compressed file.
        data_dir = dl_manager.download_and_extract(my_urls)
        return [
            datasets.SplitGenerator(
                name=datasets.Split.TRAIN,
                # These kwargs will be passed to _generate_examples
                gen_kwargs={
                    "filepath": os.path.join(data_dir, paths[self.config.name]["train"]),
                },
            ),
            datasets.SplitGenerator(
                name=datasets.Split.TEST,
                # These kwargs will be passed to _generate_examples
                gen_kwargs={
                    "filepath": os.path.join(data_dir, paths[self.config.name]["test"]),
                },
            ),
            datasets.SplitGenerator(
                name=datasets.Split.VALIDATION,
                # These kwargs will be passed to _generate_examples
                gen_kwargs={
                    "filepath": os.path.join(data_dir, paths[self.config.name]["valid"]),
                },
            ),
        ]

    def _generate_examples(
        self, filepath  # method parameters are unpacked from `gen_kwargs` as given in `_split_generators`
    ):
        """Yields examples as (key, example) tuples."""
        # This method handles input defined in _split_generators to yield (key, example) tuples from the dataset.
        # The `key` is here for legacy reason (tfds) and is not important in itself.

        if self.config.name != "raw":
            with open(filepath, encoding="utf-8") as f:
                sentences = []
                example_idx = 0
                for idx, line in enumerate(f):
                    if line.strip() == "":
                        continue

                    elif line.split()[0] == "21":
                        splitline = line.split("\t")  # question, answer options are tab separated
                        question = splitline[0]
                        answer = splitline[1]
                        options = splitline[-1]
                        question = question[2:].strip()  # The first two indices contain `21`.
                        answer = answer.strip()
                        options = options.strip().split("|")
                        yield example_idx, {
                            "sentences": sentences,
                            "question": question,
                            "options": options,
                            "answer": answer,
                        }

                        sentences = []
                        example_idx += 1
                    else:
                        if len(line.split()[0]) == 1:
                            sentences.append(line[1:].strip())
                        else:
                            sentences.append(line[2:].strip())
                            # Text might contain double spaces.
        else:
            with open(filepath, encoding="utf=8") as f:
                book_idx = 0
                book_sentences = []
                for idx, line in enumerate(f):
                    if line[:12] == "_BOOK_TITLE_":
                        if idx == 0:  # First line:
                            title = line.split(":")[1].strip()
                        else:
                            yield book_idx, {
                                "title": title,
                                "content": "".join(book_sentences),
                            }
                            title = line.split(":")[1].strip()
                            book_sentences = []
                            book_idx += 1
                    else:
                        book_sentences.append(line)
                else:
                    yield book_idx, {
                        "title": title,
                        "content": "".join(book_sentences),
                    }
                    book_sentences = []
                    book_idx += 1