MegaWika / megawika.py
conceptofmind's picture
Update megawika.py
c6d2430 verified
raw
history blame
13.6 kB
# 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"),
# }
# )
# }