Multi_Legal_Pile / Multi_Legal_Pile.py
joelniklaus's picture
fixed bug
86f2280
raw
history blame
18 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 = """
Multi Legal Pile is a dataset of legal documents in the 24 EU languages.
"""
_CITATION = """
"""
_URL = "https://huggingface.co/datasets/joelito/Multi_Legal_Pile"
VERSION = datasets.Version("1.0.0", "")
# IMPORTANT: Types should not have underscores in this dataset
CASELAW = "caselaw"
LEGISLATION = "legislation"
CONTRACTS = "contracts"
OTHER = "other"
LEGAL_MC4 = "legal-mc4"
# Native MultiLegalPile
_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", "switzerland_entscheidsuche"],
LEGISLATION: ["germany_openlegaldata", "switzerland_lexfind"],
},
"en": {
LEGISLATION: ["switzerland_lexfind", "uk_uk_lex"],
},
"fr": {
CASELAW: ["belgium_jurportal", "france_cass", "luxembourg_judoc", "switzerland_entscheidsuche"],
LEGISLATION: ["belgium_ejustice", "switzerland_lexfind"],
},
"hu": {
LEGISLATION: ["hungary_marcell"],
},
"it": {
CASELAW: ["switzerland_entscheidsuche"],
LEGISLATION: ["switzerland_lexfind"],
},
"nl": {
LEGISLATION: ["belgium_ejustice"],
},
"pl": {
LEGISLATION: ["poland_marcell"],
},
"pt": {
CASELAW: ["brazil_rulingbr", "brazil_creta",
"brazil_cjpg_0", "brazil_cjpg_1", "brazil_cjpg_2", "brazil_cjpg_3", "brazil_cjpg_4"],
},
"ro": {
LEGISLATION: ["romania_marcell"],
},
"sk": {
LEGISLATION: ["slovakia_marcell"],
},
"sl": {
LEGISLATION: ["slovenia_marcell"],
},
}
# PileOfLaw
_PILE_OF_LAW_NAMES = {
CASELAW: {
"courtlistener_docket_entry_documents": {
"train": [
"train.courtlistenerdocketentries.0",
"train.courtlistenerdocketentries.1",
"train.courtlistenerdocketentries.2",
"train.courtlistenerdocketentries.3"
],
"validation": [
"validation.courtlistenerdocketentries.0",
"validation.courtlistenerdocketentries.1"
]
},
"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",
"train.courtlisteneropinions.10",
"train.courtlisteneropinions.11",
"train.courtlisteneropinions.12",
"train.courtlisteneropinions.13",
"train.courtlisteneropinions.14",
"train.courtlisteneropinions.15"
],
"validation": [
"validation.courtlisteneropinions.0",
"validation.courtlisteneropinions.1",
"validation.courtlisteneropinions.2",
"validation.courtlisteneropinions.3",
"validation.courtlisteneropinions.4",
"validation.courtlisteneropinions.5"
]
},
"bva_opinions": {
"train": ["train.bva"],
"validation": ["validation.bva"]
},
"nlrb_decisions": {
"train": ["train.nlrb_decisions"],
"validation": ["validation.nlrb_decisions"]
},
"scotus_oral_arguments": {
"train": ["train.scotus_oral"],
"validation": ["validation.scotus_oral"]
},
"scotus_filings": {
"train": ["train.scotus_docket_entries"],
"validation": ["validation.scotus_docket_entries"]
},
"ftc_advisory_opinions": {
"train": ["train.ftc_advisory_opinions"],
"validation": ["validation.ftc_advisory_opinions"]
},
"echr": {
"train": ["train.echr"],
"validation": ["validation.echr"]
},
"tax_rulings": {
"train": ["train.taxrulings"],
"validation": ["validation.taxrulings"]
},
"canadian_decisions": {
"train": ["train.canadian_decisions"],
"validation": ["validation.canadian_decisions"]
},
"eoir": {
"train": ["train.eoir"],
"validation": ["validation.eoir"]
},
"dol_ecab": {
"train": ["train.dol_ecab"],
"validation": ["validation.dol_ecab"]
},
"icj-pcij": {
"train": ["train.ijc"],
"validation": ["validation.ijc"]
},
"hhs_alj_opinions": {
"train": ["train.hhs_alj"],
"validation": ["validation.hhs_alj"]
},
"sec_administrative_proceedings": {
"train": ["train.sec"],
"validation": ["validation.sec"]
},
},
LEGISLATION: {
"federal_register": {
"train": ["train.federal_register"],
"validation": ["validation.federal_register"]
},
"us_bills": {
"train": ["train.us_bills"],
"validation": ["validation.us_bills"]
},
"cfr": {
"train": ["train.cfr"],
"validation": ["validation.cfr"]
},
"state_codes": {
"train": ["train.state_code"],
"validation": ["validation.state_code"]
},
"constitutions": {
"train": ["train.constitutions"],
"validation": ["validation.constitutions"]
},
"uscode": {
"train": ["train.uscode"],
"validation": ["validation.uscode"]
},
"founding_docs": {
"train": ["train.founding_docs"],
"validation": ["validation.founding_docs"]
},
"eurlex": {
"train": ["train.eurlex"],
"validation": ["validation.eurlex"]
},
"fre": {
"train": ["train.fre"],
"validation": ["validation.fre"]
},
"frcp": {
"train": ["train.frcp"],
"validation": ["validation.frcp"]
},
},
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"
]
},
"tos": {
"train": ["train.tos"],
"validation": ["validation.tos"]
},
"edgar": {
"train": ["train.edgar"],
"validation": ["validation.edgar"]
},
"cfpb_creditcard_contracts": {
"train": ["train.cfpb_cc"],
"validation": ["validation.cfpb_cc"]
},
"resource_contracts": {
"train": ["train.resource_contracts"],
"validation": ["validation.resource_contracts"]
},
},
OTHER: {
"r_legaladvice":
{
"train": ["train.r_legaldvice"],
"validation": ["validation.r_legaldvice"]
},
"cc_casebooks": {
"train": ["train.cc_casebooks"],
"validation": ["validation.cc_casebooks"]
},
"euro_parl": {
"train": ["train.euro_parl"],
"validation": ["validation.euro_parl"]
},
"exam_outlines": {
"train": [
"train.examoutlines",
],
"validation": [
"validation.examoutlines",
]
},
"congressional_hearings": {
"train": ["train.congressional_hearings"],
"validation": ["validation.congressional_hearings"]
},
"oig": {
"train": ["train.oig"],
"validation": ["validation.oig"]
},
"olc_memos": {
"train": ["train.olc_memos"],
"validation": ["validation.olc_memos"]
},
"un_debates": {
"train": ["train.undebates"],
"validation": ["validation.undebates"]
},
"uspto_office_actions": {
"train": ["train.uspto_oab"],
"validation": ["validation.uspto_oab"]
},
"ed_policy_guidance": {
"train": ["train.ed_policy_guidance"],
"validation": ["validation.ed_policy_guidance"]
},
"acus_reports": {
"train": ["train.acus_reports"],
"validation": ["validation.acus_reports"]
},
"fmshrc_bluebooks": {
"train": ["train.fmshrc"],
"validation": ["validation.fmshrc"]
},
"medicaid_policy_guidance": {
"train": ["train.medicaid_policy_guidance"],
"validation": ["validation.medicaid_policy_guidance"]
},
"irs_legal_advice_memos": {
"train": ["train.irs_legal_advice_memos"],
"validation": ["validation.irs_legal_advice_memos"]
},
"doj_guidance_documents": {
"train": ["train.doj_guidance"],
"validation": ["validation.doj_guidance"]
}
},
LEGAL_MC4: {}
}
_LEGAL_MC4_SHARDS = {
"bg": 0,
"cs": 2,
"da": 0,
"de": 8,
"el": 0,
"en": 1,
"es": 9,
"et": 0,
"fi": 0,
"fr": 2,
"ga": 0,
# "hr", # hr is not present in mc4
"hu": 0,
"it": 3,
"lt": 0,
"lv": 0,
"mt": 0,
"nl": 0,
"pl": 2,
"pt": 1,
"ro": 0,
"sk": 0,
"sl": 0,
"sv": 0,
}
_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, LEGAL_MC4]
_JURISDICTIONS = ["Austria", "Belgium", "Brazil", "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, repo_data_only=False, **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,legal-mc4 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]
self.repo_data_only = repo_data_only
class MultiLegalPile(datasets.GeneratorBasedBuilder):
"""MultiLegalPile: A Corpus Covering Large-Scale Multilingual Legal Data"""
BUILDER_CONFIG_CLASS = MultiLegalPileConfig
BUILDER_CONFIGS = [MultiLegalPileConfig(f"{language}_{type}",
version=VERSION,
description=f"MultiLegalPile for language {language} and type {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 _JURISDICTIONS
"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["jurisdiction"] = data_name.split("_")[0].capitalize()
info["filepath"] = download_url("joelito/Multi_Legal_Pile", f"{language}/{type}/{data_name}")
data_infos.append(info.copy())
if not self.config.repo_data_only:
# 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 legal-mc4 data
if type == LEGAL_MC4:
info["jurisdiction"] = "N/A"
if language == "hr":
pass
else:
for split in ["train", "validation"]:
shards = range(_LEGAL_MC4_SHARDS[language] + 1) if split == "train" else [0]
for shard in shards:
info["filepath"] = download_url("joelito/legal-mc4", f"{language}.{split}.{shard}")
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', 'eurlex', 'euro_parl']:
info["jurisdiction"] = "EU"
elif name in ['constitutions', 'icj-pcij', 'r_legaladvice', 'un_debates', 'tos']:
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 Exception:
logger.exception("Error while processing file %s", data_info["filepath"])