hplt_monolingual_v1_2 / hplt_monolingual_v1_2.py
BramVanroy's picture
Add better logging error when JSON loads fails
7c1b3db verified
"""Data loading script for HPLT Monolingual Release v1.2."""
import json
import logging
from json import JSONDecodeError
from pathlib import Path
from typing import List
import datasets
_DESCRIPTION = """\
Data release 1.2 of the monolingual portion of HPLT (December 2023)
There are 75 languages in this release (22 TB of raw files, 11 TB of deduped files and 8.4 TB of clean files) provided as JSONL files compressed with zstd. For convenience, data is split into multiple shards, a few GB each. The number of shards per language depends on the size of the specific corpus.
"""
_HOMEPAGE = "https://hplt-project.org/"
_LICENSE = "CC0"
_PROCTYPE2URL = {
"": "https://data.hplt-project.org/one/monotext/{code}_map.txt",
"deduplicated": "https://data.hplt-project.org/one/monotext/deduplicated/{code}_map.txt",
"cleaned": "https://data.hplt-project.org/one/monotext/cleaned/{code}_map.txt",
}
_CODE2LANG = {
"af": "Afrikaans",
"ar": "Arabic",
"az": "Azerbaijani",
"be": "Belarusian",
"bg": "Bulgarian",
"bn": "Bangla",
"ca": "Catalan",
"cs": "Czech",
"cy": "Welsh",
"da": "Danish",
"de": "German",
"el": "Greek",
"en": "English",
"eo": "Esperanto",
"es": "Spanish",
"et": "Estonian",
"eu": "Basque",
"fa": "Persian",
"fi": "Finnish",
"fr": "French",
"ga": "Irish",
"gl": "Galician",
"gu": "Gujarati",
"hbs": "Serbo-Croatian",
"he": "Hebrew",
"hi": "Hindi",
"hu": "Hungarian",
"hy": "Armenian",
"id": "Indonesian",
"is": "Icelandic",
"it": "Italian",
"ja": "Japanese",
"ka": "Georgian",
"kk": "Kazakh",
"kn": "Kannada",
"ko": "Korean",
"ky": "Kyrgyz",
"la": "Latin",
"lt": "Lithuanian",
"lv": "Latvian",
"mk": "Macedonian",
"ml": "Malayalam",
"mn": "Mongolian",
"mr": "Marathi",
"ms": "Malay",
"mt": "Maltese",
"my": "Burmese",
"nb": "Norwegian Bokmål",
"ne": "Nepali",
"nl": "Dutch",
"nn": "Norwegian Nynorsk",
"pa": "Punjabi",
"pl": "Polish",
"ps": "Pashto",
"pt": "Portuguese",
"ro": "Romanian",
"ru": "Russian",
"si": "Sinhala",
"sk": "Slovak",
"sl": "Slovenian",
"so": "Somali",
"sq": "Albanian",
"sv": "Swedish",
"sw": "Swahili",
"ta": "Tamil",
"te": "Telugu",
"th": "Thai",
"tl": "Filipino",
"tr": "Turkish",
"tt": "Tatar",
"uk": "Ukrainian",
"ur": "Urdu",
"uz": "Uzbek",
"vi": "Vietnamese",
"zh": "Chinese",
}
_SUPPORTED_LANG_STR = "* " + "\n* ".join([f"{code}: {lang}" for code, lang in _CODE2LANG.items()])
_VERSION = "1.2.0"
class Hplt_monolingual_v1_2(datasets.GeneratorBasedBuilder):
"""Release v1.2 of the HPLT monolingual datasets."""
VERSION = datasets.Version(_VERSION)
BUILDER_CONFIGS = [
datasets.BuilderConfig(
name=f"{code}_{proc_type}" if proc_type else code,
version=datasets.Version(_VERSION),
description=f"{lang}{' ('+proc_type+')' if proc_type else ''} - HPLT {_VERSION}",
)
for code, lang in _CODE2LANG.items()
for proc_type in _PROCTYPE2URL
]
def _info(self):
features = datasets.Features(
{
"id": datasets.Value("int64"),
"document_lang": datasets.Value("string"),
"scores": datasets.Sequence(datasets.Value("float64")),
"langs": datasets.Sequence(datasets.Value("string")),
"text": datasets.Value("string"),
"url": datasets.Value("string"),
"collection": datasets.Value("string"),
}
)
return datasets.DatasetInfo(
description=_DESCRIPTION,
features=features,
homepage=_HOMEPAGE,
license=_LICENSE,
)
def _split_generators(self, dl_manager):
error_msg = (
"You can choose any of the supported language codes as-is, or the `deduplicated` or `cleaned` versions,"
f" e.g. nl, nl_deduplicated, nl_cleaned.\nSupported languages are:\n{_SUPPORTED_LANG_STR}"
)
# Get the language code and type (default emptry string ``, `deduplicated`, or `cleaned`)
try:
if "_" in self.config.name:
langcode, proctype = self.config.name.split("_", 1)
url = _PROCTYPE2URL[proctype].format(code=langcode)
else:
url = _PROCTYPE2URL[""].format(code=self.config.name)
except Exception as exc:
raise ValueError(f"Error reading the entered config '{self.config.name}'. {error_msg}") from exc
try:
pf_json_list = Path(dl_manager.download(url)).resolve()
except Exception as exc:
raise KeyError(
f"Error downloading JSONL overview. This may indicate a problem with the server OR you entered an"
f" unsupported language.\n{error_msg}"
) from exc
data_urls = [
lstrip for line in pf_json_list.read_text(encoding="utf-8").splitlines() if (lstrip := line.strip())
]
pfs_data = [Path(url) for url in dl_manager.download_and_extract(data_urls)]
return [
datasets.SplitGenerator(
name=datasets.Split.TRAIN,
gen_kwargs={
"pfs_data": pfs_data,
},
)
]
def _generate_examples(self, pfs_data: List[Path]):
# Apparently a unique key for each sample is recommended for legacy tfds reasons
# https://github.com/huggingface/datasets/blob/e52f4d0cf1cb89a9719b42fff13a891f92d51e04/templates/new_dataset_script.py#L156
document_idx = 1
for pfin in pfs_data:
with pfin.open(encoding="utf-8") as fhin:
for line_idx, line in enumerate(fhin, 1):
line = line.strip()
if not line:
continue
try:
data = json.loads(line)
except JSONDecodeError as exc:
logging.error(f"Error parsing JSON! Line will be skipped...\n- file {pfin}\n- line no. {line_idx:,}\n- line: {line}\n- error: {exc}")
continue
yield document_idx, {
"id": document_idx,
"document_lang": data["document_lang"],
"scores": data["scores"],
"langs": data["langs"],
"text": data["text"],
"url": data["url"],
"collection": data["collection"],
}
document_idx += 1