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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
"""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_Commercial"

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"],
    },
    "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_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"]
        },
        "eoir": {
            "train": ["train.eoir"],
            "validation": ["validation.eoir"]
        },
        "dol_ecab": {
            "train": ["train.dol_ecab"],
            "validation": ["validation.dol_ecab"]
        },
        "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"]
        },
        "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"
            ]
        },
        "resource_contracts": {
            "train": ["train.resource_contracts"],
            "validation": ["validation.resource_contracts"]
        },
    },
    OTHER: {
        "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"])