File size: 8,490 Bytes
0183bcd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# coding=utf-8
# Copyright 2020 The HuggingFace Datasets Authors.
#
# 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.
"""MCTest: Machine comprehension test: http://research.microsoft.com/mct"""


import os
import datasets


_CITATION = """\
@inproceedings{richardson-etal-2013-mctest,
    title = "{MCT}est: A Challenge Dataset for the Open-Domain Machine Comprehension of Text",
    author = "Richardson, Matthew  and
      Burges, Christopher J.C.  and
      Renshaw, Erin",
    booktitle = "Proceedings of the 2013 Conference on Empirical Methods in Natural Language Processing",
    month = oct,
    year = "2013",
    address = "Seattle, Washington, USA",
    publisher = "Association for Computational Linguistics",
    url = "https://www.aclweb.org/anthology/D13-1020",
    pages = "193--203",
}
"""

_DESCRIPTION = """\
MCTest requires machines to answer multiple-choice reading comprehension questions about fictional stories, directly tackling the high-level goal of open-domain machine comprehension.
"""

_HOMEPAGE = "https://www.aclweb.org/anthology/D13-1020/"

_DATA_URL = "http://parl.ai/downloads/mctest/mctest.tar.gz"


class MCTest(datasets.GeneratorBasedBuilder):
    """MCTest: Machine comprehension test: http://research.microsoft.com/mct"""

    VERSION = datasets.Version("1.0.0")

    BUILDER_CONFIGS = [
        datasets.BuilderConfig(
            name="mc500",
            version=VERSION,
            description="MC 500",
        ),
        datasets.BuilderConfig(
            name="mc160",
            version=VERSION,
            description="MC 160",
        ),
    ]

    DEFAULT_CONFIG_NAME = "mc500"

    def _info(self):
        if self.config.name == "mc500":
            features = datasets.Features(
                {
                    "idx": dict(
                        {"story": datasets.Value("string"),
                         "question": datasets.Value("int32")
                         }
                    ),
                    "question": datasets.Value("string"),
                    "story": datasets.Value("string"),
                    "properties": dict(
                        {
                            "author": datasets.Value("string"),
                            "work_time": datasets.Value("int32"),
                            "quality_score": datasets.Value("int32"),
                            "creativity_words": datasets.Sequence(datasets.Value("string")),
                        }
                    ),
                    "answer_options": dict(
                        {
                            "A": datasets.Value("string"),
                            "B": datasets.Value("string"),
                            "C": datasets.Value("string"),
                            "D": datasets.Value("string")
                        }
                    ),
                    "answer": datasets.Value("string"),
                    "question_is_multiple": datasets.Value("bool")
                }
            )
        else:
            features = datasets.Features(
                {
                    "idx": dict(
                        {"story": datasets.Value("string"),
                         "question": datasets.Value("int32")
                         }
                    ),
                    "question": datasets.Value("string"),
                    "story": datasets.Value("string"),
                    "properties": dict(
                        {
                            "author": datasets.Value("string"),
                            "work_time": datasets.Value("int32"),
                        }
                    ),
                    "answer_options": dict(
                        {
                            "A": datasets.Value("string"),
                            "B": datasets.Value("string"),
                            "C": datasets.Value("string"),
                            "D": datasets.Value("string")
                        }
                    ),
                    "answer": datasets.Value("string"),
                    "question_is_multiple": datasets.Value("bool")
                }
            )
        return datasets.DatasetInfo(
            description=_DESCRIPTION,
            features=features,
            homepage=_HOMEPAGE,
            citation=_CITATION,
        )

    def _split_generators(self, dl_manager):
        data_dir = os.path.join(dl_manager.download_and_extract(_DATA_URL), 'mctest')
        paths = {}
        for phase in ["train", "dev", "test"]:
            paths[phase] = {
                "data": os.path.join(data_dir, "MCTest", f"{self.config.name}.{phase}.tsv"),
                "answer": os.path.join(data_dir, "MCTest", f"{self.config.name}.{phase}.ans")
            }
        paths["test"]["answer"] = os.path.join(data_dir, "MCTestAnswers", f"{self.config.name}.test.ans")

        return [
            datasets.SplitGenerator(
                name=datasets.Split.TRAIN,
                gen_kwargs={"filepath": paths["train"]},
            ),
            datasets.SplitGenerator(
                name=datasets.Split.VALIDATION,
                gen_kwargs={"filepath": paths["dev"]},
            ),
            datasets.SplitGenerator(
                name=datasets.Split.TEST,
                gen_kwargs={"filepath": paths["test"]},
            ),
        ]

    def _get_properties(self, property_str):
        """
         properties is a semicolon-delimited list of property:value pairs, including
         Author (anonymized author id, consistent across all files)
         Work Time(s): Seconds between author accepting and submitting the task
         Qual. score: The author's grammar qualification test score (% correct)
         Creativity Words: Words the author was given to encourage creativity
         (there are no creativity words or qual score for mc160, see paper)
        :param property_str:
        :return:
        """
        properties = property_str.split(';')
        property_data = {
            "author": properties[0].split(':')[-1].strip(),
            "work_time": int(properties[1].split(':')[-1].strip())
        }
        if self.config.name == "mc500":
            property_data.update(
                {
                    "quality_score": int(properties[2].split(':')[-1].strip()),
                    "creativity_words": properties[3].split(':')[-1].strip().split(',')
                }
            )
        return property_data

    def _generate_examples(self, filepath):
        tab_char = '\t'
        data_path = filepath['data']
        ans_path = filepath['answer']
        data_lines = open(data_path, encoding="utf-8").read().split('\n')[:-1]
        answer_lines = open(ans_path, encoding="utf-8").read().split('\n')[:-1]
        for data_line, answer_line in zip(data_lines, answer_lines):
            data_line_split = data_line.split(tab_char)
            story_id = data_line_split[0]
            properties = self._get_properties(data_line_split[1])
            story = data_line_split[2]
            answers = answer_line.split('\t')
            data_line_split = data_line_split[3:]
            for i in range(4):
                answer = answers[i]
                index = i*5
                multiple, question_text = [x.strip() for x in data_line_split[index].strip().split(':')]
                question_is_multiple = True if multiple == "multiple" else False
                answer_options = {x: y for x, y in zip(["A", "B", "C", "D"], data_line_split[index+1:index+5])}
                yield f"{story_id}-{i}", {
                    "idx":
                        {"story": story_id,
                         "question": i
                         },
                    "question": question_text,
                    "story": story,
                    "properties": properties,
                    "answer_options": answer_options,
                    "answer": answer,
                    "question_is_multiple": question_is_multiple
                }