Coverage for src/courtpy/sources/lexis.py: 97%

79 statements  

« prev     ^ index     » next       coverage.py v7.16.2, created at 2026-11-22 15:51 +0000

1"""Reads court opinions downloaded from Lexis-Nexis as text files. 

2 

3Lexis-Nexis lets users download many cases at once in one text file, with a 

4line such as "3 of 250 DOCUMENTS" before each case. `split` divides such 

5files into one file for each case, which `read_case` reads for parsing. 

6 

7Lexis-Nexis cases have a header (with the parties, court, docket number, 

8dates, history, counsel, judges, and so on) followed by the opinions. The 

9rules in the "lexis_nexis" rulebook (in "instructions/sources/lexis_nexis", 

10with a file for each kind of court) find each part of the header, and the 

11"lexis_nexis_header" rulebook (with that folder's "header.csv") finds the 

12court, parties, and judges in the parts, so they can be changed without 

13changing courtpy. 

14 

15Contents: 

16 LexisNexisSource: reads Lexis-Nexis cases saved one to a text file. 

17 clean: removes common clutter from Lexis-Nexis text. 

18 finish: adds dates and publication status to a parsed case. 

19 read_case: reads a Lexis-Nexis case for parsing. 

20 split: divides files of many cases into one file for each case. 

21 logger: the module's logger, which reports how many cases each file held. 

22 

23""" 

24 

25from __future__ import annotations 

26 

27import dataclasses 

28import logging 

29import pathlib 

30import re 

31from collections.abc import Iterable, MutableMapping 

32from typing import Any, ClassVar 

33 

34from ..core import cases, utilities 

35from . import base 

36 

37logger = logging.getLogger(__name__) 

38_DIVIDER: re.Pattern[str] = re.compile(r'\d+ of \d+ DOCUMENTS', re.IGNORECASE) 

39_DATE_KINDS: tuple[str, ...] = ( 

40 'DECIDED', 'FILED', 'ARGUED', 'SUBMITTED', 'AMENDED') 

41 

42 

43@dataclasses.dataclass 

44class LexisNexisSource(base.Source): 

45 """Reads Lexis-Nexis cases saved one to a text file (see `split`). 

46 

47 The "lexis_nexis" rules find the sections of each case's header, the 

48 "lexis_nexis_header" rules find the court (by the names in the 

49 jurisdiction's table of courts), parties, and judges in them, and 

50 `finish` adds its dates and publication status. 

51 

52 """ 

53 

54 name: ClassVar[str] = 'lexis_nexis' 

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

56 structure: ClassVar[str | None] = 'lexis_nexis' 

57 header: ClassVar[str] = 'lexis_nexis_header' 

58 

59 """ Required Methods """ 

60 

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

62 """Reads a Lexis-Nexis case for parsing (see `read_case`). 

63 

64 Args: 

65 path: path of a text file with one case. 

66 

67 Returns: 

68 The case. 

69 

70 """ 

71 return read_case(path) 

72 

73 """ Public Methods """ 

74 

75 def finish(self, row: MutableMapping[str, Any]) -> None: 

76 """Adds dates and publication status to a parsed case (see `finish`). 

77 

78 Args: 

79 row: the parsed case, which is changed in place. 

80 

81 """ 

82 finish(row) 

83 

84 

85""" Public Functions """ 

86 

87 

88def clean(text: str) -> str: 

89 """Removes common clutter from Lexis-Nexis text. 

90 

91 Star paging ("*123"), bracketed footnote numbers ("[12]"), and the 

92 "Signal:" and "As of:" lines that Lexis adds are removed, spaces are 

93 collapsed, and spaces at the starts and ends of lines are trimmed. 

94 

95 Args: 

96 text: text of one or more cases. 

97 

98 Returns: 

99 The cleaned text. 

100 

101 """ 

102 text = text.replace('\r\n', '\n').replace('\r', '\n') 

103 text = text.replace('*', '') 

104 text = re.sub(r'\[\d*\]', '', text) 

105 text = re.sub(r'[^\S\n]+', ' ', text) 

106 text = re.sub(r'(?im)^ ?(?:signal|as of):.*\n?\n?', '', text) 

107 return re.sub(r' *\n *', '\n', text) 

108 

109 

110def finish(row: MutableMapping[str, Any]) -> MutableMapping[str, Any]: 

