Datasets:
joelniklaus
commited on
Commit
•
30dd125
1
Parent(s):
3ffe3b2
added data loader script and data preparation script
Browse files- EU_Wikipedias.py +134 -0
- prepare_wikipedias.py +48 -0
EU_Wikipedias.py
ADDED
@@ -0,0 +1,134 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""EU Wikipedias"""
|
2 |
+
|
3 |
+
import json
|
4 |
+
|
5 |
+
import datasets
|
6 |
+
from huggingface_hub.file_download import hf_hub_url
|
7 |
+
|
8 |
+
try:
|
9 |
+
import lzma as xz
|
10 |
+
except ImportError:
|
11 |
+
import pylzma as xz
|
12 |
+
|
13 |
+
datasets.logging.set_verbosity_info()
|
14 |
+
logger = datasets.logging.get_logger(__name__)
|
15 |
+
|
16 |
+
_CITATION = """\
|
17 |
+
@ONLINE {wikidump,
|
18 |
+
author = {Wikimedia Foundation},
|
19 |
+
title = {Wikimedia Downloads},
|
20 |
+
url = {https://dumps.wikimedia.org}
|
21 |
+
}
|
22 |
+
"""
|
23 |
+
|
24 |
+
_DESCRIPTION = """\
|
25 |
+
Wikipedia dataset containing cleaned articles of all languages.
|
26 |
+
The datasets are built from the Wikipedia dump
|
27 |
+
(https://dumps.wikimedia.org/) with one split per language. Each example
|
28 |
+
contains the content of one full Wikipedia article with cleaning to strip
|
29 |
+
markdown and unwanted sections (references, etc.).
|
30 |
+
"""
|
31 |
+
|
32 |
+
_LICENSE = (
|
33 |
+
"This work is licensed under the Creative Commons Attribution-ShareAlike "
|
34 |
+
"3.0 Unported License. To view a copy of this license, visit "
|
35 |
+
"http://creativecommons.org/licenses/by-sa/3.0/ or send a letter to "
|
36 |
+
"Creative Commons, PO Box 1866, Mountain View, CA 94042, USA."
|
37 |
+
)
|
38 |
+
|
39 |
+
_URL = "https://huggingface.co/datasets/joelito/EU_Wikipedias"
|
40 |
+
|
41 |
+
_LANGUAGES = ["bg", "cs", "da", "de", "el", "en", "es", "et", "fi", "fr", "ga", "hr",
|
42 |
+
"hu", "it", "lt", "lv", "mt", "nl", "pl", "pt", "ro", "sk", "sl", "sv"]
|
43 |
+
|
44 |
+
_DATES = ["20221120"] # one can add more in the future with the file prepare_wikipedias.py
|
45 |
+
|
46 |
+
|
47 |
+
class EUWikipediasConfig(datasets.BuilderConfig):
|
48 |
+
"""BuilderConfig for EUWikipedias."""
|
49 |
+
|
50 |
+
def __init__(self, date=None, language=None, **kwargs):
|
51 |
+
"""BuilderConfig for EUWikipedias.
|
52 |
+
Args:
|
53 |
+
language: string, the language code for the Wikipedia dump to use:
|
54 |
+
One of bg,cs,da,de,el,en,es,et,fi,fr,ga,hr,hu,it,lt,lv,mt,nl,pl,pt,ro,sk,sl,sv or all
|
55 |
+
date: string, date of the Wikipedia dump in YYYYMMDD format. A list of
|
56 |
+
available dates can be found at https://dumps.wikimedia.org/enwiki/.
|
57 |
+
**kwargs: keyword arguments forwarded to super.
|
58 |
+
"""
|
59 |
+
if date not in _DATES:
|
60 |
+
raise ValueError(f"date must be one of {_DATES} but was `{date}`")
|
61 |
+
if language not in _LANGUAGES + ["all"]:
|
62 |
+
raise ValueError(f"language must be one of {_LANGUAGES} but was `{language}`")
|
63 |
+
|
64 |
+
super().__init__(
|
65 |
+
name=f"{date}.{language}",
|
66 |
+
description=f"Wikipedia dataset for {language}, parsed from {date} dump.",
|
67 |
+
**kwargs,
|
68 |
+
)
|
69 |
+
self.date = date
|
70 |
+
self.language = language
|
71 |
+
|
72 |
+
|
73 |
+
class EUWikipedias(datasets.GeneratorBasedBuilder):
|
74 |
+
"""EUWikipedias: A dataset of Wikipedias in the EU languages"""
|
75 |
+
BUILDER_CONFIG_CLASS = EUWikipediasConfig
|
76 |
+
|
77 |
+
BUILDER_CONFIGS = [EUWikipediasConfig(date=date, language=language)
|
78 |
+
for language in _LANGUAGES + ["all"]
|
79 |
+
for date in _DATES]
|
80 |
+
|
81 |
+
def _info(self):
|
82 |
+
return datasets.DatasetInfo(
|
83 |
+
description=_DESCRIPTION,
|
84 |
+
features=datasets.Features(
|
85 |
+
{
|
86 |
+
"language": datasets.Value("string"),
|
87 |
+
"id": datasets.Value("string"),
|
88 |
+
"url": datasets.Value("string"),
|
89 |
+
"title": datasets.Value("string"),
|
90 |
+
"text": datasets.Value("string"),
|
91 |
+
}
|
92 |
+
),
|
93 |
+
supervised_keys=None, # No default supervised_keys.
|
94 |
+
homepage=_URL,
|
95 |
+
citation=_CITATION,
|
96 |
+
)
|
97 |
+
|
98 |
+
def _split_generators(self, dl_manager):
|
99 |
+
def download_url(dataset, file_name):
|
100 |
+
url = hf_hub_url(repo_id=dataset, filename=f"data/{file_name}.jsonl.xz", repo_type="dataset")
|
101 |
+
return dl_manager.download(url)
|
102 |
+
|
103 |
+
data_infos = []
|
104 |
+
languages = _LANGUAGES if self.config.language == "all" else [self.config.language]
|
105 |
+
|
106 |
+
for language in languages:
|
107 |
+
info = {"language": language}
|
108 |
+
for shard in range(50): # 50 shards per language at most (English has 10 in 20221120)
|
109 |
+
try:
|
110 |
+
info["filepath"] = download_url("joelito/EU_Wikipedias", f"{self.config.date}/{language}_{shard}")
|
111 |
+
data_infos.append(info.copy())
|
112 |
+
except:
|
113 |
+
break # we found the last shard
|
114 |
+
|
115 |
+
return [datasets.SplitGenerator(name=datasets.Split.TRAIN, gen_kwargs={"data_infos": data_infos})]
|
116 |
+
|
117 |
+
def _generate_examples(self, data_infos):
|
118 |
+
"""This function returns the examples in the raw (text) form by iterating on all the files."""
|
119 |
+
id_ = 0
|
120 |
+
for data_info in data_infos:
|
121 |
+
logger.info("Generating examples from = %s", data_info["filepath"])
|
122 |
+
try:
|
123 |
+
with xz.open(open(data_info["filepath"], "rb"), "rt", encoding="utf-8") as f:
|
124 |
+
for line in f:
|
125 |
+
if line:
|
126 |
+
example = json.loads(line)
|
127 |
+
if example is not None and isinstance(example, dict):
|
128 |
+
yield id_, {
|
129 |
+
"language": data_info["language"], # add the language
|
130 |
+
**example,
|
131 |
+
}
|
132 |
+
id_ += 1
|
133 |
+
except Exception:
|
134 |
+
logger.exception("Error while processing file %s", data_info["filepath"])
|
prepare_wikipedias.py
ADDED
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import glob
|
2 |
+
import os
|
3 |
+
|
4 |
+
from datasets import load_dataset
|
5 |
+
|
6 |
+
_LANGUAGES = ['bg', 'cs', 'da', 'de', 'el', 'en', 'es', 'et', 'fi', 'fr', 'ga', 'hr',
|
7 |
+
'hu', 'it', 'lt', 'lv', 'mt', 'nl', 'pl', 'pt', 'ro', 'sk', 'sl', 'sv']
|
8 |
+
ERROR_LANGS = ['et', 'ga'] # 20221101: ga somehow hangs at sample 36715/57711, for et no data is downloaded
|
9 |
+
ERROR_LANGS = [] # 20221120: no errors here
|
10 |
+
FINAL_LANGS = [l for l in _LANGUAGES if l not in ERROR_LANGS]
|
11 |
+
date = "20221120" # every 01 and 20 of the month, just edit this to generate newer data
|
12 |
+
|
13 |
+
base_dir = 'data'
|
14 |
+
date_dir = os.path.join(base_dir, date)
|
15 |
+
os.makedirs(date_dir, exist_ok=True)
|
16 |
+
|
17 |
+
max_file_size = 4 # GB
|
18 |
+
|
19 |
+
|
20 |
+
def process_language(LANG):
|
21 |
+
print(f'Processing language {LANG}...')
|
22 |
+
# streaming does not work here!
|
23 |
+
dataset = load_dataset("olm/wikipedia", language=LANG, date=date, split='train')
|
24 |
+
size_in_gb = dataset.size_in_bytes / 1e9
|
25 |
+
print(f'Found {size_in_gb} GB of data ({len(dataset)} documents) for language {LANG}...')
|
26 |
+
if size_in_gb > max_file_size:
|
27 |
+
num_shards = int(size_in_gb / max_file_size) + 1
|
28 |
+
for shard in range(num_shards):
|
29 |
+
dataset.shard(num_shards, shard).to_json(f'{date_dir}/{LANG}_{shard}.jsonl', lines=True)
|
30 |
+
else:
|
31 |
+
dataset.to_json(f'{date_dir}/{LANG}_0.jsonl', lines=True)
|
32 |
+
|
33 |
+
|
34 |
+
if __name__ == '__main__':
|
35 |
+
"""
|
36 |
+
Run with
|
37 |
+
export PYTHONPATH=. && python prepare_wikipedias.py | tee prepare_wikipedias.log
|
38 |
+
"""
|
39 |
+
# it does not work in parallel
|
40 |
+
for LANG in FINAL_LANGS:
|
41 |
+
process_language(LANG)
|
42 |
+
|
43 |
+
# Compress datasets
|
44 |
+
print(f"Compressing datasets at {date_dir}")
|
45 |
+
# Do this at the end because we use multithreading
|
46 |
+
for path in glob.glob(os.path.join(date_dir, '*.jsonl')):
|
47 |
+
os.system(f'xz -zkf -T0 {path}') # -TO to use multithreading
|
48 |
+
# os.system(f'rm {path}') # remove uncompressed file to save space
|