File size: 13,595 Bytes
f53e412
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
# Copyright 2020 The HuggingFace Datasets Authors and
# the Johns Hopkins University (JHU) Human Language Technology
# Center of Excellence.
#
# 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.
"""
This file provides a HuggingFace dataset loader implementation for
the JHU/HLTCOE MegaWika dataset.
MegaWika is a multi- and crosslingual text dataset containing 30 million
Wikipedia passages with their scraped and cleaned web citations. The
passages span 50 Wikipedias in 50 languages, and the articles in which
the passages were originally embedded are included for convenience. Where
a Wikipedia passage is in a non-English language, an automated English
translation is provided. Furthermore, nearly 130 million English
question/answer pairs were extracted from the passages, and FrameNet events
occurring in the passages are detected using the LOME FrameNet parser.
"""


import csv
import json
import os
import re
import pathlib
from pathlib import Path
import yaml
from ast import literal_eval

import datasets

# import gzip
# try:
#     import lzma as xz
# except ImportError:
#     import pylzma as xz


# TODO: Add BibTeX citation
# Find for instance the citation on arxiv or on the dataset repo/website
_CITATION = """\
@article{barham2023megawika,
  title={MegaWika: Millions of reports and their sources across 50 diverse languages},
  author={Barham, Samuel and Weller, Orion and
          Yuan, Michelle and Murray, Kenton and
          Yarmohammadi, Mahsa and Jiang, Zhengping and
          Vashishtha, Siddharth and Martin, Alexander and
          Liu, Anqi and White, Aaron Steven and
          Boyd-Graber, Jordan and Van Durme, Benjamin
  },
  journal={INSERT ARXIV PREPRINT ID HERE},
  year={2023}
}
"""

# TODO: Add description of the dataset here
# You can copy an official description
_DESCRIPTION = """\
MegaWika is a multi- and crosslingual text dataset containing 30 million
Wikipedia passages with their scraped and cleaned web citations. The
passages span 50 Wikipedias in 50 languages, and the articles in which
the passages were originally embedded are included for convenience. Where
a Wikipedia passage is in a non-English language, an automated English
translation is provided. Furthermore, nearly 130 million English
question/answer pairs were extracted from the passages, and FrameNet events
occurring in the passages are detected using the LOME FrameNet parser.
"""

_HOMEPAGE = "https://huggingface.co/datasets/conceptofmind/MegaWika"

_LICENSE = "cc-by-sa-4.0"

_URL = "https://huggingface.co/datasets/conceptofmind/MegaWika"

# Load the file paths for all the splits (per language currently)

file_list_url = "https://huggingface.co/datasets/conceptofmind/MegaWika/raw/main/files.yml"

import urllib.request
with urllib.request.urlopen(file_list_url) as f:
    try:
        fnames = yaml.safe_load(f)
    except yaml.YAMLError as exc:
        print("Error loading the file paths for the dataset splits. Aborting.")
        exit(1)

_DATA_URL = fnames['fnames']

_VARIANTS = ["all"] + list(_DATA_URL.keys())