111 """Adds dates and publication status to a parsed Lexis-Nexis case. 

112 

113 The "dates" section has each line of the header with a date (such as 

114 "March 3, 2009, Argued"), with "; " between them. Each kind of date 

115 (decided, filed, argued, submitted, and amended) is stored as an ISO date 

116 in its own column ("date_decided" and so on). "date_filed" is the date 

117 filed or, if there is none, the date decided, as on CourtListener. "year" 

118 is the year of that date (or of the first date found). 

119 

120 A case is published if it has a Federal Reporter citation and no notice 

121 that it is unpublished (as found by the federal rules). 

122 

123 Args: 

124 row: a parsed case. 

125 

126 Returns: 

127 The same `row`, with the new columns. 

128 

129 """ 

130 lines = str(row.get('dates') or '').split(cases._SEPARATOR) 

131 for kind in _DATE_KINDS: 

132 column = f'date_{kind.lower()}' 

133 row.setdefault(column, None) 

134 for line in lines: 

135 if kind in line.upper(): 

136 row[column] = utilities.parse_date(line) 

137 break 

138 if not row.get('date_filed'): 

139 row['date_filed'] = row.get('date_decided') 

140 first = row.get('date_filed') or next( 

141 (d for d in map(utilities.parse_date, lines) if d), None) 

142 row['year'] = int(first[:4]) if first else None 

143 if 'cite_federal_reporter' in row: 143 ↛ 146line 143 didn't jump to line 146 because the condition on line 143 was always true

144 row['published'] = bool(row['cite_federal_reporter']) and not bool( 

145 row.get('notice_unpublished')) 

146 return row 

147 

148 

149def read_case(path: pathlib.Path | str) -> cases.Case: 

150 """Reads a Lexis-Nexis case for parsing. 

151 

152 Args: 

153 path: path of a text file with one case. 

154 

155 Returns: 

156 The case. Its only section is "text" (the whole case, cleaned), which 

157 the "lexis_nexis" rules divide into the header and opinions. 

158 

159 """ 

160 path = pathlib.Path(path) 

161 text = clean(_read_text(path)).strip() 

162 # Line breaks at each end let rules look for a line at the start or end. 

163 return cases.Case( 

164 id = path.stem, 

165 source = 'lexis_nexis', 

166 sections = {'text': f'\n{text}\n'}, 

167 metadata = {'source': 'lexis_nexis', 'file': path.name}, 

168 path = path) 

169 

170 

171def split( 

172 files: Iterable[pathlib.Path | str] | pathlib.Path | str, 

173 folder: pathlib.Path | str = 'lexis_nexis') -> list[pathlib.Path]: 

174 """Divides files of many cases into one file for each case. 

175 

176 Args: 

177 files: text files downloaded from Lexis-Nexis, or a folder of them. 

178 folder: folder to save the cases in. Each is named for the file it came 

179 from and its place in that file (such as "batch1_00003.txt"). 

180 Defaults to "lexis_nexis". 

181 

182 Returns: 

183 The paths of the new files. 

184 

185 """ 

186 if isinstance(files, str | pathlib.Path): 

187 source = pathlib.Path(files) 

188 files = sorted(source.glob('*.txt')) if source.is_dir() else [source] 

189 folder = pathlib.Path(folder) 

190 folder.mkdir(parents = True, exist_ok = True) 

191 saved = [] 

192 for file in files: 

193 file = pathlib.Path(file) # noqa: PLW2901 

194 pieces = [clean(p).strip() for p in _DIVIDER.split(_read_text(file))] 

195 number = 0 

196 for piece in pieces: 

197 if not piece: 

198 continue 

199 number += 1 

200 path = folder / f'{file.stem}_{number:05d}.txt' 

201 path.write_text(piece + '\n', encoding = 'utf-8') 

202 saved.append(path) 

203 logger.info('%s: %d cases', file.name, number) 

204 return saved 

205 

206 

207""" Private Functions """ 

208 

209 

210def _read_text(path: pathlib.Path) -> str: 

211 """Returns the text of a file in UTF-8 or, failing that, Windows-1252. 

212 

213 Lexis-Nexis has saved downloads in both encodings. Text that is not valid 

214 UTF-8 is read as Windows-1252, with any byte that is not valid there 

215 either replaced by a placeholder character. 

216 

217 Args: 

218 path: path of a text file. 

219 

220 Returns: 

221 The text, without a UTF-8 byte order mark if the file had one. 

222 

223 """ 

224 data = path.read_bytes() 

225 try: 

226 return data.decode('utf-8-sig') 

227 except UnicodeDecodeError: 

228 return data.decode('cp1252', errors = 'replace')