Multi_Legal_Pile / Multi_Legal_Pile.py
joelniklaus's picture
removed more data from pile-of-law, added more documentation and added three more datasets
47c0146
raw
history blame
12.1 kB
"""Multi Legal Pile"""
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/Multi_Legal_Pile"
# Specific Data
_DATA_NAME = {
"bg": {
"legislation": ["bulgaria_marcell"],
},
"cs": {
"caselaw": ["czechia_constitutional_court", "czechia_supreme_administrative_court", "czechia_supreme_court"],
},
"da": {
"caselaw": ["denmark_ddsc"],
"legislation": ["denmark_ddsc"],
},
"de": {
"caselaw": ["germany_openlegaldata"],
"legislation": ["germany_openlegaldata", "switzerland_lexfind"],
},
"en": {
"legislation": ["switzerland_lexfind"],
},
"fr": {
"caselaw": ["belgium_jurportal", "france_cass", "luxembourg_judoc"],
"legislation": ["belgium_ejustice", "switzerland_lexfind"],
},
"hu": {
"caselaw": ["hungary_marcell"],
},
"it": {
"legislation": ["switzerland_lexfind"],
},
"nl": {
"legislation": ["belgium_ejustice"],
},
"pl": {
"legislation": ["poland_marcell"],
},
"pt": {
"caselaw": ["barzil_ruling_br"],
},
"ro": {
"legislation": ["romania_marcell"],
},
"sk": {
"legislation": ["slovakia_marcell"],
},
"sl": {
"legislation": ["slovenia_marcell"],
},
}
_PILE_OF_LAW_NAMES = {
"caselaw": {
"courtlistener_opinions": {
"train": [
"train.courtlisteneropinions.0",
"train.courtlisteneropinions.1",
"train.courtlisteneropinions.2",
"train.courtlisteneropinions.3",
"train.courtlisteneropinions.4",
"train.courtlisteneropinions.5",
"train.courtlisteneropinions.6",
"train.courtlisteneropinions.7",
"train.courtlisteneropinions.8",
"train.courtlisteneropinions.9",
],
"validation": [
"validation.courtlisteneropinions.0",
"validation.courtlisteneropinions.1",
"validation.courtlisteneropinions.2",
"validation.courtlisteneropinions.3"
]
},
"courtlistener_docket_entry_documents": {
"train": [
"train.courtlistenerdocketentries.0",
"train.courtlistenerdocketentries.1",
"train.courtlistenerdocketentries.2",
"train.courtlistenerdocketentries.3"
],
"validation": [
"validation.courtlistenerdocketentries.0",
"validation.courtlistenerdocketentries.1"
]
},
"scotus_filings": {
"train": ["train.scotus_docket_entries"],
"validation": ["validation.scotus_docket_entries"]
},
"echr": {
"train": ["train.echr"],
"validation": ["validation.echr"]
},
"canadian_decisions": {
"train": ["train.canadian_decisions"],
"validation": ["validation.canadian_decisions"]
},
},
"contracts": {
"atticus_contracts": {
"train": [
"train.atticus_contracts.0",
"train.atticus_contracts.1",
"train.atticus_contracts.2",
"train.atticus_contracts.3",
"train.atticus_contracts.4"
],
"validation": [
"validation.atticus_contracts.0",
"validation.atticus_contracts.1"
]
},
"edgar": {
"train": ["train.edgar"],
"validation": ["validation.edgar"]
},
"cfpb_creditcard_contracts": {
"train": ["train.cfpb_cc"],
"validation": ["validation.cfpb_cc"]
},
},
"legislation": {
"uscode": {
"train": ["train.uscode"],
"validation": ["validation.uscode"]
},
"state_codes": {
"train": ["train.state_code"],
"validation": ["validation.state_code"]
},
"us_bills": {
"train": ["train.us_bills"],
"validation": ["validation.us_bills"]
},
"federal_register": {
"train": ["train.federal_register"],
"validation": ["validation.federal_register"]
},
"cfr": {
"train": ["train.cfr"],
"validation": ["validation.cfr"]
},
"constitutions": {
"train": ["train.constitutions"],
"validation": ["validation.constitutions"]
},
},
"other": { # analyses
"oig": {
"train": ["train.oig"],
"validation": ["validation.oig"]
},
"olc_memos": {
"train": ["train.olcmemos"],
"validation": ["validation.olcmemos"]
},
},
}
_LANGUAGES = ["bg", "cs", "da", "de", "el", "en", "es", "et", "fi", "fr", "ga", "hr",
"hu", "it", "lt", "lv", "mt", "nl", "pl", "pt", "ro", "sk", "sl", "sv"]
_TYPES = ["caselaw", "contracts", "legislation", "other"]
_JURISDICTONS = ["Austria", "Belgium", "Bulgaria", "Croatia", "Czechia", "Denmark", "Estonia", "Finland",
"France", "Germany", "Greece", "Hungary", "Ireland", "Italy", "Latvia", "Lithuania", "Luxembourg",
"Malta", "Netherlands", "Poland", "Portugal", "Romania", "Slovakia", "Slovenia", "Spain", "Sweden",
"EU", "Switzerland", "UK", "US", "Canada", "N/A"]
class MultiLegalPileConfig(datasets.BuilderConfig):
"""BuilderConfig for MultiLegalPile."""
def __init__(self, name: str, **kwargs):
"""BuilderConfig for MultiLegalPile.
Args:
name: combination of language and type with _
language: 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
type: One of caselaw,contracts,legislation,other or all
**kwargs: keyword arguments forwarded to super.
"""
super(MultiLegalPileConfig, self).__init__(**kwargs)
self.name = name
self.language = name.split("_")[0]
self.type = name.split("_")[1]
class MultiLegalPile(datasets.GeneratorBasedBuilder):
"""MultiLegalPile: A Corpus Covering Large-Scale Multilingual Legal Data"""
BUILDER_CONFIGS = [MultiLegalPileConfig(f"{language}_{type}")
for type in _TYPES + ["all"]
for language in _LANGUAGES + ["all"]]
def _info(self):
return datasets.DatasetInfo(
description=_DESCRIPTION,
features=datasets.Features(
{
"language": datasets.Value("string"), # one of _LANGUAGES
"type": datasets.Value("string"), # one of _TYPES
"jurisdiction": datasets.Value("string"), # one of _JURISDICTONS
"text": datasets.Value("string"),
}
),
supervised_keys=None,
homepage=_URL,
citation=_CITATION,
)
def _split_generators(self, dl_manager):
def download_url(dataset, file_name):
url = hf_hub_url(repo_id=dataset, filename=f"data/{file_name}.jsonl.xz", repo_type="dataset")
return dl_manager.download(url)
data_infos = []
languages = _LANGUAGES if self.config.language == "all" else [self.config.language]
types = _TYPES if self.config.type == "all" else [self.config.type]
for language in languages:
for type in types:
info = {"language": language, "type": type}
# add native MultiLegalPile data
if language in _DATA_NAME and type in _DATA_NAME[language]: # if we actually have something there
for data_name in _DATA_NAME[language][type]:
info["filepath"] = download_url("Multi_Legal_Pile", data_name)
data_infos.append(info.copy())
# add eurlex_resources data
info["jurisdiction"] = "EU"
if type == 'caselaw':
info["filepath"] = download_url("joelito/eurlex_resources", f"{language}/caselaw")
data_infos.append(info.copy())
elif type == 'legislation':
for resource_type in ["decision", "directive", "regulation", "recommendation", "proposal"]:
info["filepath"] = download_url("joelito/eurlex_resources", f"{language}/{resource_type}")
data_infos.append(info.copy())
elif type == 'contracts':
# international agreements
info["filepath"] = download_url("joelito/eurlex_resources", f"{language}/intagr")
data_infos.append(info.copy())
# add mc4_legal data
if type == 'other':
info["jurisdiction"] = "N/A"
if language in ["de", "en", "es"]: # here we need to chunk because the files are too large
for idx in [0, 1]:
info["filepath"] = download_url("joelito/mc4_legal", f"{language}_{idx}")
data_infos.append(info.copy())
elif language in ["hr"]:
pass # nothing there for Croatian
else:
info["filepath"] = download_url("joelito/mc4_legal", f"{language}")
data_infos.append(info.copy())
# add pile-of-law data
if language == 'en':
info["jurisdiction"] = "US"
for name, train_val_files in _PILE_OF_LAW_NAMES[type].items():
if name == 'canadian_decisions':
info["jurisdiction"] = "Canada"
elif name in ['echr']:
info["jurisdiction"] = "EU"
elif name in ['constitutions']:
info["jurisdiction"] = "N/A"
for split in ["train", "validation"]:
for file_name in train_val_files[split]:
info["filepath"] = download_url("pile-of-law/pile-of-law", file_name)
data_infos.append(info.copy())
return [datasets.SplitGenerator(name=datasets.Split.TRAIN, gen_kwargs={"data_infos": data_infos})]
def _generate_examples(self, data_infos):
"""This function returns the examples in the raw (text) form by iterating on all the files."""
id_ = 0
for data_info in data_infos:
logger.info("Generating examples from = %s", data_info["filepath"])
try:
with xz.open(open(data_info["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):
yield id_, {
# uses the default values for language, type and jurisdiction if it is not set
"language": example.get("language", data_info["language"]),
"type": example.get("type", data_info["type"]),
"jurisdiction": example.get("jurisdiction", data_info["jurisdiction"]),
"text": example.get("text", ""),
}
id_ += 1
except:
print("Error reading file:", data_info["filepath"])