Coverage for src/courtpy/wrangler/rules.py: 98%
121 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"""courtpy's rulebooks, which find information in the text of court opinions.
3The rules are rows of CSV files (spreadsheets) in courtpy's "instructions"
4folder, so they can be read and changed without knowing Python. They are
5`amos` rulebooks: each row is a rule of `amos.parsers.ParseAll`, which
6documents the columns and kinds of rules (and also reads files in the older
7layout, with "target", "variable", "label", and "section").
9The rules of each topic (such as "criminal") are in two places. The file in
10the "general" folder has the rules that fit opinions of any jurisdiction, and
11the file of the same name in a jurisdiction's folder (such as "federal") has
12the rules that fit only that jurisdiction, if there are any. A rulebook for a
13topic applies the general rules and then the jurisdiction's (see
14`find_rule_files`). courtpy reads only federal cases so far, so every
15rulebook here is federal.
17Each source's rules are in its folder of "sources" (such as
18"sources/lexis_nexis"): the rules that find the sections of its cases, with
19a file for each kind of court (such as "federal_appellate.csv"; see
20`find_structure_file`), and the rules of its header ("header.csv"). The
21header rulebook of a source (see `make_header_rules`) applies
22"general/header.csv" (the rules that fit every source), rules made from the
23jurisdiction's "agencies.csv" that find the agencies named in each party and
24the history (see `make_agency_rules`), the source's "header.csv", and, for a
25source whose cases name their court in text, rules made from the
26jurisdiction's "courts.csv" that find "court_num" and "court_name" (see
27`make_court_rules`). Rules made from "courts.csv" also find the court whose
28decision is reviewed in every source's history ("lower_court_num" and
29"lower_court_name").
30So the header rules name no courts or agencies of their own, and a court or
31agency added to the tables is found without changing them.
33`register_rulebooks` makes a rulebook of each topic, a subclass of
34`amos.parsers.ParseAll` that is added to the `amos` library, so it has a name
35that `courtpy.parse`, the "rulebooks" of a case loader, other rulebooks, and
36the "rules" of `parse_all` can use (such as "federal" or "civil"). Each is
37also a technique of its own (such as `parse_civil`), which searches the
38columns of text of a dataset (such as "opinion", which a case loader keeps
39with "keep_text"). A study can make rulebooks of its own folders of rules the
40same way. courtpy's own are in `RULEBOOKS`: "general",
41"citations", "civil", "constitutional", "criminal", "review", "agencies",
42"federal" (all of those, in that order), the header rulebooks "header" (for
43a source with no rules of its own), "courtlistener_header", and
44"lexis_nexis_header", and "lexis_nexis", which finds the sections of a
45Lexis-Nexis case. The parser applies a source's header rulebook (named by
46its `header`) before the others.
48Rules that make several values in one cell (`names`, `matches`, and
49`categories` rules, such as "panel_judges", "citations_case", and
50"agencies") separate them with "; ", so that a table of cases can be saved
51as a CSV file. The `split_values` technique (`coders.SplitValues`) turns
52such text into lists or columns.
54Contents:
55 RULEBOOKS: courtpy's rulebooks, by their names.
56 case_type_prefixes: returns the prefixes of the names of the rules of
57 the topics of cases, each of which is a case type.
58 find_rule_files: returns the files of rules of a topic in a jurisdiction.
59 find_structure_file: returns the file of rules that finds the sections
60 of a source's cases.
61 make_agency_rules: returns rules that find the agencies named in
62 sections of the header.
63 make_court_rules: returns rules that find a case's court from its
64 name.
65 make_header_rules: returns the rules of a source's header.
66 register_rulebooks: makes a rulebook of each topic in folders of rule
67 files.
68 _AGENCY_COLUMNS: the sections of the header whose agencies are found.
69 _PARTY_AGENCY_END: what must follow an agency's name in a party.
70 _PARTY_COLUMNS: the sections of the header that are parties.
71 _CASE_TYPE_TOPICS: the topics whose rules' prefixes are case types.
72 _COURT_NAME_COLUMNS: the columns of a table of courts with patterns of
73 their names, in the order they are tried.
74 _GENERAL: the folder of the rules that fit every jurisdiction.
75 _HEADER: the stem of the files of header rules.
76 _LOWER_COURT_LEVELS: the levels of courts, in the order they are tried,
77 that the history is searched for to find the court whose decision is
78 reviewed.
79 _INSTRUCTIONS: courtpy's "instructions" folder.
80 _JURISDICTION: the jurisdiction of the cases that courtpy reads.
81 _SOURCES: the folder of the rules of each source.
82 _TOPICS: the topics of courtpy's rules, in the order of the "federal"
83 rulebook.
85"""
87from __future__ import annotations
89import dataclasses
90import pathlib
91from collections.abc import Sequence
92from typing import Any
94import amos
95import pandas as pd
97from ..core import utilities
98from ..references import courts
100_INSTRUCTIONS = utilities.instructions_folder()
101_GENERAL = _INSTRUCTIONS / 'general'
102_SOURCES = _INSTRUCTIONS / 'sources'
103_HEADER = 'header'
104# The sections of the header whose agencies are found, each into a column of
105# its own ("party1_agencies" and so on), so a study can tell an agency that
106# is a party from one whose decision is reviewed.
107_AGENCY_COLUMNS: tuple[str, ...] = ('party1', 'party2', 'history')
108# An agency that is a party is named as a party of its own, so its name ends
109# the party or comes before a comma ("..., Respondent"), a semicolon (between
110# parties), a closing parenthesis, or "et al." A name followed by other words
111# is part of another party's name (such as "FMC WYOMING CORPORATION").
112_PARTY_AGENCY_END: str = r'(?=\s*(?:[,;)]|\.?\s*$|(?i:et\s+al)\b))'
113# The sections of the header that are parties, whose agencies must end a party
114# (see `_PARTY_AGENCY_END`).
115_PARTY_COLUMNS: tuple[str, ...] = ('party1', 'party2')
116# A court is found by how opinions name it before the Federal Judicial
117# Center's names for it, which opinions rarely use.
118_COURT_NAME_COLUMNS: tuple[str, ...] = ('opinion_name', 'fjc_name')
119# The courts whose decisions the courts of appeals review. The history of an
120# appeal also cites earlier appeals and remands from the Supreme Court, which
121# are not the court below, so courts of appeals and the Supreme Court are left
122# out. (A CourtListener case of the Supreme Court has the court below from its
123# docket.)
124_LOWER_COURT_LEVELS: tuple[str, ...] = ('trial', 'specialty')
125# The folder of the rules of each jurisdiction is named for it. courtpy reads
126# only federal cases so far.
127_JURISDICTION = 'federal'
128# The topics whose rules find the subject of a case. The prefix of each rule's
129# name (such as "tort" in "tort_negligence") is a case type.
130_CASE_TYPE_TOPICS: tuple[str, ...] = ('criminal', 'civil', 'constitutional')
131# The topics of the built-in rules, in the order of the "federal" rulebook.
132# The header rules are not among them, since they depend on the source (see
133# `make_header_rules`).
134_TOPICS: tuple[str, ...] = (
135 'general', 'citations', 'civil', 'constitutional', 'criminal', 'review',
136 'agencies')
139""" Public Functions """
142def case_type_prefixes(
143 jurisdiction: str | None = _JURISDICTION) -> list[str]:
144 """Returns the prefixes of the rules of the topics of cases.
146 Each rule of the "criminal", "civil", and "constitutional" files names a
147 column with a prefix (such as "criminal" in "criminal_firearm", or "tort"
148 in "tort_negligence"), and each prefix is a case type (see
149 `code_case_type`). A prefix added to a file (such as "immigration_") is
150 a case type too.
152 Args:
153 jurisdiction: the folder of the jurisdiction's rules, such as
154 "federal". Defaults to `_JURISDICTION`. If it is `None`, only
155 the general rules are read.
157 Returns:
158 The prefixes, in the order in which they first appear in the files.
160 """
161 prefixes: dict[str, None] = {}
162 for topic in _CASE_TYPE_TOPICS:
163 for path in find_rule_files(topic, jurisdiction):
164 names = utilities.read_csv(path, usecols = ['name'])['name']
165 for name in names.dropna().astype(str):
166 prefix, separator, _ = name.strip().partition('_')
167 if separator and prefix: 167 ↛ 165line 167 didn't jump to line 165 because the condition on line 167 was always true
168 prefixes.setdefault(prefix)
169 return list(prefixes)
172def find_rule_files(
173 topic: str,
174 jurisdiction: str | None = _JURISDICTION) -> list[pathlib.Path]:
175 """Returns the files of rules of a topic in a jurisdiction.
177 Args:
178 topic: the stem of the files, such as "criminal".
179 jurisdiction: the folder of the jurisdiction's rules, such as
180 "federal". Defaults to `_JURISDICTION`. If it is `None`, only
181 the general rules are returned.
183 Raises:
184 FileNotFoundError: if neither the "general" folder nor the
185 jurisdiction's folder has a file for the topic.
187 Returns:
188 The file in the "general" folder and then the file in the
189 jurisdiction's folder, leaving out either one that does not
190 exist (as "federal/citations.csv" does not, since every rule of
191 citations fits every jurisdiction).
193 """
194 folders = [_GENERAL]
195 if jurisdiction is not None:
196 folders.append(_INSTRUCTIONS / jurisdiction)
197 files = [
198 folder / f'{topic}.csv' for folder in folders
199 if (folder / f'{topic}.csv').is_file()]
200 if not files:
201 searched = ', '.join(str(folder) for folder in folders)
202 message = f'there is no file of rules for {topic!r} in {searched}'
203 raise FileNotFoundError(message)
204 return files
207def find_structure_file(source: str, courts: str) -> pathlib.Path:
208 """Returns the file of rules that finds the sections of a source's cases.
210 Args:
211 source: the name of the source, which is also the name of its folder
212 of rules in `_SOURCES`, such as "lexis_nexis".
213 courts: the kind of courts whose cases the rules fit, which is the
214 stem of the file, such as "federal_appellate".
216 Raises:
217 FileNotFoundError: if there is no such file.
219 Returns:
220 The path of the file.
222 """
223 path = _SOURCES / source / f'{courts}.csv'
224 if not path.is_file():
225 message = f'there are no rules for {courts!r} cases of {source!r}'
226 raise FileNotFoundError(message)
227 return path
230def make_agency_rules(
231 jurisdiction: str | None = _JURISDICTION,
232 columns: Sequence[str] = _AGENCY_COLUMNS,
233 party_columns: Sequence[str] = _PARTY_COLUMNS) -> list[dict[str, Any]]:
234 """Returns rules that find the agencies named in sections of the header.
236 Each rule of the jurisdiction's "agencies" files (see `find_rule_files`)
237 is made into a rule for each of `columns`, which searches only that
238 column and makes "{column}_agencies" (such as "party1_agencies"), so
239 that the header names no agencies of its own. In a column of
240 `party_columns`, an agency's name must end a party (see
241 `_PARTY_AGENCY_END`), so that a company or person named for an agency is
242 not taken for it.
244 Args:
245 jurisdiction: the folder of the jurisdiction's rules, such as
246 "federal". Defaults to `_JURISDICTION`. If it is `None`, only
247 the general rules are read.
248 columns: the sections to search. Defaults to `_AGENCY_COLUMNS`
249 ("party1", "party2", and "history").
250 party_columns: the sections of `columns` that are parties. Defaults
251 to `_PARTY_COLUMNS` ("party1" and "party2").
253 Returns:
254 The rules, as `dict`s with the columns of a file of rules, ordered by
255 column and then by the order of the files. They are empty if
256 there are no "agencies" files.
258 """
259 try:
260 paths = find_rule_files('agencies', jurisdiction)
261 except FileNotFoundError:
262 return []
263 tables = [
264 utilities.read_csv(path, dtype = str, keep_default_na = False)
265 for path in paths]
266 made: list[dict[str, Any]] = []
267 for column in columns:
268 for table in tables:
269 for row in table.to_dict('records'):
270 rule = {str(key): value for key, value in row.items()}
271 rule.update(column = column, name = f'{column}_agencies')
272 if column in party_columns:
273 rule['pattern'] = (
274 f'(?:{rule["pattern"]}){_PARTY_AGENCY_END}')
275 made.append(rule)
276 return made
279def make_court_rules(
280 jurisdiction: str = _JURISDICTION,
281 column: str = 'court',
282 *,
283 prefix: str = '',
284 levels: Sequence[str] | None = None) -> list[dict[str, Any]]:
285 """Returns rules that find a case's court from its name.
287 Each court of the jurisdiction's table of courts (see
288 `courtpy.courts.court_table`) gives two `category` rules for each
289 pattern of its names: one makes "{prefix}court_num" (its number) and the
290 other "{prefix}court_name" (its `court`, such as "tenth_circuit"), if
291 the pattern matches, ignoring case. Every court's "opinion_name" is
292 tried before any court's "fjc_name". Within each, the courts are tried in
293 the order of `levels`, and then in the order of the table (the courts
294 of appeals and the Supreme Court before the district courts, so that
295 "DISTRICT OF COLUMBIA" does not take the D.C. Circuit's cases).
297 Args:
298 jurisdiction: the folder of the jurisdiction's instructions, such as
299 "federal". Defaults to `_JURISDICTION`.
300 column: the section with the name of the court. Defaults to "court".
301 prefix: text put before the names of the columns that the rules make
302 (such as "lower_" for the court whose decision is reviewed).
303 Defaults to "", which makes "court_num" and "court_name".
304 levels: the levels of courts (as in the table's "level") to try, in
305 order. Courts of other levels are left out. Defaults to `None`,
306 which tries every court in the order of the table.
308 Returns:
309 The rules, as `dict`s with the columns of a file of rules. They are
310 empty if the jurisdiction has no table of courts.
312 """
313 try:
314 table = courts.court_table(jurisdiction)
315 except FileNotFoundError:
316 return []
317 if levels is not None:
318 rank = {level: place for place, level in enumerate(levels)}
319 table = table[table['level'].isin(rank)].sort_values(
320 'level', key = lambda found: found.map(rank), kind = 'stable')
321 made: list[dict[str, Any]] = []
322 for names in _COURT_NAME_COLUMNS:
323 for number, name, pattern in zip(
324 table['court_num'], table['court'], table[names],
325 strict = True):
326 if pd.isna(pattern) or not str(pattern).strip():
327 continue
328 note = f'From the {names} of {name} in courts.csv'
329 for made_name, value in (
330 ('court_num', str(number)), ('court_name', str(name))):
331 made.append({
332 'column': column,
333 'name': f'{prefix}{made_name}',
334 'kind': 'category',
335 'pattern': str(pattern),
336 'value': value,
337 'flags': 'ignorecase',
338 'note': note})
339 return made
342def make_header_rules(
343 source: str | None = None,
344 jurisdiction: str = _JURISDICTION,
345 *,
346 courts_named: bool = False) -> list[Any]:
347 """Returns the rules of a source's header.
349 The rules are, in order: "general/header.csv" (which divides the parties
350 and finds their roles, the disposition, the counsel, and the judges),
351 the rules of `make_agency_rules`, rules of `make_court_rules` that find
352 the court whose decision is reviewed in the history ("lower_court_num"
353 and "lower_court_name", trying the levels of `_LOWER_COURT_LEVELS` in
354 order), the source's "header.csv" in `_SOURCES` (if it has one), and,
355 if `courts_named`, the rules of `make_court_rules` that find the case's
356 own court ("court_num" and "court_name").
358 Args:
359 source: the name of the source, which is also the name of its folder
360 of rules in `_SOURCES`, such as "lexis_nexis". Defaults to
361 `None`, which uses only the rules that fit every source.
362 jurisdiction: the folder of the jurisdiction's rules, such as
363 "federal". Defaults to `_JURISDICTION`.
364 courts_named: whether the source's cases name their court in a
365 "court" section that `make_court_rules` should search. Defaults
366 to `False` (as for CourtListener, whose cases have the id of
367 their court, and of the court below if the docket names it).
369 Returns:
370 The rules, in any form that `amos.parsers.Rulebook.create` accepts.
372 """
373 found: list[Any] = [_GENERAL / f'{_HEADER}.csv']
374 found.extend(make_agency_rules(jurisdiction))
375 found.extend(make_court_rules(
376 jurisdiction, 'history', prefix = 'lower_',
377 levels = _LOWER_COURT_LEVELS))
378 if source is not None:
379 path = _SOURCES / source / f'{_HEADER}.csv'
380 if path.is_file(): 380 ↛ 382line 380 didn't jump to line 382 because the condition on line 380 was always true
381 found.append(path)
382 if courts_named:
383 found.extend(make_court_rules(jurisdiction))
384 return found
387def register_rulebooks(
388 *folders: pathlib.Path | str,
389 topics: Sequence[str] | None = None,
390 combined: str | None = None,
391 prefix: str = '') -> dict[str, type[amos.parsers.ParseAll]]:
392 """Makes a rulebook of each topic in folders of rule files.
394 Each CSV file in `folders` is a topic, named for its stem (such as
395 "criminal" for "criminal.csv"). The rulebook of a topic applies the file
396 of the topic in each folder that has one, in the order of `folders`, so
397 a folder of general rules can come before a folder of a jurisdiction's
398 rules. Each rulebook is a subclass of `amos.parsers.ParseAll`, which is
399 added to the `amos` library, so settings and `courtpy.parse` can name it
400 (such as "criminal"), and it is a technique of its own (such as
401 "parse_criminal"). A study can call this with its own folder of rules:
403 ```py
404 courtpy.rules.register_rulebooks(STUDY_FOLDER / 'instructions')
405 ```
407 Calling it again with the same names replaces the rulebooks.
409 Args:
410 *folders: folders of CSV files of rules, in the order in which their
411 rules are applied. "~" is the user's home folder.
412 topics: the topics to make rulebooks of, in order. Defaults to
413 `None`, which makes one of every file in `folders`, in
414 alphabetical order.
415 combined: the name of a rulebook that applies every topic, in the
416 order of `topics` (such as "federal"). Defaults to `None`, which
417 makes no such rulebook.
418 prefix: text put before the name of each topic's rulebook (with "_"
419 between), so that the topics of two jurisdictions can have
420 rulebooks of their own (such as "texas_civil"). Defaults to "",
421 which uses the names of the topics alone.
423 Raises:
424 FileNotFoundError: if a topic of `topics` has no file in `folders`,
425 or `folders` have no CSV files.
427 Returns:
428 The rulebooks, by their names (as settings name them), in order,
429 with the combined one (if any) last.
431 """
432 paths = [pathlib.Path(folder).expanduser() for folder in folders]
433 found = sorted({
434 file.stem for path in paths if path.is_dir()
435 for file in path.glob('*.csv')})
436 names = list(topics) if topics is not None else found
437 if not names:
438 searched = ', '.join(str(path) for path in paths)
439 message = f'there are no files of rules in {searched}'
440 raise FileNotFoundError(message)
441 books: dict[str, type[amos.parsers.ParseAll]] = {}
442 for topic in names:
443 files = [
444 path / f'{topic}.csv' for path in paths
445 if (path / f'{topic}.csv').is_file()]
446 if not files:
447 searched = ', '.join(str(path) for path in paths)
448 message = f'there is no file of rules for {topic!r} in {searched}'
449 raise FileNotFoundError(message)
450 name = f'{prefix}_{topic}' if prefix else topic
451 listed = ', '.join(
452 f'"{file.parent.name}/{file.name}"' for file in files)
453 books[name] = _make_rulebook(
454 name, files, f'Applies the rules of {listed}.')
455 if combined is not None:
456 listed = ', '.join(books)
457 books[combined] = _make_rulebook(
458 combined, list(books.values()),
459 f'Applies the rulebooks of every topic, in order: {listed}.')
460 return books
463""" Private Functions """
466def _make_rulebook(
467 name: str,
468 rules: Any,
469 summary: str) -> type[amos.parsers.ParseAll]:
470 """Makes a rulebook and adds it to the `amos` library.
472 Args:
473 name: the name of the rulebook, in snake case (such as "criminal").
474 Its class is named "Parse" and the name in camel case (such as
475 `ParseCriminal`).
476 rules: the rules, in any form that `amos.parsers.Rulebook.create`
477 accepts (such as a list of files).
478 summary: the first line of the class's documentation.
480 Returns:
481 The rulebook, a subclass of `amos.parsers.ParseAll`.
483 """
484 class_name = 'Parse' + ''.join(
485 part.capitalize() for part in name.split('_'))
486 book = type(class_name, (amos.parsers.ParseAll,), {
487 'rules': rules,
488 '__doc__': summary,
489 '__module__': __name__})
490 return dataclasses.dataclass(book)
493""" Rulebooks """
495# courtpy's own rulebooks: the federal rules of each topic (the general file
496# and then the federal one), "federal" for all of them, the rules of each
497# source's header, and the rules that find the sections of a Lexis-Nexis
498# case.
499RULEBOOKS: dict[str, type[amos.parsers.ParseAll]] = {
500 **register_rulebooks(
501 _GENERAL,
502 _INSTRUCTIONS / _JURISDICTION,
503 topics = _TOPICS,
504 combined = _JURISDICTION),
505 _HEADER: _make_rulebook(
506 _HEADER,
507 make_header_rules(),
508 'Finds the parties, their roles, and the judges in the header of a '
509 'case from a source with no header rules of its own.'),
510 f'courtlistener_{_HEADER}': _make_rulebook(
511 f'courtlistener_{_HEADER}',
512 make_header_rules('courtlistener'),
513 'Finds the parties, their roles, and the judges in a CourtListener '
514 'case.'),
515 f'lexis_nexis_{_HEADER}': _make_rulebook(
516 f'lexis_nexis_{_HEADER}',
517 make_header_rules('lexis_nexis', courts_named = True),
518 'Finds the court, the parties, their roles, and the judges in the '
519 'header of a Lexis-Nexis case.'),
520 'lexis_nexis': _make_rulebook(
521 'lexis_nexis',
522 find_structure_file('lexis_nexis', 'federal_appellate'),
523 'Finds the sections of a Lexis-Nexis case of a federal court of '
524 'appeals.')}