class MegaWika(datasets.GeneratorBasedBuilder):
    BUILDER_CONFIGS = [datasets.BuilderConfig(name) for name in _VARIANTS]

    def _info(self):
        return datasets.DatasetInfo(
            description=_DESCRIPTION,
            features=datasets.Features(
                {
                    "article_title": datasets.Value("string"),
                    "article_text": datasets.Value("string"),
                    "entries": datasets.features.Sequence(
                        {
                            "id": datasets.Value("string"),

                            # Wiki passage
                            "passage": {
                                "text": [datasets.Value("string")],
                                "parse": datasets.Value("string"),
                                "en_tokens": [datasets.Value("string")],
                                "lang_tokens": [datasets.Value("string")],
                                "en_lang_token_map": [[datasets.Value("int32")]] # list of pairs
                            },

                            # MT
                            "mt": {
                                "original": datasets.Value("string"),
                                "original_sents": [datasets.Value("string")],
                                "translation": datasets.Value("string"),
                                "translation_sents": [datasets.Value("string")],
                                "translation_probs": [[datasets.Value("string")]],
                                "repetitious_translation": datasets.Value("bool")
                            },

                            # Source document
                            "source_lang": datasets.Value("string"),
                            "source_url": datasets.Value("string"),
                            "source_text": datasets.Value("string"),
                            
                            # Question/answer pairs
                            "qa_pairs": datasets.Sequence(
                                {
                                    "question": datasets.Value("string"),
                                    "en_answer": datasets.Value("string"),
                                    "lang_answer": datasets.Value("string"),
                                    "frames": datasets.Sequence(
                                        {
                                            "frame": datasets.Value("string"),
                                            "argument": datasets.Value("string")
                                        }
                                    ),
                                    "en_matches_in_source": [[datasets.Value("int32")]], # list of pair of int indices
                                    "en_match_in_passage": [datasets.Value("int32")], # pair of int indices
                                    "lang_matches_in_source": [[datasets.Value("int32")]], # list of pair of int indices
                                    "lang_match_in_passage": [datasets.Value("int32")], # pair of int indices
                                    "passage": [datasets.Value("string")],
                                    "en_answer_tokens": [datasets.Value("string")],
                                    "match_disambiguated_question": datasets.Value("string"),
                                }
                            )
                        }
                    )
                }
            ),
            supervised_keys=None,
            homepage=_URL,
            citation=_CITATION,
        )

    def _split_generators(self, dl_manager):
        if self.config.name == "all":
            data_sources = _DATA_URL
        else:
            data_sources = {self.config.name: _DATA_URL[self.config.name]}

        return [
            datasets.SplitGenerator(
                name=lang,
                gen_kwargs={
                    "filepaths": dl_manager.download(data_sources[lang])
                }
            )
            for lang
            in data_sources
        ]

    def _get_qa_pair_list_features(self, qa_pair, feature_name):
        res = []

        if feature_name in qa_pair:
            if qa_pair[feature_name]:
                return qa_pair[feature_name]  
        else:
            if feature_name.startswith('en'):
                feature_name = '_'.join(feature_name.split('_')[1:])
                return self._get_qa_pair_list_features(qa_pair, feature_name)

        return res
    
    def _generate_examples(self, filepaths):
        """This function returns the examples in the raw (text) form by iterating on all the files."""
        id_ = 0
        for filepath in filepaths:
            # logger.info("Generating examples from = %s", filepath)
            try:
                with open(filepath, "r", encoding="utf-8") as f:
                    for line in f:
                        if line:
                            example = json.loads(line)
                            if example is not None and isinstance(example, dict):
                                yield id_, {
                                    "article_title": example.get("article_title", ""),
                                    "article_text": example.get("article_text", ""),
                                    "entries": [
                                        {
                                            "id": entry.get("id", "").lower(),
                                            "passage": {
                                                "text": entry['passage'].get("text", []),
                                                "parse": json.dumps(entry['passage'].get("parse", [{}])),
                                                "en_tokens": list(entry['passage'].get(
                                                    "en_tokens",
                                                    {
                                                        token: token
                                                        for tokens in entry['passage'].get("tokens", {})
                                                        for token in tokens
                                                    }
                                                ).values()),
                                                "lang_tokens": list(entry['passage'].get("lang_tokens", {}).values()),
                                                "en_lang_token_map": [
                                                    (int(item[0]), int(item[1]))
                                                    for item
                                                    in entry['passage'].get("en_lang_token_map", {}).items()
                                                ]
                                            },
                                            "mt": {
                                                "original": entry.get("original", ""),
                                                "original_sents": entry.get("original_sents", []),
                                                "translation": entry.get("translation", ""),
                                                "translation_sents": entry.get("translation_sents", []),
                                                "translation_probs": entry.get("translation_probs", [[]]),
                                                "repetitious_translation": entry.get("repetitious_translation", None)
                                            },
                                            "source_lang": entry.get("source_lang", ""),
                                            "source_url": entry.get("source_url", ""),
                                            "source_text": entry.get("source_text", ""),
                                            "qa_pairs": [
                                                {
                                                    "question": qa_pair.get('question', ""),
                                                    "en_answer": qa_pair.get('en_answer', qa_pair.get('answer', "")),
                                                    'lang_answer': qa_pair.get('lang_answer', ''),
                                                    'frames': qa_pair.get('frames', []),
                                                    "en_matches_in_source": self._get_qa_pair_list_features(qa_pair, "en_matches_in_source"), 
                                                    "en_match_in_passage": self._get_qa_pair_list_features(qa_pair, "en_match_in_passage"), 
                                                    "lang_matches_in_source": self._get_qa_pair_list_features(qa_pair, "lang_matches_in_source"), 
                                                    "lang_match_in_passage": self._get_qa_pair_list_features(qa_pair, "lang_match_in_passage"), 
                                                    "passage": qa_pair.get('passage', []),
                                                    "en_answer_tokens": qa_pair.get('en_answer_tokens', qa_pair.get('answer_tokens', [])),
                                                    "match_disambiguated_question": qa_pair.get('match_disambiguated_question', ""),
                                                }
                                                for qa_pair
                                                in entry.get('qa_pairs', [])
                                            ]
                                        }
                                        for entry
                                        in example.get("entries", [])
                                    ]
                                }
                                id_ += 1
            except:
                print("Error reading file:", filepath)



# "entries": datasets.features.Sequence(
#     {
#         "qa_pairs": datasets.Sequence(
#             {
#                 "question": datasets.Value("string"),
#                 "answer": datasets.Value("string"),
#             }
#         )
#     }