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
« 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.
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.
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.
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.
23"""
25from __future__ import annotations
27import dataclasses
28import logging
29import pathlib
30import re
31from collections.abc import Iterable, MutableMapping
32from typing import Any, ClassVar
34from ..core import cases, utilities
35from . import base
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')
43@dataclasses.dataclass
44class LexisNexisSource(base.Source):
45 """Reads Lexis-Nexis cases saved one to a text file (see `split`).
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.
52 """
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'
59 """ Required Methods """
61 def read(self, path: pathlib.Path) -> cases.Case:
62 """Reads a Lexis-Nexis case for parsing (see `read_case`).
64 Args:
65 path: path of a text file with one case.
67 Returns:
68 The case.
70 """
71 return read_case(path)
73 """ Public Methods """
75 def finish(self, row: MutableMapping[str, Any]) -> None:
76 """Adds dates and publication status to a parsed case (see `finish`).
78 Args:
79 row: the parsed case, which is changed in place.
81 """
82 finish(row)
85""" Public Functions """
88def clean(text: str) -> str:
89 """Removes common clutter from Lexis-Nexis text.
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.
95 Args:
96 text: text of one or more cases.
98 Returns:
99 The cleaned text.
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)
110def finish(row: MutableMapping[str, Any]) -> MutableMapping[str, Any]:
111 """Adds dates and publication status to a parsed Lexis-Nexis case.
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).
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).
123 Args:
124 row: a parsed case.
126 Returns:
127 The same `row`, with the new columns.
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
149def read_case(path: pathlib.Path | str) -> cases.Case:
150 """Reads a Lexis-Nexis case for parsing.
152 Args:
153 path: path of a text file with one case.
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.
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)
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.
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".
182 Returns:
183 The paths of the new files.
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
207""" Private Functions """
210def _read_text(path: pathlib.Path) -> str:
211 """Returns the text of a file in UTF-8 or, failing that, Windows-1252.
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.
217 Args:
218 path: path of a text file.
220 Returns:
221 The text, without a UTF-8 byte order mark if the file had one.
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')