"""MC4_Legal""" import ast import json import datasets from huggingface_hub.file_download import hf_hub_url try: import lzma as xz except ImportError: import pylzma as xz datasets.logging.set_verbosity_info() logger = datasets.logging.get_logger(__name__) _DESCRIPTION = """ """ _CITATION = """ """ _URL = "https://huggingface.co/datasets/joelito/mc4_legal" _LANGUAGES = [ "bg", "cs", "da", "de", "el", "en", "es", "et", "fi", "fr", "ga", # "hr", # hr is not present in mc4 "hu", "it", "lt", "lv", "mt", "nl", "pl", "pt", "ro", "sk", "sl", "sv", ] class MC4LegalConfig(datasets.BuilderConfig): """BuilderConfig for MC4_Legal.""" def __init__(self, name: str, **kwargs): """BuilderConfig for MC4_Legal. Args: name: One of bg,cs,da,de,el,en,es,et,fi,fr,ga,hu,it,lt,lv,mt,nl,pl,pt,ro,sk,sl,sv or all **kwargs: keyword arguments forwarded to super. """ super(MC4LegalConfig, self).__init__(**kwargs) self.name = name class MC4Legal(datasets.GeneratorBasedBuilder): """MC4_Legal: A Corpus Covering the Legal Part of MC4 for European Languages""" BUILDER_CONFIGS = [MC4LegalConfig(language) for language in _LANGUAGES + ["all"]] def _info(self): return datasets.DatasetInfo( description=_DESCRIPTION, features=datasets.Features( { "index": datasets.Value("int32"), "url": datasets.Value("string"), "timestamp": datasets.Value("timestamp[s]"), "matches": datasets.Sequence(datasets.Value("string")), "text": datasets.Value("string"), } ), supervised_keys=None, homepage=_URL, citation=_CITATION, ) def _split_generators(self, dl_manager): def get_url(file_name): return hf_hub_url(repo_id="joelito/mc4_legal", filename=f"data/{file_name}.jsonl.xz", repo_type="dataset") data_urls = [] languages = _LANGUAGES if self.config.name == "all" else [self.config.name] for language in languages: if language in ["de", "en", "es"]: # here we need to chunk because the files are too large data_urls.extend([get_url(f"{language}_{idx}") for idx in [0, 1]]) else: data_urls.append(get_url(language)) downloaded_files = dl_manager.download(data_urls) return [datasets.SplitGenerator(name=datasets.Split.TRAIN, gen_kwargs={"filepaths": downloaded_files})] 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 xz.open(open(filepath, "rb"), "rt", encoding="utf-8") as f: for line in f: if line: example = json.loads(line) if example is not None and isinstance(example, dict): timestamp = example.get("timestamp", "") # remove the Z at the end (time zone) if isinstance(timestamp, str) and timestamp.endswith("Z"): timestamp = timestamp[:-1] yield id_, { "index": example.get("index", ""), "url": example.get("url", ""), "timestamp": timestamp, "matches": ast.literal_eval(example.get("matches", "")), "text": example.get("text", ""), } id_ += 1 except Exception: logger.exception("Error while processing file %s", filepath)