Coverage for src/courtpy/wrangler/loaders.py: 98%
127 statements
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-22 15:51 +0000
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-22 15:51 +0000
1"""Techniques that load court cases into an `amos` project.
3Loaders make a project's data from a source named in its settings, so a
4project with a loader needs no `item`. They are usually the first step of the
5wrangler, and they work through the project's clerk (its
6`nagata.FileManager`): a folder or file named by a relative path is looked
7for in the current folder and then in the clerk's input folder (the
8"input_folder" of the "files" section), and downloads are saved in the input
9folder.
11courtpy's loaders collect court cases (downloading or dividing them first, if
12asked), parse them with rulebooks, and code them, so the label of a study
13(such as "outcome_reversal", which a coder makes) exists when the data is
14loaded. As with reference data, `load_courtlistener` parses the cases that
15were saved before, and `download_courtlistener` downloads them first (from
16CourtListener's bulk data, unless "method" is "api"):
18```ini
19[general]
20seed = 43
21label = outcome_reversal
23[files]
24input_folder = data
26[appeals_project]
27appeals_workers = wrangler, analyst, critic
29[wrangler]
30techniques = download_courtlistener, drop_text_columns
32[download_courtlistener_parameters]
33source = courtlistener
34method = bulk
35courts = federal_geographic_circuits
36start_date = 2019-01-01
37end_date = 2019-12-31
38save = cases.csv
39reuse = true
40```
42Every loader takes these parameters, set in its "{name}_parameters" section:
44| Parameter | Meaning |
45| --- | --- |
46| `source` | The folder of saved cases (or, for `load_cases`, a saved table). |
47| `coders` | Techniques to apply after parsing. Defaults to "code_parties, code_case_type, code_outcome" ("none" for `load_cases`). Use "none" for none. |
48| `save` | File to save the coded table to (".csv", ".parquet", or ".xlsx"), with the whole dataset beside it in a joblib file of the same name (see `Cases.save`). A relative path is in the clerk's interim folder. |
49| `reuse` | Whether to load the saved dataset, if there is one, instead of collecting, parsing, and coding the cases again. Defaults to false. |
50| `label`, `task`, `groups` | As in `amos`: they default to those in the "general" section. |
52Other modules add reference loaders (see `ReferenceLoader`), which load a
53table that describes something other than cases. Each "load_" technique
54loads the files that courtpy keeps (or a file named as its "source"), and
55each "download_" technique downloads the files first, again if "refresh" is
56true:
58| Technique | Table | Module |
59| --- | --- | --- |
60| `load_roster`, `download_biographies` | A roster of judges. | `courtpy.judges` |
61| `load_scdb`, `download_scdb` | The Supreme Court Database's cases or votes. | `courtpy.scdb` |
62| `load_idb`, `download_idb` | The Integrated Database's appeals. | `courtpy.fjc_idb` |
63| `load_politics`, `download_politics` | The political context of each year. | `courtpy.politics` |
64| `download_jcs` | The Judicial Common Space scores. | `courtpy.jcs` |
66Contents:
67 CaseLoader: base class for techniques that load court cases.
68 LoadCases: loads a dataset of cases saved by `Cases.save`, or a table of
69 one.
70 DownloadCourtlistener: downloads CourtListener cases, and parses and
71 codes them.
72 LoadCourtlistener: parses and codes saved CourtListener cases.
73 LoadLexisNexis: divides, parses, and codes Lexis-Nexis cases.
74 ReferenceLoader: base class for techniques that load a table of
75 reference data, such as `load_scdb` and `download_biographies`.
76 SourceLoader: base class for loaders that parse a folder of a source's
77 saved cases.
79"""
81from __future__ import annotations
83import abc
84import dataclasses
85import pathlib
86from typing import Any, ClassVar
88import amos
89import pandas as pd
91from ..core import datasets, options, utilities
93# Importing the modules of the sources adds them to `base.SOURCES`.
94from ..sources import courtlistener, lexis
95from . import coders, parsers
98@dataclasses.dataclass
99class CaseLoader(amos.Loader, abc.ABC):
100 """Base class for techniques that load court cases.
102 A subclass writes `load`, which collects and parses the cases at a source
103 (a folder or file, already found with the clerk) and returns a table of
104 them, one row for each case. `apply` then codes the table with the
105 loader's "coders", saves it if "save" is set, and makes it the dataset
106 that the rest of the workflow works on, with the label, task, and groups
107 from the loader's parameters (which default to the "general" section of
108 the settings). The label can be a column that a coder makes. If no coder
109 makes it, it is pending, as in `amos`: a later technique (such as
110 "derive_columns") can still make it, and using it before then raises an
111 error. The dataset's history records the loader and then each coder.
113 The dataset is `Cases`, or the kind that the last of the coders makes
114 (such as `Votes`, if "cases_to_votes" is the last). If "save" is set, it
115 is saved with `CourtData.save`: whole, in a joblib file beside the table
116 (such as "cases.joblib" beside "cases.csv"), and as the table. If
117 "reuse" is true and it was saved before, the saved dataset is loaded
118 instead (from the joblib file, or else from the table), and nothing is
119 collected, parsed, or coded again.
121 Args:
122 name: name used to refer to the technique in a workflow. Defaults to
123 `None`, in which case it is the snake case name of the class.
124 contents: not used. Defaults to `None`.
125 parameters: "source", "coders", "save", "reuse", "label", "task", and
126 "groups" (see the module's documentation), and parameters for
127 `load`. Defaults to an empty `dict`.
128 clerk: the file manager that finds folders and files. Defaults to
129 `None`, in which case one for the current folder is made when it
130 is needed. A loader built from a project's settings uses the
131 project's clerk.
133 Attributes:
134 default_coders: the coders applied when "coders" is not set.
135 default_source: the source used when "source" is not set, or `None`
136 if a source must be set.
138 """
140 default_coders: ClassVar[tuple[str, ...]] = options._DEFAULT_CODERS
141 default_source: ClassVar[str | None] = None
143 """ Public Methods """
145 def apply(self, item: amos.Dataset, **kwargs: Any) -> amos.Dataset:
146 """Loads, codes, and saves the cases, as a dataset continuing `item`.
148 Args:
149 item: the dataset so far, whose seed and history are kept.
150 **kwargs: "source", "coders", "save", "reuse", "label", "task", and
151 "groups", and parameters for `load`.
153 Raises:
154 ValueError: if there is no "source" and the loader has no default
155 source.
157 Returns:
158 The dataset of the coded cases.
160 """
161 source = kwargs.pop('source', None) or self.default_source
162 if source is None:
163 message = (
164 f'{self.name!r} has nothing to load: set its "source" in the '
165 f'"{self.name}_parameters" section of the settings'
166 )
167 raise ValueError(message)
168 label = kwargs.pop('label', None) or item.label
169 task = kwargs.pop('task', None)
170 groups = kwargs.pop('groups', None) or item.groups or None
171 names = kwargs.pop('coders', self.default_coders)
172 save = kwargs.pop('save', None)
173 reuse = utilities.to_bool(kwargs.pop('reuse', False))
174 saved = self._interim(save) if save else None
175 reused = _reusable(saved) if saved is not None and reuse else None
176 dataset: amos.Dataset
177 if reused is not None:
178 dataset = LoadCases().load(reused)
179 dataset.seed = item.seed
180 dataset.history = [*item.history, *dataset.history]
181 dataset.record(
182 self.name, source = str(source), reused = str(reused),
183 rows = len(dataset.data), columns = len(dataset.data.columns))
184 else:
185 loaded = self.load(self._locate(source), **kwargs)
186 if isinstance(loaded, amos.Dataset):
187 dataset = loaded
188 dataset.seed = item.seed
189 dataset.history = [*item.history, *dataset.history]
190 else:
191 dataset = datasets.Cases(data = loaded, seed = item.seed)
192 dataset.history = item.history
193 dataset.record(
194 self.name, source = str(source), rows = len(dataset.data),
195 columns = len(dataset.data.columns))
196 dataset = coders.code(dataset, names)
197 if saved is not None and isinstance(dataset, datasets.CourtData):
198 dataset.save(saved, clerk = self._get_clerk())
199 return type(dataset).create(
200 dataset, label = label, task = task, groups = groups)
202 """ Private Methods """
204 def _interim(self, path: Any) -> pathlib.Path:
205 """Returns where to save a table of cases.
207 Args:
208 path: the "save" parameter: a path to a ".csv" or ".parquet" file.
210 Returns:
211 `path` itself if it is absolute, and otherwise `path` in the
212 clerk's interim folder.
214 """
215 resolved = pathlib.Path(str(path)).expanduser()
216 if resolved.is_absolute(): 216 ↛ 217line 216 didn't jump to line 217 because the condition on line 216 was never true
217 return resolved
218 return pathlib.Path(self._get_clerk().interim_folder) / resolved
220 def _locate(self, path: Any) -> pathlib.Path:
221 """Returns a folder or file named in the settings, found with the clerk.
223 Args:
224 path: a path from the settings, which may begin with "~" for the
225 user's home folder.
227 Returns:
228 `path` itself if it is absolute or exists in the current folder,
229 and otherwise `path` in the clerk's input folder (where a
230 download saves its cases, even if the folder does not exist
231 yet).
233 """
234 resolved = pathlib.Path(str(path)).expanduser()
235 if resolved.is_absolute() or resolved.exists():
236 return resolved
237 return pathlib.Path(self._get_clerk().input_folder) / resolved
240@dataclasses.dataclass
241class LoadCases(CaseLoader):
242 """Loads a dataset of cases saved by `Cases.save`, or a table of one.
244 A joblib file holds the whole dataset, of the kind that it was (so a
245 saved `Votes` is `Votes` again), with its history. A table (such as a
246 CSV or parquet file) becomes `Cases`, labeled by "case_id", and columns
247 of booleans and whole numbers with missing values get types that allow
248 them (see `CourtData.load`). A saved dataset is usually coded already,
249 so no coders are applied unless "coders" names some.
251 """
253 default_coders: ClassVar[tuple[str, ...]] = ()
255 def load(self, source: Any, **kwargs: Any) -> amos.Dataset:
256 """Loads the dataset at `source`.
258 Args:
259 source: path of a joblib, CSV, or parquet file saved by
260 `CourtData.save`, found with the clerk.
261 **kwargs: not used.
263 Raises:
264 FileNotFoundError: if there is no file at `source`.
266 Returns:
267 The dataset.
269 """
270 loaded = datasets.CourtData.load(pathlib.Path(source))
271 if type(loaded) is datasets.CourtData:
272 return datasets.Cases.adopt(loaded)
273 return loaded
276@dataclasses.dataclass
277class SourceLoader(CaseLoader, abc.ABC):
278 """Base class for loaders that parse a folder of a source's saved cases.
280 The source is a folder of saved cases of the `courtpy.sources.Source`
281 named by `reads`. A subclass sets `reads` and `default_source`, and can
282 extend `load` to collect the cases first (as `DownloadCourtlistener`
283 downloads them and `LoadLexisNexis` divides files of many cases).
285 | Parameter | Meaning |
286 | --- | --- |
287 | `rulebooks` | Rules to parse with (such as "civil, criminal"), after the source's header rules and "general", which are always applied. Defaults to "federal". |
288 | `keep_text` | Whether to keep the text of the cases' sections (such as "party", "history", and "opinion") in the table, which `parse_all` can parse again. |
289 | `limit` | Most cases to parse, for trying out rules. |
290 | `workers` | Number of processes to parse with. |
292 Attributes:
293 reads: the name of the source of the saved cases, such as
294 "courtlistener".
296 """
298 reads: ClassVar[str] = ''
300 """ Required Methods """
302 def load(
303 self,
304 source: Any,
305 *,
306 rulebooks: Any = None,
307 keep_text: Any = False,
308 limit: Any = None,
309 workers: Any = None,
310 **kwargs: Any) -> pd.DataFrame:
311 """Parses the folder `source`.
313 Args:
314 source: the folder of saved cases, found with the clerk.
315 rulebooks: rules to parse with. Defaults to `None`, in which case
316 `options._DEFAULT_JURISDICTION` is used.
317 keep_text: whether to keep the text of the cases' sections.
318 Defaults to `False`.
319 limit: most cases to parse. Defaults to `None` (every case).
320 workers: number of processes to parse with. Defaults to `None`
321 (one).
322 **kwargs: not used.
324 Raises:
325 ValueError: if no cases are found.
327 Returns:
328 The table of parsed cases, labeled by "case_id".
330 """
331 return _parse(
332 pathlib.Path(source), self.reads, rulebooks = rulebooks,
333 keep_text = keep_text, limit = limit, workers = workers)
336@dataclasses.dataclass
337class LoadCourtlistener(SourceLoader):
338 """Parses and codes cases saved from CourtListener.
340 The source is a folder of cases saved by `courtpy.CourtListener` (by
341 default, "courtlistener" in the clerk's input folder), from its bulk
342 data or its API. To download them first, use `download_courtlistener`.
343 It takes the parameters of `SourceLoader`.
345 """
347 default_source: ClassVar[str | None] = 'courtlistener'
348 reads: ClassVar[str] = 'courtlistener'
351@dataclasses.dataclass
352class DownloadCourtlistener(LoadCourtlistener):
353 """Downloads cases from CourtListener, and parses and codes them.
355 The cases are downloaded into the source folder (by default,
356 "courtlistener" in the clerk's input folder) with
357 `courtpy.CourtListener.download`, and then the folder is parsed as
358 `load_courtlistener` parses it. With "bulk" (the default), they are
359 extracted from CourtListener's bulk data, which needs no API key. With
360 "api", they are downloaded with the API, with the key from
361 `courtpy.secrets`. Cases that were saved before are not downloaded again
362 unless "refresh" is true.
364 It takes the parameters of `SourceLoader`, and these:
366 | Parameter | Meaning |
367 | --- | --- |
368 | `method` | "bulk" (the default) or "api". |
369 | `courts` | CourtListener court ids (such as "ca1, ca2") or groups (such as "federal_appellate") to download. |
370 | `start_date`, `end_date` | Dates filed to download (YYYY-MM-DD). |
371 | `max_cases` | Most cases to download: in all with "bulk", and in each court with "api". |
372 | `refresh` | Whether to download cases that were already saved. |
373 | `dockets` | For "api", whether to download each case's docket too (the bulk data always has it). |
374 | `bulk_folder`, `bulk_date`, `stream` | For "bulk", where to keep the bulk files (found with the clerk), which date's files to use, and whether to read them without saving them. |
376 """
378 """ Required Methods """
380 def load(
381 self,
382 source: Any,
383 *,
384 method: Any = 'bulk',
385 courts: Any = None,
386 start_date: Any = None,
387 end_date: Any = None,
388 max_cases: Any = None,
389 refresh: Any = False,
390 dockets: Any = False,
391 bulk_folder: Any = None,
392 bulk_date: Any = None,
393 stream: Any = False,
394 **kwargs: Any) -> pd.DataFrame:
395 """Downloads the cases into the folder `source` and parses it.
397 Settings can be text (as a settings file gives them), so each is
398 converted to the type it needs.
400 Args:
401 source: the folder to save the cases in, found with the clerk.
402 method: "bulk" or "api". Defaults to "bulk".
403 courts: CourtListener court ids or groups to download. Defaults
404 to `None`, which raises an error.
405 start_date: earliest date filed to download (YYYY-MM-DD).
406 Defaults to `None`.
407 end_date: latest date filed to download (YYYY-MM-DD). Defaults
408 to `None`.
409 max_cases: most cases to download. Defaults to `None` (every
410 case).
411 refresh: whether to download cases that were already saved.
412 Defaults to `False`.
413 dockets: with "api", whether to download each case's docket too.
414 Defaults to `False`.
415 bulk_folder: with "bulk", the folder to keep the bulk files in,
416 found with the clerk. Defaults to `None`, in which case
417 "bulk" in `utilities.data_folder()` is used.
418 bulk_date: with "bulk", the date of the files to use. Defaults to
419 `None` (the newest).
420 stream: with "bulk", whether to read the files without saving
421 them. Defaults to `False`.
422 **kwargs: the parameters of `SourceLoader.load`.
424 Raises:
425 ValueError: if "method" is not "bulk" or "api", if no courts are
426 named, or if no cases are found.
428 Returns:
429 The table of parsed cases, labeled by "case_id".
431 """
432 folder = pathlib.Path(source)
433 client = courtlistener.CourtListener(
434 bulk_folder = self._locate(bulk_folder) if bulk_folder else None,
435 bulk_date = utilities.to_date(bulk_date),
436 stream = utilities.to_bool(stream))
437 client.download(
438 courts or [],
439 utilities.to_date(start_date),
440 utilities.to_date(end_date),
441 folder,
442 method = str(method),
443 max_cases = utilities.to_integer(max_cases),
444 dockets = utilities.to_bool(dockets),
445 refresh = utilities.to_bool(refresh))
446 return super().load(folder, **kwargs)
449@dataclasses.dataclass
450class LoadLexisNexis(SourceLoader):
451 """Divides, parses, and codes cases downloaded from Lexis-Nexis.
453 The source is a folder of Lexis-Nexis cases, one per text file (by
454 default, "lexis_nexis" in the clerk's input folder). If "batches" names
455 files (or folders) of many cases, as Lexis-Nexis downloads them, they are
456 divided into the source folder first (see `courtpy.lexis.split`).
458 It takes the parameters of `SourceLoader`, and:
460 | Parameter | Meaning |
461 | --- | --- |
462 | `batches` | Lexis-Nexis downloads of many cases to divide first. |
464 """
466 default_source: ClassVar[str | None] = 'lexis_nexis'
467 reads: ClassVar[str] = 'lexis_nexis'
469 """ Required Methods """
471 def load(
472 self,
473 source: Any,
474 *,
475 batches: Any = None,
476 **kwargs: Any) -> pd.DataFrame:
477 """Divides any batches into the folder `source` and parses it.
479 Args:
480 source: the folder of Lexis-Nexis cases, found with the clerk.
481 batches: files or folders of downloads of many cases, found with
482 the clerk. The ".txt" files in a folder are used. Defaults to
483 `None` (none).
484 **kwargs: the parameters of `SourceLoader.load`.
486 Returns:
487 The table of parsed cases, labeled by "case_id".
489 """
490 folder = pathlib.Path(source)
491 if batches: 491 ↛ 498line 491 didn't jump to line 498 because the condition on line 491 was always true
492 files = []
493 for batch in utilities.listify(batches):
494 found = self._locate(batch)
495 files.extend(
496 sorted(found.glob('*.txt')) if found.is_dir() else [found])
497 lexis.split(files, folder)
498 return super().load(folder, **kwargs)
501@dataclasses.dataclass
502class ReferenceLoader(amos.Loader, abc.ABC):
503 """Base class for techniques that load a table of reference data.
505 Reference data describes something other than parsed cases: the judges,
506 the Supreme Court Database, the Integrated Database, or the political
507 context of each year. Unlike a `CaseLoader`, a reference loader needs no
508 "source". Without one, it loads the files that courtpy keeps outside of
509 projects (in `courtpy.utilities.data_folder()`), which are downloaded
510 first if they are missing, and the dataset's history records the source
511 as "current". A relative "source" is looked for in the current folder and
512 then in the clerk's input folder.
514 Like every loader, it starts a new dataset, so it usually begins a study
515 whose rows are what the table describes (such as each justice's vote in
516 each case). To add a table's columns to parsed cases, use a merger (such
517 as `add_scdb`) instead.
519 Attributes:
520 default_source: the source that is recorded when "source" is not
521 set.
523 """
525 default_source: ClassVar[str] = 'current'
527 """ Public Methods """
529 def apply(self, item: amos.Dataset, **kwargs: Any) -> amos.Dataset:
530 """Loads the table into a dataset that continues `item`.
532 Args:
533 item: the dataset so far, whose seed and history are kept.
534 **kwargs: "source", "label", "task", and "groups", and parameters
535 for `load`.
537 Returns:
538 The dataset of the loaded table.
540 """
541 kwargs['source'] = kwargs.get('source') or self.default_source
542 return super().apply(item, **kwargs)
544 """ Private Methods """
546 def _choose(self, value: Any) -> bool | pathlib.Path | None:
547 """Returns a setting that names a file or says whether to use one.
549 Args:
550 value: `None`, a `bool`, text that `utilities.to_bool` reads
551 (such as "false"), or the path of a file.
553 Returns:
554 `None`, the boolean, or the path, found with the clerk (see
555 `utilities.locate`).
557 """
558 if value is None or isinstance(value, bool):
559 return value
560 try:
561 return utilities.to_bool(value)
562 except ValueError:
563 return utilities.locate(value, self._get_clerk())
565 def _locate(self, source: Any) -> pathlib.Path | None:
566 """Returns the folder or file that a source names.
568 Args:
569 source: the "source" parameter.
571 Returns:
572 `None` if `source` is missing or `default_source` (so the current
573 files are used), and otherwise the path, found with the
574 clerk (see `utilities.locate`).
576 """
577 if source is None or str(source) == self.default_source:
578 return None
579 return utilities.locate(source, self._get_clerk())
582""" Private Functions """
585def _parse(
586 folder: pathlib.Path,
587 source: str,
588 *,
589 rulebooks: Any,
590 keep_text: Any,
591 limit: Any,
592 workers: Any) -> pd.DataFrame:
593 """Parses a folder of saved cases with settings that may be text.
595 Args:
596 folder: the folder of saved cases.
597 source: the name of their source, such as "courtlistener".
598 rulebooks: rules to parse with, or `None` (or blank) for
599 `options._DEFAULT_JURISDICTION`.
600 keep_text: whether to keep the text of the cases' sections.
601 limit: most cases to parse, or `None` for every case.
602 workers: number of processes to parse with, or `None` for one.
604 Raises:
605 ValueError: if no cases are found in `folder`.
607 Returns:
608 The table of parsed cases, labeled by "case_id".
610 """
611 data = parsers.parse(
612 folder,
613 source = source,
614 rulebooks = rulebooks or options._DEFAULT_JURISDICTION,
615 keep_text = utilities.to_bool(keep_text),
616 limit = utilities.to_integer(limit),
617 workers = utilities.to_integer(workers) or 1)
618 if data.empty:
619 message = f'no {source} cases were found in {folder}'
620 raise ValueError(message)
621 return data
624def _reusable(saved: pathlib.Path) -> pathlib.Path | None:
625 """Returns the file of a saved dataset that a loader can reuse.
627 Args:
628 saved: the path of the saved table (the loader's "save").
630 Returns:
631 The joblib file beside it (which holds the whole dataset), if there is
632 one, or else the table, if it exists, or else `None`.
634 """
635 whole = saved.with_suffix('.joblib')
636 if whole.is_file():
637 return whole
638 return saved if saved.is_file() else None