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

1"""The base class for sources of court opinions. 

2 

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"). 

6 

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: 

10 

11```python 

12import dataclasses 

13from typing import ClassVar 

14 

15import courtpy 

16 

17 

18@dataclasses.dataclass 

19class StateCourtSource(courtpy.Source): 

20 

21 name: ClassVar[str] = 'state_court' 

22 pattern: ClassVar[str] = '*.txt' 

23 

24 def read(self, path): 

25 ... 

26``` 

27 

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. 

32 

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. 

37 

38""" 

39 

40from __future__ import annotations 

41 

42import abc 

43import dataclasses 

44import pathlib 

45import re 

46from collections.abc import MutableMapping 

47from typing import Any, ClassVar 

48 

49from ..core import cases 

50 

51SOURCES: dict[str, type[Source]] = {} 

52_CAPITAL: re.Pattern[str] = re.compile(r'(?<=[a-z0-9])(?=[A-Z])') 

53 

54 

55@dataclasses.dataclass 

56class Source(abc.ABC): 

57 """Base class for a source of saved cases. 

58 

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`. 

62 

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. 

74 

75 """ 

76 

77 name: ClassVar[str] = '' 

78 pattern: ClassVar[str] = '*' 

79 structure: ClassVar[str | None] = None 

80 header: ClassVar[str] = 'header' 

81 

82 """ Initialization Methods """ 

83 

84 def __init_subclass__(cls, **kwargs: Any) -> None: 

85 """Adds the subclass to `SOURCES`, unless it is a base class. 

86 

87 Args: 

88 **kwargs: passed to the `__init_subclass__` of the parent class. 

89 

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 

96 

97 """ Required Methods """ 

98 

99 @abc.abstractmethod 

100 def read(self, path: pathlib.Path) -> cases.Case: 

101 """Reads one saved case for parsing. 

102 

103 Args: 

104 path: the path of the saved case. 

105 

106 Returns: 

107 The case, with `source` set to the source's `name`. 

108 

109 """ 

110 

111 """ Public Methods """ 

112 

113 def find_files(self, folder: pathlib.Path | str) -> list[pathlib.Path]: 

114 """Returns the saved cases in a folder and its subfolders. 

115 

116 Args: 

117 folder: the folder. 

118 

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. 

123 

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)) 

130 

131 def finish(self, row: MutableMapping[str, Any]) -> None: # noqa: B027 

132 """Adds columns to a parsed case after the rules are applied. 

133 

134 The base class adds nothing; a subclass can override it. 

135 

136 Args: 

137 row: the parsed case, as a `dict` from column to value, which is 

138 changed in place. 

139 

140 """ 

141 

142 

143""" Public Functions """ 

144 

145 

146def find_source(name: str) -> Source: 

147 """Returns a source of saved cases, by name. 

148 

149 Args: 

150 name: the name of a `Source`, such as "courtlistener". 

151 

152 Raises: 

153 ValueError: if no source has that name. 

154 

155 Returns: 

156 An instance of the `Source` subclass. 

157 

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]() 

163 

164 

165""" Private Functions """ 

166 

167 

168def _name_of(cls: type[Source]) -> str: 

169 """Returns the name of a source. 

170 

171 Args: 

172 cls: the subclass. 

173 

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`). 

177 

178 """ 

179 named = cls.__dict__.get('name') 

180 if named: 

181 return str(named) 

182 return _CAPITAL.sub('_', cls.__name__).lower()