Coverage for src/courtpy/core/utilities.py: 98%
112 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"""Shared tools.
3Contents:
4 config_folder: returns the folder for courtpy's settings and secrets.
5 data_folder: returns the folder for large downloads, such as bulk data.
6 expand_courts: turns court ids and group names into court ids.
7 instructions_folder: returns courtpy's "instructions" folder.
8 is_none_setting: returns whether a setting names nothing, such as "none"
9 or "false".
10 listify: returns a setting as a list of names.
11 locate: returns a file named in settings, found as a clerk finds files.
12 normalize: collapses all whitespace in text into single spaces.
13 open_session: returns a session that identifies courtpy to servers.
14 parse_date: returns an ISO date (YYYY-MM-DD) from a date in text.
15 read_csv: loads a CSV file that is in UTF-8 or Windows-1252.
16 to_bool: converts a setting or a CSV cell to a boolean.
17 to_date: converts a date setting to YYYY-MM-DD text.
18 to_integer: converts a whole-number setting to an `int`.
19 _ISO_DATE: pattern for a date written as YYYY-MM-DD, with the year, month,
20 and day as its groups.
21 _MONTHS: the number of each month, by the first three letters of its name
22 in capitals.
23 _NONE: text of a setting that turns something off.
24 _WRITTEN_DATE: pattern for a date written out, such as "January 5, 2010",
25 "Jan. 5, 2010", or "Sept. 5 2010", with the month, day, and year as
26 its groups.
28"""
30from __future__ import annotations
32import datetime
33import importlib.resources
34import os
35import pathlib
36import re
37import sys
38from collections.abc import Iterable
39from typing import Any
41import amos
42import pandas as pd
43import requests
45from . import options
47_MONTHS: dict[str, int] = {
48 'JAN': 1, 'FEB': 2, 'MAR': 3, 'APR': 4, 'MAY': 5, 'JUN': 6, 'JUL': 7,
49 'AUG': 8, 'SEP': 9, 'OCT': 10, 'NOV': 11, 'DEC': 12}
50# A date such as "January 5, 2010", "Jan. 5, 2010", or "Sept. 5 2010".
51_WRITTEN_DATE: re.Pattern[str] = re.compile(
52 r'\b(JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC)[A-Z]*\.?\s+'
53 r'(\d{1,2}),?\s+(\d{4})\b',
54 flags = re.IGNORECASE)
55_ISO_DATE: re.Pattern[str] = re.compile(r'\b(\d{4})-(\d{2})-(\d{2})\b')
56# Settings that turn something off.
57_NONE: frozenset[str] = frozenset({'', 'none', 'false', 'no', '0'})
60def config_folder() -> pathlib.Path:
61 """Returns the folder for courtpy's settings and secrets.
63 The folder is outside of any project or package, so that a secret (such as
64 the CourtListener API key) is never saved in a project's files or shared
65 with them. It is the folder named by the `COURTPY_CONFIG_DIR` environment
66 variable, if it is set. Otherwise, it is "courtpy" in the user's
67 application data folder on Windows ("%APPDATA%"), or in
68 "~/.config" (or "$XDG_CONFIG_HOME") on other systems.
70 Returns:
71 The path of the folder. It is not created.
73 """
74 named = os.environ.get(options._ENV_CONFIG)
75 if named:
76 return pathlib.Path(named).expanduser()
77 if sys.platform == 'win32': 77 ↛ 78line 77 didn't jump to line 78 because the condition on line 77 was never true
78 base = (
79 os.environ.get('APPDATA')
80 or pathlib.Path.home() / 'AppData' / 'Roaming')
81 return pathlib.Path(base) / 'courtpy'
82 base = os.environ.get('XDG_CONFIG_HOME') or pathlib.Path.home() / '.config'
83 return pathlib.Path(base) / 'courtpy'
86def data_folder() -> pathlib.Path:
87 """Returns the folder for large downloads, such as bulk data.
89 Bulk data files are very large (the opinions alone are more than 50 GB),
90 so they are kept outside of projects, where every project can share
91 them. The folder is the one named by the `COURTPY_DATA_DIR` environment
92 variable, if it is set. Otherwise, it is `options._DATA_SUBFOLDER`
93 ("courts") in the data folder of the `amos` workspace, which is where
94 every `amos` project keeps its data (see `amos.clerks.workspace`): with
95 projects in "projects/code", it is "projects/data/courts".
97 Returns:
98 The path of the folder. It is not created.
100 """
101 named = os.environ.get(options._ENV_DATA)
102 if named:
103 return pathlib.Path(named).expanduser()
104 return (
105 amos.clerks.workspace() / amos.options._DATA_FOLDER
106 / options._DATA_SUBFOLDER)
109def expand_courts(courts: str | Iterable[str] | None) -> list[str]:
110 """Turns court ids and names of groups of courts into court ids.
112 Args:
113 courts: CourtListener court ids (such as "ca1" or "scotus") or names of
114 groups in `options._COURT_GROUPS` (such as "federal_appellate"),
115 as a list or a comma-separated `str`.
117 Raises:
118 ValueError: if no courts are named.
120 Returns:
121 The court ids, in order, without repeats.
123 """
124 found: list[str] = []
125 for name in listify(courts):
126 for court in options._COURT_GROUPS.get(name.lower(), (name.lower(),)):
127 if court not in found:
128 found.append(court)
129 if not found:
130 message = 'name at least one court (such as "ca1") or group of courts'
131 raise ValueError(message)
132 return found
135def instructions_folder() -> pathlib.Path:
136 """Returns courtpy's "instructions" folder.
138 The folder has the built-in rulebooks (see `courtpy.rules`).
140 Returns:
141 The path of the folder, inside the installed package.
143 """
144 package = pathlib.Path(str(importlib.resources.files('courtpy')))
145 return package / 'instructions'
148def is_none_setting(value: Any) -> bool:
149 """Returns whether a setting names nothing, such as "none" or "false".
151 Settings such as "coders = none" turn something off.
153 Args:
154 value: a setting: `None`, a `bool`, or text.
156 Returns:
157 Whether `value` is `None`, `False`, or text (in any case, with any
158 spaces around it) in `_NONE`.
160 """
161 if value is None or value is False:
162 return True
163 return str(value).strip().lower() in _NONE
166def listify(item: Any) -> list[str]:
167 """Returns a setting as a list of names.
169 Args:
170 item: `None`, a `str` (which may list names separated by commas), or an
171 iterable of names.
173 Returns:
174 The names, with surrounding spaces removed and blank names dropped.
176 """
177 if item is None:
178 return []
179 if isinstance(item, str):
180 item = item.split(',')
181 elif not isinstance(item, Iterable):
182 item = [item]
183 return [str(name).strip() for name in item if str(name).strip()]
186def locate(path: pathlib.Path | str, clerk: Any = None) -> pathlib.Path:
187 """Returns a file named in settings, found as a clerk finds files.
189 Args:
190 path: a path, which may begin with "~" for the user's home folder.
191 clerk: the file manager of a project (a `nagata.FileManager`).
192 Defaults to `None`.
194 Returns:
195 `path` itself if it is absolute, exists in the current folder, or
196 there is no `clerk`, and otherwise `path` in the clerk's input
197 folder.
199 """
200 resolved = pathlib.Path(str(path)).expanduser()
201 if clerk is None or resolved.is_absolute() or resolved.exists():
202 return resolved
203 return pathlib.Path(clerk.input_folder) / resolved
206def normalize(text: str | None) -> str:
207 """Collapses all whitespace in `text` into single spaces.
209 Args:
210 text: text to normalize. `None` becomes an empty `str`.
212 Returns:
213 The text on one line, with single spaces between words.
215 """
216 return ' '.join(text.split()) if text else ''
219def open_session(session: Any = None) -> Any:
220 """Returns a session that identifies courtpy to servers.
222 Args:
223 session: an object with a `get` method like a `requests.Session`.
224 Defaults to `None`.
226 Returns:
227 `session`, or a new `requests.Session` with courtpy's user agent if
228 it is `None`.
230 """
231 if session is None:
232 session = requests.Session()
233 session.headers.update({'User-Agent': options._USER_AGENT})
234 return session
237def parse_date(text: str | None) -> str | None:
238 """Returns the first date in `text` as an ISO date (YYYY-MM-DD).
240 Args:
241 text: text with a date written out (such as "March 3, 2010" or
242 "Mar. 3, 2010") or in ISO format ("2010-03-03").
244 Returns:
245 The date, or `None` if there is no valid date in `text`.
247 """
248 if not text:
249 return None
250 match = _ISO_DATE.search(text)
251 if match:
252 year, month, day = (int(part) for part in match.groups())
253 else:
254 match = _WRITTEN_DATE.search(text)
255 if match is None:
256 return None
257 month = _MONTHS[match.group(1).upper()[:3]]
258 day, year = int(match.group(2)), int(match.group(3))
259 try:
260 return datetime.date(year, month, day).isoformat()
261 except ValueError:
262 return None
265def read_csv(path: pathlib.Path | str, **kwargs: Any) -> pd.DataFrame:
266 """Loads a CSV file that is in UTF-8 or Windows-1252.
268 The files of other researchers' data are not all in UTF-8, and some have
269 been in one encoding in one year and another in the next.
271 Args:
272 path: the path of the file, which may begin with "~" for the user's
273 home folder. A zip archive of one CSV file is read as that file.
274 **kwargs: arguments for `pandas.read_csv`.
276 Returns:
277 The table.
279 """
280 path = pathlib.Path(path).expanduser()
281 table: pd.DataFrame
282 try:
283 table = pd.read_csv(path, encoding = 'utf-8-sig', **kwargs)
284 except UnicodeDecodeError:
285 table = pd.read_csv(path, encoding = 'cp1252', **kwargs)
286 return table
289def to_bool(value: Any) -> bool:
290 """Converts a setting or a CSV cell to a boolean.
292 Args:
293 value: a `bool`, a number, or text such as "TRUE", "yes", "1", "t",
294 "FALSE", "no", "0", or "f" (in any case). Blank text is `False`.
296 Raises:
297 ValueError: if `value` is text that is not one of those.
299 Returns:
300 The boolean value.
302 """
303 if isinstance(value, bool):
304 return value
305 if value is None:
306 return False
307 if isinstance(value, int | float):
308 return bool(value)
309 text = str(value).strip().lower()
310 if text in {'true', 't', 'yes', 'y', '1'}:
311 return True
312 if text in {'false', 'f', 'no', 'n', '0', ''}:
313 return False
314 message = f'{value!r} is not TRUE or FALSE'
315 raise ValueError(message)
318def to_date(value: Any) -> str | None:
319 """Converts a date setting to YYYY-MM-DD text.
321 Args:
322 value: the setting: text such as "2019-01-01", or a date or date and
323 time (which a settings file may have turned it into).
325 Returns:
326 The first ten characters of the setting as text (the date), or `None`
327 if it is blank.
329 """
330 if value in (None, ''):
331 return None
332 return str(value)[:10]
335def to_integer(value: Any) -> int | None:
336 """Converts a whole-number setting to an `int`.
338 Args:
339 value: the setting, as a number or as text such as "500".
341 Raises:
342 ValueError: if the setting is not a whole number.
344 Returns:
345 The number, or `None` if the setting is blank.
347 """
348 if value in (None, ''):
349 return None
350 return int(value)