Coverage for src/courtpy/sources/base.py: 100%
43 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"""The base class for sources of court opinions.
3A `Source` is a kind of saved case that courtpy can read and parse, such as
4the JSON files that CourtListener's bulk data and API are saved as
5("courtlistener") or the text files of Lexis-Nexis ("lexis_nexis").
7A source adds itself to courtpy when it is subclassed, as `amos` techniques
8add themselves to the `amos` library, so a study can add its own by defining
9a subclass in a module that it imports:
11```python
12import dataclasses
13from typing import ClassVar
15import courtpy
18@dataclasses.dataclass
19class StateCourtSource(courtpy.Source):
21 name: ClassVar[str] = 'state_court'
22 pattern: ClassVar[str] = '*.txt'
24 def read(self, path):
25 ...
26```
28Then "state_court" can be the source of `courtpy.parse` and of a loader
29that subclasses `courtpy.SourceLoader`. A subclass with the name of one that
30is already known replaces it. A subclass that lists `abc.ABC` among its bases
31is a base class for others, and is not added.
33Contents:
34 SOURCES: the sources of saved cases that courtpy can read, by name.
35 Source: base class for a source of saved cases.
36 find_source: returns a source of saved cases, by name.
38"""
40from __future__ import annotations
42import abc
43import dataclasses
44import pathlib
45import re
46from collections.abc import MutableMapping
47from typing import Any, ClassVar
49from ..core import cases
51SOURCES: dict[str, type[Source]] = {}
52_CAPITAL: re.Pattern[str] = re.compile(r'(?<=[a-z0-9])(?=[A-Z])')
55@dataclasses.dataclass
56class Source(abc.ABC):
57 """Base class for a source of saved cases.
59 A subclass writes `read`, which reads one saved case into a `cases.Case`,
60 and sets `pattern`, which finds its saved cases in a folder. It is added
61 to `SOURCES` when it is defined, under its `name`.
63 Attributes:
64 name: the name of the source, such as "courtlistener". Defaults to
65 the snake case name of the class.
66 pattern: the file pattern of its saved cases, such as "*.json".
67 structure: the rulebook that finds the sections of its cases, if
68 they need finding (such as "lexis_nexis"), or `None`.
69 header: the rulebook that finds the court, the parties and their
70 roles, and the judges in its cases' sections, which the parser
71 applies before any other (see `courtpy.rules.make_header_rules`).
72 Defaults to "header", which has only the rules that fit every
73 source.
75 """
77 name: ClassVar[str] = ''
78 pattern: ClassVar[str] = '*'
79 structure: ClassVar[str | None] = None
80 header: ClassVar[str] = 'header'
82 """ Initialization Methods """
84 def __init_subclass__(cls, **kwargs: Any) -> None:
85 """Adds the subclass to `SOURCES`, unless it is a base class.
87 Args:
88 **kwargs: passed to the `__init_subclass__` of the parent class.
90 """
91 super().__init_subclass__(**kwargs)
92 if abc.ABC in cls.__bases__:
93 return
94 cls.name = _name_of(cls)
95 SOURCES[cls.name] = cls
97 """ Required Methods """
99 @abc.abstractmethod
100 def read(self, path: pathlib.Path) -> cases.Case:
101 """Reads one saved case for parsing.
103 Args:
104 path: the path of the saved case.
106 Returns:
107 The case, with `source` set to the source's `name`.
109 """
111 """ Public Methods """
113 def find_files(self, folder: pathlib.Path | str) -> list[pathlib.Path]:
114 """Returns the saved cases in a folder and its subfolders.
116 Args:
117 folder: the folder.
119 Returns:
120 The paths of the files that match `pattern`, sorted. Files in
121 hidden folders (such as ".courtpy", where downloads keep
122 their place) are left out.
124 """
125 folder = pathlib.Path(folder)
126 return sorted(
127 p for p in folder.rglob(self.pattern)
128 if p.is_file() and not any(
129 part.startswith('.') for part in p.relative_to(folder).parts))
131 def finish(self, row: MutableMapping[str, Any]) -> None: # noqa: B027
132 """Adds columns to a parsed case after the rules are applied.
134 The base class adds nothing; a subclass can override it.
136 Args:
137 row: the parsed case, as a `dict` from column to value, which is
138 changed in place.
140 """
143""" Public Functions """
146def find_source(name: str) -> Source:
147 """Returns a source of saved cases, by name.
149 Args:
150 name: the name of a `Source`, such as "courtlistener".
152 Raises:
153 ValueError: if no source has that name.
155 Returns:
156 An instance of the `Source` subclass.
158 """
159 if name not in SOURCES:
160 message = f'source must be one of {sorted(SOURCES)}, not {name!r}'
161 raise ValueError(message)
162 return SOURCES[name]()
165""" Private Functions """
168def _name_of(cls: type[Source]) -> str:
169 """Returns the name of a source.
171 Args:
172 cls: the subclass.
174 Returns:
175 The `name` set in the class's own body, or else the snake case name
176 of the class (such as "state_court" for `StateCourt`).
178 """
179 named = cls.__dict__.get('name')
180 if named:
181 return str(named)
182 return _CAPITAL.sub('_', cls.__name__).lower()