Coverage for src/courtpy/core/cases.py: 100%
65 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"""Court cases and tables of them.
3Contents:
4 Case: the text and information of one case, ready to be parsed.
5 column_as_flags: returns a column of a table of cases as plain booleans.
6 flags_as_numbers: returns a column of flags as numbers, keeping missing
7 values.
8 require_columns: raises an error if a table lacks columns.
9 select_whole_cases: returns which rows a query selects, keeping each
10 case whole.
11 split_cell: returns the values in a cell of a table of cases, as a list.
12 tidy: gives columns with missing values the right type.
13 _SEPARATOR: the text between several values in one cell.
14 _TRUE: text that `column_as_flags` reads as true.
15 _WHOLE_NUMBERS: columns that hold whole numbers.
17"""
19from __future__ import annotations
21import dataclasses
22import pathlib
23from collections.abc import Iterable
24from typing import Any
26import numpy as np
27import pandas as pd
29_SEPARATOR: str = '; '
30_TRUE: frozenset[str] = frozenset({'true', 't', '1', 'yes'})
31_WHOLE_NUMBERS: frozenset[str] = frozenset({
32 'year', 'court_num', 'lower_court_num', 'cluster_id', 'docket_id',
33 'author_id', 'citation_count'})
36@dataclasses.dataclass
37class Case:
38 """The text and information of one case, ready to be parsed.
40 Readers (such as `courtlistener.read_case` and `lexis.read_case`) make
41 cases from files, and a `Parser` turns each case into a row of a table.
43 Args:
44 id: a unique name for the case, which becomes the row's label in the
45 table (such as the CourtListener cluster id or the file name).
46 source: where the case came from: "courtlistener" or "lexis_nexis".
47 sections: sections of text that rules search, by name (such as
48 "party", "disposition", and "opinion"). Defaults to an empty
49 `dict`.
50 metadata: information that needs no parsing (such as the date filed
51 from CourtListener), by the name of its column. These values are
52 used instead of anything rules find with the same names. Defaults
53 to an empty `dict`.
54 path: the file the case came from. Defaults to `None`.
56 """
58 id: str
59 source: str
60 sections: dict[str, str] = dataclasses.field(default_factory = dict)
61 metadata: dict[str, Any] = dataclasses.field(default_factory = dict)
62 path: pathlib.Path | None = None
65def tidy(data: pd.DataFrame) -> pd.DataFrame:
66 """Gives columns of booleans or whole numbers with missing values a type.
68 `pandas` stores a column of booleans with missing values (such as
69 "published", which is unknown for some cases) as plain objects, and a
70 column of whole numbers with missing values (such as "year") as decimals.
71 Such columns become the "boolean" and "Int64" types, which allow missing
72 values.
74 Args:
75 data: a table of cases.
77 Returns:
78 The table, with those columns changed.
80 """
81 for column in data.columns:
82 values = data[column].dropna()
83 if len(values) == 0:
84 continue
85 if data[column].dtype == object and values.map(
86 lambda v: isinstance(v, bool)).all():
87 data[column] = data[column].astype('boolean')
88 elif (
89 column in _WHOLE_NUMBERS
90 and pd.api.types.is_float_dtype(data[column].dtype)
91 and (values == values.round()).all()):
92 data[column] = data[column].astype('Int64')
93 return data
96""" Helpers for Tables of Cases """
99def column_as_flags(data: pd.DataFrame, column: str) -> pd.Series:
100 """Returns a column of a table of cases as plain booleans.
102 Flags combined with `&` and `|` need plain booleans without missing
103 values. A missing value (or a missing column) is false. Text (as in a
104 table loaded from a CSV file) is true if it is "true", "t", "1", or "yes"
105 (in any case).
107 Args:
108 data: the cases.
109 column: name of the column.
111 Returns:
112 The column as plain booleans, or a column of false values if `data`
113 has no such column.
115 """
116 if column not in data.columns:
117 return pd.Series(False, index = data.index)
118 values = data[column]
119 # pandas reads text as the "str" type, or as `object` when it is mixed
120 # with other values.
121 if values.dtype == object or pd.api.types.is_string_dtype(values.dtype):
122 values = values.map(
123 lambda v: str(v).strip().lower() in _TRUE
124 if isinstance(v, str) else bool(v) if pd.notna(v) else False)
125 return values.astype('boolean').fillna(False).astype(bool)
128def flags_as_numbers(column: pd.Series) -> pd.Series:
129 """Returns a column of flags as numbers, keeping missing values.
131 Args:
132 column: flags, which may be missing.
134 Returns:
135 1.0 for true, 0.0 for false, and NaN for missing values, as plain
136 floats (so that means and models can use them).
138 """
139 return pd.Series(
140 column.astype('boolean').astype('Float64').to_numpy(
141 dtype = 'float64', na_value = np.nan),
142 index = column.index)
145def require_columns(
146 data: pd.DataFrame,
147 columns: Iterable[str],
148 name: str,
149 *,
150 hint: str | None = None) -> None:
151 """Raises an error if a table lacks columns.
153 Args:
154 data: the table.
155 columns: names of the columns that are needed.
156 name: what needs them (such as "a table of votes" or a technique's
157 name), for the message.
158 hint: a sentence added to the message, such as how to make the
159 columns. Defaults to `None`.
161 Raises:
162 KeyError: if a column is missing. The message names the missing
163 columns and `name`.
165 """
166 missing = [c for c in columns if c not in data.columns]
167 if missing:
168 message = f'{name} needs the columns {missing}, which are missing'
169 if hint:
170 message = f'{message}. {hint}'
171 raise KeyError(message)
174def select_whole_cases(
175 data: pd.DataFrame,
176 query: str | None,
177 *,
178 case_column: str = 'case_id') -> pd.Series:
179 """Returns which rows a query selects, keeping each case whole.
181 A table with several rows for each case (such as a row for each judge's
182 vote) is selected a case at a time, so that a case is never split.
184 Args:
185 data: the table.
186 query: an expression that `pandas.DataFrame.eval` reads (such as
187 "year >= 2010 and not dissenting"), or `None`.
188 case_column: the column with each row's case. Defaults to "case_id".
190 Raises:
191 KeyError: if `data` has no `case_column`.
192 ValueError: if the query does not say whether each row is selected
193 (such as "year + 1", which makes a number for each row).
195 Returns:
196 Whether each row is selected: every row without a query, and the
197 rows of a case only if the query selects every one of them.
199 """
200 if not query:
201 return pd.Series(True, index = data.index)
202 require_columns(data, [case_column], 'select_whole_cases')
203 message = (
204 f'the query {query!r} must say whether each row is selected (true '
205 f'or false), as "year >= 2010" does')
206 found = data.eval(query)
207 if not isinstance(found, pd.Series) or len(found) != len(data):
208 raise ValueError(message)
209 try:
210 selected = column_as_flags(
211 pd.DataFrame({'selected': found}, index = data.index),
212 'selected')
213 except (TypeError, ValueError) as error:
214 raise ValueError(message) from error
215 whole: pd.Series = selected.groupby(data[case_column]).transform('all')
216 return whole
219def split_cell(value: Any, separator: str = _SEPARATOR) -> list[Any]:
220 """Returns the values in a cell of a table of cases, as a list.
222 Rules that find several values (such as "panel_judges" or "agencies")
223 join them with "; " so that the table can be saved as a CSV file.
225 Args:
226 value: a cell: text with `separator` between its values, a list (or
227 tuple or array) of values, or a missing value.
228 separator: the text between the values. Defaults to "; ".
230 Returns:
231 The values, with text trimmed of spaces and without blank values. A
232 missing value or blank text has none.
234 """
235 if isinstance(value, list | tuple | np.ndarray):
236 return [v for v in value if not isinstance(v, str) or v.strip()]
237 if value is None or (not isinstance(value, str) and pd.isna(value)):
238 return []
239 pieces = (p.strip() for p in str(value).split(separator))
240 return [p for p in pieces if p]