Coverage for src/courtpy/sources/courtlistener.py: 90%
594 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"""Downloads court opinions from CourtListener and reads them.
3CourtListener (https://www.courtlistener.com) is a free legal research site
4run by the Free Law Project. `CourtListener` downloads its opinions in two
5ways (its "method"):
7* "bulk" (the default) extracts them from the bulk data files, which need no
8 key and have no limits, but are very large and are updated every three
9 months.
10* "api" downloads them with the REST API, which needs an API key (see
11 `courtpy.secrets`). It is best for small or very recent sets of cases,
12 because CourtListener limits how many requests an account can make (a free
13 account can make 5 a minute, 50 an hour, and 125 a day, as of 2026). The
14 client waits when asked to, saves its place, and resumes where it stopped
15 when it is run again.
17Both save each case as a JSON file named for its CourtListener cluster id, in
18a folder named for its court (such as "courtlistener/ca1/4567890.json"),
19which `read_case` turns into a `Case` for parsing.
21The bulk data is published every three months (on the last day of March,
22June, September, and December), in a public bucket:
23https://com-courtlistener-storage.s3-us-west-2.amazonaws.com/list.html?prefix=bulk-data/
25Five files hold what courtpy needs, and every one is always read, so that
26each case is put in the court of its docket:
28| File | Size (2026) | Holds |
29| --- | --- | --- |
30| courts | < 1 MB | Each court's name and jurisdiction. |
31| dockets | about 5 GB | Each case's court, docket number, and dates. |
32| opinion-clusters | about 2.5 GB | Each decision's parties, judges, date, and status. |
33| citations | about 130 MB | Each decision's reporter citations. |
34| opinions | about 55 GB | The text of each opinion. |
36They are read in that order, keeping the cases of the courts and dates asked
37for, and each case is saved in the same form as the API's, so the same parser
38reads both. Every case is saved with its whole docket (all of its fields but
39those in `options._DOCKET_SKIPPED`), so the dockets file is read twice: first
40to find which dockets belong to the courts, and again, once the cases are
41known, to keep the dockets of those cases alone. Reading the opinions file
42takes hours, so it is worth extracting every court and year you may need at
43once.
45The files are read with `amos.loaders.read_chunks`, which decompresses and
46parses them on every core and keeps only the rows asked for. By default, they
47are downloaded first (to a folder outside of any project, see
48`courtpy.utilities.data_folder`) with `amos.loaders.download_file` and kept,
49so that they can be used again and an interrupted download resumes. With
50`stream = True`, they are read straight from the bucket instead, which needs
51no disk space but starts over if the connection fails.
53Contents:
54 DOWNLOAD_METHODS: the ways that `CourtListener.download` can download.
55 CourtListener: downloads cases from CourtListener's bulk data or API.
56 CourtListenerSource: reads cases saved by `CourtListener`.
57 CourtListenerError: raised when the API returns an error.
58 RateLimitError: raised when the API asks for a longer pause than allowed.
59 add_opinions: adds opinions to a saved case.
60 case_path: returns the path of a saved case.
61 citation_strings: returns citations as text.
62 is_complete: returns whether a case was saved with its opinions.
63 opinion_role: classifies an opinion as majority, concurrence, or dissent.
64 opinion_text: returns the plain text of an opinion.
65 read_case: reads a saved case for parsing.
66 save_case: saves a case.
67 slim_opinion: keeps one field of an opinion's text, to save space.
68 logger: the module's logger, which reports the progress of downloads,
69 of reading the bulk files, and pauses asked for by CourtListener.
71"""
73from __future__ import annotations
75import concurrent.futures
76import dataclasses
77import email.utils
78import io
79import json
80import logging
81import pathlib
82import re
83import sys
84import time
85import urllib.parse
86from collections.abc import Iterable, Iterator, Mapping, Sequence
87from typing import Any, ClassVar
88from xml.etree import ElementTree as ET
90import amos
91import pandas as pd
92import pypdf
93import requests
95from ..core import cases, options, secrets, utilities
96from ..references import courts
97from . import base
99logger = logging.getLogger(__name__)
100DOWNLOAD_METHODS: tuple[str, ...] = ('bulk', 'api')
101_SITE: str = 'https://www.courtlistener.com'
102_TEMPORARY: frozenset[int] = frozenset({500, 502, 503, 504})
103# Courts that moved their opinions' PDFs since CourtListener recorded their
104# addresses: the Ninth Circuit serves its old "www" addresses from "cdn",
105# and the Eleventh moved its files to "media".
106_PDF_MOVES: tuple[tuple[re.Pattern[str], str], ...] = (
107 (re.compile(r'^https?://www\.ca9\.uscourts\.gov/datastore/'),
108 'https://cdn.ca9.uscourts.gov/datastore/'),
109 (re.compile(r'^https?://www\.ca11\.uscourts\.gov/unpub/ops/'),
110 'https://media.ca11.uscourts.gov/opinions/unpub/files/'),
111 (re.compile(r'^https?://www\.ca11\.uscourts\.gov/opinions/ops/'),
112 'https://media.ca11.uscourts.gov/opinions/pub/files/'))
113_RETRIES: int = 4
114_OPINION_KEPT: tuple[str, ...] = (
115 'id', 'cluster_id', 'type', 'author_id', 'author_str', 'per_curiam',
116 'joined_by_str', 'joined_by', 'ordering_key', 'download_url')
117# "Concurrence in part" is checked before "dissent" and "concur", which it
118# also contains. "unamimous" is CourtListener's own spelling of the type.
119_ROLES: tuple[tuple[str, str], ...] = (
120 ('concurrenceinpart', 'mixed'),
121 ('in part', 'mixed'),
122 ('dissent', 'dissent'),
123 ('concur', 'concurrence'),
124 ('combined', 'majority'),
125 ('unanimous', 'majority'),
126 ('unamimous', 'majority'),
127 ('lead', 'majority'),
128 ('plurality', 'majority'),
129 ('onthemerits', 'majority'),
130 ('on the merits', 'majority'),
131 ('trialcourt', 'majority'),
132 ('trial court', 'majority'))
133_BULK_KINDS: tuple[str, ...] = (
134 'courts', 'dockets', 'opinion-clusters', 'citations', 'opinions')
135_BULK_BUFFER_BYTES: int = 200 * 1024 * 1024
136_BULK_DATE: re.Pattern[str] = re.compile(r'(\d{4}-\d{2}-\d{2})\.csv\.bz2$')
137# "source" is left out because it is a number in the dockets file but letters
138# in the opinion clusters file.
139_BULK_INTEGERS: frozenset[str] = frozenset({
140 'id', 'cluster_id', 'docket_id', 'author_id', 'citation_count',
141 'ordering_key', 'page_count', 'scdb_decision_direction',
142 'scdb_votes_majority', 'scdb_votes_minority', 'assigned_to_id',
143 'referred_to_id', 'idb_data_id', 'originating_court_information_id',
144 'parent_docket_id', 'federal_defendant_number'})
145_BULK_BOOLEANS: frozenset[str] = frozenset({
146 'per_curiam', 'blocked', 'date_filed_is_approximate', 'extracted_by_ocr'})
147_BULK_CLUSTER_SKIPPED: frozenset[str] = frozenset({
148 'date_created', 'date_modified', 'filepath_json_harvard',
149 'filepath_pdf_harvard', 'filepath_pdf_scan', 'filepath_xml_scan'})
152class CourtListenerError(RuntimeError):
153 """Raised when the CourtListener API returns an error."""
156class RateLimitError(CourtListenerError):
157 """Raised when the API asks for a longer pause than courtpy will wait.
159 Its message says how long to wait and how to resume.
161 Args:
162 seconds: how long CourtListener asked courtpy to wait.
164 """
166 def __init__(self, seconds: float) -> None: # noqa: D107
167 self.seconds = seconds
168 hours = seconds / 3600
169 message = (
170 f'CourtListener asked courtpy to wait {hours:.1f} hours before '
171 f"making more requests (the account's limit was reached). Run "
172 f'the same download again later: it resumes where it stopped. '
173 f'The bulk data (method "bulk") has no limits.')
174 super().__init__(message)
177@dataclasses.dataclass
178class CourtListener:
179 """Downloads cases from CourtListener's bulk data or its REST API.
181 `download` takes the "method" to download with: "bulk" (the default),
182 which extracts the cases from the bulk data files and needs no key, or
183 "api", which downloads them with the REST API (version 4).
185 Every request to the API includes the API key, which is found with
186 `courtpy.secrets.get_api_key` when the first request is made if it was
187 not passed, so the bulk data can be used without a key. Requests to the
188 API are spaced at least `min_interval` seconds apart. If CourtListener
189 asks for a pause (an HTTP 429 response), the client waits as long as it
190 is asked, up to `max_wait` seconds. A longer pause (such as the daily
191 limit) raises a `RateLimitError`, and `download` can be run again later
192 to resume.
194 Args:
195 api_key: a CourtListener API key. Defaults to `None`, in which case it
196 is found with `courtpy.secrets.get_api_key` when it is needed.
197 api_url: address of the API. Defaults to `options._API_URL`.
198 bulk_url: address of the bucket of bulk data. Defaults to
199 `options._BULK_URL`.
200 bulk_folder: folder to keep the downloaded bulk files in. Defaults
201 to `None`, in which case "bulk" in `utilities.data_folder()` is
202 used.
203 bulk_date: the date of the bulk files to use, as YYYY-MM-DD. Defaults
204 to `None`, in which case the newest files are used (and it is set
205 when they are found, see `resolve_bulk_date`).
206 stream: whether to read the bulk files straight from the bucket
207 instead of downloading them. Defaults to `False`.
208 min_interval: fewest seconds between requests to the API. Defaults to
209 `options._MIN_INTERVAL`.
210 max_wait: most seconds to wait when the API asks for a pause.
211 Defaults to `options._MAX_WAIT`.
212 timeout: seconds to wait for a response. Defaults to
213 `options._TIMEOUT`.
214 session: an object with a `get` method like a `requests.Session`.
215 Defaults to `None`, in which case a `requests.Session` that
216 identifies courtpy is made.
218 Attributes:
219 requests_made: number of requests made to the API by this client.
220 _courts: information about each court that has been looked up (see
221 `court`), by its id, so that each court is asked for only once.
222 _last_request: when the last request was made, from
223 `time.monotonic`, so that the next one can wait until
224 `min_interval` seconds have passed. It is 0 before the first
225 request.
227 """
229 api_key: str | None = dataclasses.field(default = None, repr = False)
230 api_url: str = options._API_URL
231 bulk_url: str = options._BULK_URL
232 bulk_folder: pathlib.Path | str | None = None
233 bulk_date: str | None = None
234 stream: bool = False
235 min_interval: float = options._MIN_INTERVAL
236 max_wait: float = options._MAX_WAIT
237 timeout: float = options._TIMEOUT
238 session: Any = dataclasses.field(default = None, repr = False)
239 requests_made: int = dataclasses.field(default = 0, init = False)
240 _last_request: float = dataclasses.field(
241 default = 0.0, init = False, repr = False)
242 _courts: dict[str, dict[str, Any]] = dataclasses.field(
243 default_factory = dict, init = False, repr = False)
245 """ Initialization Methods """
247 def __post_init__(self) -> None:
248 """Prepares the session.
250 If no `session` was passed, a `requests.Session` that identifies
251 courtpy is made. The API key is not looked for until the first
252 request to the API (see `get`), and it is sent with requests to the
253 API alone, never to the bucket of bulk data.
255 """
256 self.session = utilities.open_session(self.session)
258 """ Public Methods """
260 def bulk_dates(self, kind: str = 'opinions') -> list[str]:
261 """Returns the dates of the bulk files of one kind in the bucket.
263 Args:
264 kind: "courts", "dockets", "opinion-clusters", "citations", or
265 "opinions". Defaults to "opinions".
267 Returns:
268 The dates, from oldest to newest.
270 """
271 dates = []
272 for key in self._list_bucket(f'{options._BULK_PREFIX}{kind}-'):
273 match = _BULK_DATE.search(key)
274 # Skips files whose kind only starts with `kind` (such as
275 # "opinions-cited" for "opinions").
276 if match and key == ( 276 ↛ 272line 276 didn't jump to line 272 because the condition on line 276 was always true
277 f'{options._BULK_PREFIX}{kind}-{match.group(1)}.csv.bz2'):
278 dates.append(match.group(1))
279 return sorted(set(dates))
281 def court(self, court: str) -> dict[str, Any]:
282 """Returns information about a court.
284 Args:
285 court: a CourtListener court id, such as "ca1".
287 Returns:
288 The court's "id", "full_name", "short_name", "citation_string",
289 and "jurisdiction" (such as "F" for federal appellate courts).
291 """
292 if court not in self._courts: 292 ↛ 296line 292 didn't jump to line 296 because the condition on line 292 was always true
293 fields = 'id,full_name,short_name,citation_string,jurisdiction'
294 self._courts[court] = self.get(
295 f'courts/{court}/', {'fields': fields})
296 return self._courts[court]
298 def download(
299 self,
300 courts: str | Iterable[str],
301 start_date: str | None = None,
302 end_date: str | None = None,
303 folder: pathlib.Path | str = 'courtlistener',
304 *,
305 method: str = 'bulk',
306 max_cases: int | None = None,
307 dockets: bool = False,
308 refresh: bool = False) -> list[pathlib.Path]:
309 """Downloads the cases of `courts` filed between two dates.
311 With "bulk", the bulk files are read in turn (see the module's
312 documentation), and the cases that were already saved with their
313 opinions are skipped. Every case is saved with its docket.
315 With "api", each page of cases (opinion clusters) takes one request,
316 and their opinions take one more (or more, if they have many
317 opinions). Cases that were already saved (with their opinions) are
318 skipped, and the place in each court's list of cases is saved, so
319 running a download again resumes it. Running a finished download
320 again takes one request for each court and saves any cases added to
321 CourtListener since.
323 Args:
324 courts: CourtListener court ids (such as "ca1") or names of groups
325 of them (such as "federal_appellate").
326 start_date: earliest date filed, as YYYY-MM-DD. Defaults to `None`
327 (no earliest date).
328 end_date: latest date filed, as YYYY-MM-DD. Defaults to `None` (no
329 latest date).
330 folder: folder to save the cases in. Defaults to "courtlistener".
331 method: "bulk" or "api" (see `DOWNLOAD_METHODS`), in any case.
332 Defaults to "bulk".
333 max_cases: most cases to save: in all with "bulk", and in each
334 court with "api". Defaults to `None` (every case).
335 dockets: with "api", whether to also download each case's docket
336 (every field but those in `options._DOCKET_SKIPPED`, such as
337 its docket number, dates, and the court appealed from). This
338 takes one more request for each case. Defaults to `False`.
339 The bulk data always includes the docket.
340 refresh: whether to download cases that were already saved.
341 Defaults to `False`.
343 Raises:
344 ValueError: if `method` is not one of `DOWNLOAD_METHODS`, or if no
345 courts are named.
346 RateLimitError: if CourtListener asks for a pause longer than
347 `max_wait`. What was downloaded is kept.
349 Returns:
350 The paths of the cases saved (or updated) in this run.
352 """
353 chosen = str(method).strip().lower()
354 if chosen not in DOWNLOAD_METHODS:
355 names = ' or '.join(f'"{m}"' for m in DOWNLOAD_METHODS)
356 message = f'method must be {names}, not {method!r}'
357 raise ValueError(message)
358 wanted = utilities.expand_courts(courts)
359 folder = pathlib.Path(folder)
360 if chosen == 'bulk':
361 return self._download_from_bulk_data(
362 wanted, start_date, end_date, folder,
363 max_cases = max_cases, refresh = refresh)
364 saved: list[pathlib.Path] = []
365 for court in wanted:
366 saved.extend(self._download_court(
367 court, start_date, end_date, folder,
368 max_cases = max_cases, dockets = dockets,
369 refresh = refresh))
370 logger.info(
371 'saved %d cases in %s with %d requests', len(saved), folder,
372 self.requests_made)
373 return saved
375 def download_case(
376 self,
377 cluster_id: int | str,
378 folder: pathlib.Path | str = 'courtlistener') -> pathlib.Path:
379 """Downloads one case by its CourtListener cluster id.
381 This takes four requests: the case, its opinions, its docket (which
382 names its court), and its court (unless another case from the same
383 court was downloaded by this client).
385 Args:
386 cluster_id: the id of the opinion cluster (the number in the
387 case's CourtListener address, after "/opinion/").
388 folder: folder to save the case in. Defaults to "courtlistener".
390 Returns:
391 The path of the saved case.
393 """
394 cluster = self.get(f'clusters/{cluster_id}/')
395 opinions = self._opinions_of([int(cluster['id'])])
396 return self._save(
397 cluster, opinions.get(int(cluster['id']), []), pathlib.Path(folder),
398 court = None, docket = True)
400 def fetch_bulk_file(self, kind: str) -> pathlib.Path:
401 """Downloads one bulk file, resuming a download that was interrupted.
403 The file is downloaded with `amos.loaders.download_file`, which
404 writes it beside its path (with ".part" added) until it is whole, so
405 a file in the bulk folder is always complete.
407 Args:
408 kind: "courts", "dockets", "opinion-clusters", "citations", or
409 "opinions".
411 Raises:
412 OSError: if the download stopped before the whole file arrived
413 (run it again to resume).
414 requests.HTTPError: if the file cannot be downloaded.
416 Returns:
417 The path of the downloaded file.
419 """
420 name = self._bulk_name(kind)
421 folder = self._bulk_folder_path()
422 path = folder / name
423 if not path.is_file():
424 logger.info('downloading %s to %s', name, folder)
425 return amos.loaders.download_file(
426 self._bulk_file_url(kind),
427 path,
428 timeout = self.timeout,
429 session = self.session,
430 resume = True)
432 def fetch_pdf_headers(
433 self,
434 paths: Iterable[pathlib.Path | str],
435 *,
436 refresh: bool = False,
437 delay: float | None = None,
438 workers: int = 4) -> pd.DataFrame:
439 """Saves the first page of each case's PDF, from its court's website.
441 CourtListener's text of many opinions starts after their header, so
442 it lacks the panel ("Before: FERNANDEZ, GOULD, and M. SMITH, Circuit
443 Judges"), and its list of judges may give only their last names,
444 which two judges of a court can share. The court's own PDF of the
445 opinion has the header on its first page. For each saved case, the
446 PDF at its first opinion's "download_url" is downloaded, the text of
447 its first page is saved in the case's file as "pdf_header" (with
448 "pdf_header_status"), and the PDF is not kept. `read_case` makes it a
449 section of its own, which the rule that finds the panel reads after
450 the opinion's opening.
452 The requests to each website are made one at a time, `delay` seconds
453 apart, and up to `workers` websites are asked at once. The API key is
454 never sent. A case whose file already has a header (or a status, if
455 its PDF could not be read) is skipped unless `refresh` is true.
457 Args:
458 paths: paths of saved cases.
459 refresh: whether to fetch the PDF of a case again. Defaults to
460 `False`.
461 delay: seconds between requests to one website. Defaults to
462 `None`, which uses `options._PDF_DELAY`.
463 workers: websites to ask at once. With 1, every request is made
464 with `session`; otherwise each website gets a session of its
465 own. Defaults to 4.
467 Returns:
468 A row for each case, with its "path", "url", and "status": "ok",
469 "saved before", "no url", "http {code}" (such as "http 404"),
470 "not a pdf", "unreadable", or "failed: {error}".
472 """
473 pause = options._PDF_DELAY if delay is None else float(delay)
474 rows: list[dict[str, Any]] = []
475 hosts: dict[str, list[tuple[pathlib.Path, dict[str, Any], str]]] = {}
476 for path in (pathlib.Path(p) for p in paths):
477 record = json.loads(path.read_text(encoding = 'utf-8'))
478 url = _pdf_url(record)
479 if 'pdf_header_status' in record and not refresh:
480 status = 'saved before'
481 elif not url:
482 status = 'no url'
483 else:
484 host = urllib.parse.urlparse(url).netloc
485 hosts.setdefault(host, []).append((path, record, url))
486 continue
487 rows.append({'path': str(path), 'url': url, 'status': status})
489 def fetch(
490 cases_of_host: list[tuple[pathlib.Path, dict[str, Any], str]],
491 session: Any) -> list[dict[str, Any]]:
492 """Fetches the PDFs of one website's cases, one at a time.
494 Args:
495 cases_of_host: the path, record, and PDF's address of each
496 case.
497 session: the session to request them with.
499 Returns:
500 A row for each case.
502 """
503 done = []
504 for place, (path, record, url) in enumerate(cases_of_host):
505 if place:
506 time.sleep(pause)
507 text, status = _fetch_pdf_header(session, url, self.timeout)
508 record['pdf_header'] = text
509 record['pdf_header_status'] = status
510 save_case(path, record)
511 done.append({'path': str(path), 'url': url, 'status': status})
512 return done
514 groups = list(hosts.values())
515 if int(workers) <= 1: 515 ↛ 519line 515 didn't jump to line 519 because the condition on line 515 was always true
516 for group in groups:
517 rows.extend(fetch(group, self.session))
518 else:
519 with concurrent.futures.ThreadPoolExecutor(
520 max_workers = int(workers)) as pool:
521 jobs = [
522 pool.submit(fetch, group, utilities.open_session())
523 for group in groups]
524 for job in jobs:
525 rows.extend(job.result())
526 table = pd.DataFrame(rows, columns = ['path', 'url', 'status'])
527 logger.info(
528 'fetched the PDF headers of %d cases: %s', len(table),
529 table['status'].value_counts().to_dict())
530 return table
532 def get(
533 self,
534 path: str,
535 params: Mapping[str, Any] | None = None) -> dict[str, Any]:
536 """Returns the JSON response of one request to the API.
538 Args:
539 path: a path in the API (such as "clusters/") or a full address
540 (such as the "next" page of a response).
541 params: query parameters. Defaults to `None`.
543 Raises:
544 CourtListenerError: if the API returns an error, rejects the key,
545 or cannot be reached after several tries.
546 MissingAPIKeyError: if no key was passed and none can be found
547 (see `courtpy.secrets.get_api_key`).
548 RateLimitError: if the API asks for a pause longer than
549 `max_wait`.
551 Returns:
552 The decoded JSON.
554 """
555 url = path if path.startswith('http') else urllib.parse.urljoin(
556 self.api_url, path)
557 headers = self._api_headers()
558 failures = 0
559 while True:
560 self._space_requests()
561 try:
562 response = self.session.get(
563 url, params = params, headers = headers,
564 timeout = self.timeout)
565 except requests.RequestException as error:
566 failures += 1
567 if failures > _RETRIES:
568 message = f'CourtListener could not be reached: {error}'
569 raise CourtListenerError(message) from error
570 time.sleep(5 * 2 ** failures)
571 continue
572 finally:
573 self.requests_made += 1
574 self._last_request = time.monotonic()
575 status = response.status_code
576 if status == 429:
577 wait = _retry_after(response)
578 if wait > self.max_wait:
579 raise RateLimitError(wait)
580 logger.info(
581 'CourtListener asked for a pause: waiting %.0f seconds',
582 wait)
583 time.sleep(wait)
584 continue
585 if status in _TEMPORARY and failures < _RETRIES:
586 failures += 1
587 time.sleep(5 * 2 ** failures)
588 continue
589 if status in (401, 403):
590 message = (
591 f'CourtListener rejected the request ({status}). Check '
592 f'the API key with "courtpy key show". Details: '
593 f'{_detail(response)}'
594 )
595 raise CourtListenerError(message)
596 if status >= 400:
597 message = (
598 f'CourtListener returned {status}: {_detail(response)}')
599 raise CourtListenerError(message)
600 return dict(response.json())
602 def pages(
603 self,
604 path: str,
605 params: Mapping[str, Any] | None = None) -> Iterator[
606 tuple[list[dict[str, Any]], str | None]]:
607 """Yields the results of each page of a list, and the next address.
609 Args:
610 path: a path in the API (such as "clusters/") or the address of a
611 page.
612 params: query parameters for the first page. Defaults to `None`.
614 Yields:
615 tuple[list[dict[str, Any]], str | None]: the results on each page
616 and the address of the next page (or `None` after the last
617 page).
619 """
620 url: str | None = path
621 query = params
622 while url:
623 data = self.get(url, query)
624 next_url = data.get('next')
625 yield list(data.get('results', [])), next_url
626 url, query = next_url, None
628 def read_bulk_chunks(
629 self,
630 kind: str,
631 *,
632 columns: Sequence[str] | None = None,
633 keep: Mapping[str, Any] | None = None) -> Iterator[pd.DataFrame]:
634 """Yields chosen rows and columns of one bulk file, a chunk at a time.
636 The file is read with `amos.loaders.read_chunks`, which parses and
637 decompresses it on every core and finds the rows in `keep` before
638 any of their text becomes Python objects. If `stream` is true, the
639 file is read from the bucket as it arrives, without being saved.
640 Otherwise, it is downloaded first (or found in the bulk folder) with
641 `fetch_bulk_file`.
643 Args:
644 kind: "courts", "dockets", "opinion-clusters", "citations", or
645 "opinions".
646 columns: the columns to return. Defaults to `None`, which
647 returns every column.
648 keep: the values to keep of each of some columns, such as
649 `{'court_id': ['ca1']}` (see `amos.loaders.read_chunks`).
650 Defaults to `None`, which keeps every row.
652 Yields:
653 pd.DataFrame: the rows of each chunk that are kept, with every
654 value as text. Missing values are empty `str`s.
656 """
657 source = (
658 self._bulk_file_url(kind) if self.stream
659 else self.fetch_bulk_file(kind))
660 yield from amos.loaders.read_chunks(
661 source,
662 columns = columns,
663 keep = keep,
664 double_quote = False,
665 escape_char = '\\',
666 session = self.session,
667 timeout = self.timeout)
669 def read_bulk_rows(
670 self,
671 kind: str,
672 *,
673 columns: Sequence[str] | None = None,
674 keep: Mapping[str, Any] | None = None) -> Iterator[dict[str, str]]:
675 """Yields chosen rows of one bulk file.
677 Args:
678 kind: "courts", "dockets", "opinion-clusters", "citations", or
679 "opinions".
680 columns: the columns to return. Defaults to `None`, which
681 returns every column.
682 keep: the values to keep of each of some columns (see
683 `read_bulk_chunks`). Defaults to `None`, which keeps every
684 row.
686 Yields:
687 dict[str, str]: each row, mapping column names to text. Missing
688 values are empty `str`s.
690 """
691 chunks = self.read_bulk_chunks(kind, columns = columns, keep = keep)
692 for chunk in chunks:
693 for row in chunk.to_dict('records'):
694 yield {str(key): value for key, value in row.items()}
696 def resolve_bulk_date(self) -> str:
697 """Returns `bulk_date`, finding the newest complete set if needed.
699 Raises:
700 LookupError: if no date has every kind of file that courtpy needs.
702 Returns:
703 The date of the bulk files to use, as YYYY-MM-DD.
705 """
706 if self.bulk_date is None:
707 common: set[str] | None = None
708 for kind in _BULK_KINDS:
709 dates = set(self.bulk_dates(kind))
710 common = dates if common is None else common & dates
711 if not common: 711 ↛ 712line 711 didn't jump to line 712 because the condition on line 711 was never true
712 message = 'no date in the bulk data has every file needed'
713 raise LookupError(message)
714 self.bulk_date = max(common)
715 return self.bulk_date
717 """ Private Methods """
719 def _api_headers(self) -> dict[str, str]:
720 """Returns the headers of a request to the API.
722 The API key is found with `courtpy.secrets.get_api_key` the first
723 time, if none was passed.
725 Raises:
726 MissingAPIKeyError: if no key was passed and none can be found.
728 Returns:
729 Headers that include the key and ask for JSON.
731 """
732 if self.api_key is None:
733 self.api_key = secrets.get_api_key()
734 return {
735 'Authorization': f'Token {self.api_key}',
736 'Accept': 'application/json'}
738 def _bulk_citations(self, cluster_ids: set[int]) -> dict[int, list[str]]:
739 """Returns the citations of the clusters in `cluster_ids`.
741 The citations file is read only if there are clusters to look for.
743 Args:
744 cluster_ids: ids of the opinion clusters (cases) being extracted.
746 Returns:
747 The citations of each cluster, as text such as "950 F.3d 12", by
748 its id. Clusters without citations are left out.
750 """
751 found: dict[int, list[str]] = {}
752 if not cluster_ids: 752 ↛ 753line 752 didn't jump to line 753 because the condition on line 752 was never true
753 return found
754 kept = {'cluster_id': cluster_ids}
755 for row in self.read_bulk_rows('citations', keep = kept):
756 cluster_id = _integer(row.get('cluster_id'))
757 if cluster_id is not None: 757 ↛ 755line 757 didn't jump to line 755 because the condition on line 757 was always true
758 found.setdefault(cluster_id, []).extend(
759 citation_strings([row]))
760 return found
762 def _bulk_clusters(
763 self,
764 dockets: Mapping[int, Any],
765 start_date: str | None,
766 end_date: str | None,
767 max_cases: int | None) -> dict[int, dict[str, Any]]:
768 """Returns the clusters of `dockets` filed between two dates.
770 The clusters file is read only if there are dockets to look for, and
771 reading stops once `max_cases` clusters are found. Dates are compared
772 as text, which works because they are written as YYYY-MM-DD.
774 Args:
775 dockets: the dockets of the courts being extracted, by their ids
776 (only the ids are used).
777 start_date: earliest date filed, as YYYY-MM-DD, or `None` for no
778 earliest date.
779 end_date: latest date filed, as YYYY-MM-DD, or `None` for no latest
780 date.
781 max_cases: most clusters to find, or `None` for every cluster.
783 Returns:
784 Each cluster (converted with `_convert_bulk_row`, without the
785 columns in `_BULK_CLUSTER_SKIPPED`), by its id.
787 """
788 found: dict[int, dict[str, Any]] = {}
789 if not dockets: 789 ↛ 790line 789 didn't jump to line 790 because the condition on line 789 was never true
790 return found
791 kept = {'docket_id': dockets.keys()}
792 for row in self.read_bulk_rows('opinion-clusters', keep = kept):
793 filed = row.get('date_filed') or ''
794 if (start_date and filed < start_date) or (
795 end_date and filed > end_date):
796 continue
797 cluster = _convert_bulk_row(row)
798 for column in _BULK_CLUSTER_SKIPPED:
799 cluster.pop(column, None)
800 found[int(cluster['id'])] = cluster
801 if max_cases is not None and len(found) >= max_cases: 801 ↛ 802line 801 didn't jump to line 802 because the condition on line 801 was never true
802 break
803 logger.info('found %d cases', len(found))
804 return found
806 def _bulk_courts(self, wanted: list[str]) -> dict[str, dict[str, Any]]:
807 """Returns information about the courts in `wanted`.
809 A warning is logged for any court in `wanted` that is not in the
810 courts file (usually a misspelled court id).
812 Args:
813 wanted: CourtListener court ids.
815 Returns:
816 The "id", "full_name", "short_name", "citation_string", and
817 "jurisdiction" of each court that was found, by its id.
819 """
820 kept = (
821 'id', 'full_name', 'short_name', 'citation_string', 'jurisdiction')
822 found = {
823 row['id']: {k: row.get(k) for k in kept}
824 for row in self.read_bulk_rows('courts', keep = {'id': wanted})}
825 missing = [c for c in wanted if c not in found]
826 if missing: 826 ↛ 827line 826 didn't jump to line 827 because the condition on line 826 was never true
827 logger.warning('these courts are not in the bulk data: %s', missing)
828 return found
830 def _bulk_docket_courts(self, wanted: set[str]) -> dict[int, str]:
831 """Returns the court of each docket of the courts in `wanted`.
833 Only the court is kept, because a court has far more dockets than
834 cases with opinions, and all of their fields would not fit in memory
835 for large courts. `_bulk_dockets` reads the fields of the dockets
836 that are needed once the cases are known.
838 Args:
839 wanted: CourtListener court ids.
841 Returns:
842 The court id of each docket of those courts, by the docket's id.
844 """
845 found: dict[int, str] = {}
846 rows = self.read_bulk_rows(
847 'dockets', columns = ['id', 'court_id'],
848 keep = {'court_id': wanted})
849 for row in rows:
850 court = row['court_id']
851 docket_id = _integer(row['id'])
852 if docket_id is not None: 852 ↛ 849line 852 didn't jump to line 849 because the condition on line 852 was always true
853 # One `str` is shared by every docket of a court.
854 found[docket_id] = sys.intern(court)
855 logger.info('found %d dockets', len(found))
856 return found
858 def _bulk_dockets(self, docket_ids: set[int]) -> dict[int, dict[str, Any]]:
859 """Returns the dockets in `docket_ids`.
861 The dockets file is read only if there are dockets to look for, and
862 reading stops once they are all found.
864 Args:
865 docket_ids: ids of the dockets of the cases being extracted.
867 Returns:
868 Each docket (converted with `_convert_bulk_row`, without the
869 columns in `options._DOCKET_SKIPPED`), by its id.
871 """
872 found: dict[int, dict[str, Any]] = {}
873 if not docket_ids: 873 ↛ 874line 873 didn't jump to line 874 because the condition on line 873 was never true
874 return found
875 for row in self.read_bulk_rows('dockets', keep = {'id': docket_ids}): 875 ↛ 883line 875 didn't jump to line 883 because the loop on line 875 didn't complete
876 docket_id = int(row['id'])
877 docket = _convert_bulk_row(row)
878 for column in options._DOCKET_SKIPPED:
879 docket.pop(column, None)
880 found[docket_id] = docket
881 if len(found) == len(docket_ids): 881 ↛ 875line 881 didn't jump to line 875 because the condition on line 881 was always true
882 break
883 logger.info('read %d dockets', len(found))
884 return found
886 def _bulk_file_url(self, kind: str) -> str:
887 """Returns the address of the bulk file of one kind.
889 Args:
890 kind: one of `_BULK_KINDS`.
892 Raises:
893 ValueError: if `kind` is not one of `_BULK_KINDS`.
895 Returns:
896 The address of the file in the bucket.
898 """
899 return f'{self.bulk_url}{options._BULK_PREFIX}{self._bulk_name(kind)}'
901 def _bulk_folder_path(self) -> pathlib.Path:
902 """Returns the folder to keep the downloaded bulk files in.
904 Returns:
905 `bulk_folder`, or "bulk" in `utilities.data_folder()` if it is
906 `None`.
908 """
909 if self.bulk_folder is None: 909 ↛ 910line 909 didn't jump to line 910 because the condition on line 909 was never true
910 return utilities.data_folder() / 'bulk'
911 return pathlib.Path(self.bulk_folder)
913 def _bulk_name(self, kind: str) -> str:
914 """Returns the name of the bulk file of one kind.
916 Args:
917 kind: one of `_BULK_KINDS`.
919 Raises:
920 ValueError: if `kind` is not one of `_BULK_KINDS`.
922 Returns:
923 The file's name, such as "opinions-2026-09-30.csv.bz2", for the date
924 from `resolve_bulk_date`.
926 """
927 if kind not in _BULK_KINDS:
928 message = f'kind must be one of {list(_BULK_KINDS)}, not {kind!r}'
929 raise ValueError(message)
930 return f'{kind}-{self.resolve_bulk_date()}.csv.bz2'
932 def _bulk_opinions(self, paths: Mapping[int, pathlib.Path]) -> None:
933 """Adds the opinions of the cases in `paths` to their files.
935 The opinions file is not sorted by case, so a case's opinions can be
936 anywhere in it. Opinions are held in memory (with one field of text
937 each, see `slim_opinion`) until their text reaches
938 `_BULK_BUFFER_BYTES`, and then written to their cases, which keeps
939 memory use bounded without rewriting a case's file for every opinion.
941 Args:
942 paths: the path of each saved case, by its cluster id.
944 """
945 buffer: dict[int, list[dict[str, Any]]] = {}
946 size = 0
947 kept = {'cluster_id': paths.keys()}
948 for row in self.read_bulk_rows('opinions', keep = kept):
949 cluster_id = int(row['cluster_id'])
950 opinion = slim_opinion(_convert_bulk_row(row))
951 buffer.setdefault(cluster_id, []).append(opinion)
952 size += sum(len(v) for v in opinion.values() if isinstance(v, str))
953 if size >= _BULK_BUFFER_BYTES: 953 ↛ 954line 953 didn't jump to line 954 because the condition on line 953 was never true
954 _write_buffered_opinions(buffer, paths)
955 size = 0
956 _write_buffered_opinions(buffer, paths)
958 def _download_from_bulk_data(
959 self,
960 courts: list[str],
961 start_date: str | None,
962 end_date: str | None,
963 folder: pathlib.Path,
964 *,
965 max_cases: int | None,
966 refresh: bool) -> list[pathlib.Path]:
967 """Saves the cases of `courts` from the bulk data (see `download`).
969 Args:
970 courts: CourtListener court ids, with groups already expanded.
971 start_date: earliest date filed, as YYYY-MM-DD, or `None` for no
972 earliest date.
973 end_date: latest date filed, as YYYY-MM-DD, or `None` for no
974 latest date.
975 folder: folder to save the cases in.
976 max_cases: most cases to save, or `None` for every case.
977 refresh: whether to replace cases that were already saved with
978 their opinions.
980 Returns:
981 The paths of the cases saved (or updated) by this call.
983 """
984 date = self.resolve_bulk_date()
985 logger.info('extracting cases from the bulk data of %s', date)
986 court_records = self._bulk_courts(courts)
987 docket_courts = self._bulk_docket_courts(set(courts))
988 clusters = self._bulk_clusters(
989 docket_courts, start_date, end_date, max_cases)
990 dockets = self._bulk_dockets(
991 {int(c['docket_id']) for c in clusters.values()})
992 citations = self._bulk_citations(set(clusters))
993 paths: dict[int, pathlib.Path] = {}
994 for cluster_id, cluster in clusters.items():
995 docket = dockets[int(cluster['docket_id'])]
996 court = docket_courts[int(cluster['docket_id'])]
997 path = case_path(folder, court, cluster_id)
998 if not refresh and is_complete(path):
999 continue
1000 save_case(path, {
1001 'source': 'courtlistener',
1002 'bulk_date': date,
1003 'court': court_records.get(court, {'id': court}),
1004 'cluster': cluster,
1005 'docket': docket,
1006 'citations': citations.get(cluster_id, []),
1007 'opinions': []})
1008 paths[cluster_id] = path
1009 logger.info('saved %d cases; now adding their opinions', len(paths))
1010 if paths:
1011 self._bulk_opinions(paths)
1012 return list(paths.values())
1014 def _download_court(
1015 self,
1016 court: str,
1017 start_date: str | None,
1018 end_date: str | None,
1019 folder: pathlib.Path,
1020 *,
1021 max_cases: int | None,
1022 dockets: bool,
1023 refresh: bool) -> list[pathlib.Path]:
1024 """Downloads the cases of one court with the API (see `download`).
1026 The court's cases (opinion clusters) are listed one page at a time, in
1027 the order they were added to CourtListener. For each page, the
1028 opinions of the cases that are not already saved are requested
1029 together, and each case is saved. After each page, the address of the
1030 next page (and of the page just read) is saved in a state file in the
1031 ".courtpy" folder of `folder`, named for the court and dates, so that
1032 the download can be resumed. Information about the court is saved
1033 there too, so that it is asked for only once.
1035 Args:
1036 court: a CourtListener court id, such as "ca1".
1037 start_date: earliest date filed, as YYYY-MM-DD, or `None` for no
1038 earliest date.
1039 end_date: latest date filed, as YYYY-MM-DD, or `None` for no latest
1040 date.
1041 folder: folder to save the cases in.
1042 max_cases: most cases to save in this run, or `None` for every
1043 case. A page that would go past it is cut short and read again
1044 the next time, so that the cases left out are not skipped.
1045 dockets: whether to also download each case's docket.
1046 refresh: whether to start from the first page and download cases
1047 that were already saved.
1049 Returns:
1050 The paths of the cases saved in this run.
1052 """
1053 state_path = folder / '.courtpy' / (
1054 f'api_{court}_{start_date or "start"}_{end_date or "end"}.json')
1055 state = _load_json(state_path) or {}
1056 params: dict[str, Any] = {'docket__court': court, 'order_by': 'id'}
1057 if start_date:
1058 params['date_filed__gte'] = start_date
1059 if end_date:
1060 params['date_filed__lte'] = end_date
1061 # The court is saved so that resuming a download does not ask again.
1062 court_path = folder / '.courtpy' / f'court_{court}.json'
1063 information = _load_json(court_path)
1064 if information is None:
1065 information = self.court(court)
1066 _save_json(court_path, information)
1067 self._courts[court] = information
1068 saved: list[pathlib.Path] = []
1069 # Every address is complete (with its filters), so any page can be
1070 # saved and requested again to resume. Cases are listed in the order
1071 # they were added to CourtListener, so after the last page has been
1072 # read, reading it again finds any cases added since.
1073 first = urllib.parse.urljoin(self.api_url, 'clusters/')
1074 url = (
1075 None if refresh else state.get('next') or state.get('last')
1076 ) or f'{first}?{urllib.parse.urlencode(params)}'
1077 while url:
1078 data = self.get(url)
1079 clusters = list(data.get('results', []))
1080 next_url = data.get('next')
1081 needed = [
1082 c for c in clusters if refresh or not is_complete(
1083 case_path(folder, court, c['id']))]
1084 remaining = None if max_cases is None else max_cases - len(saved)
1085 trimmed = remaining is not None and len(needed) > remaining
1086 if trimmed:
1087 needed = needed[:remaining]
1088 if needed:
1089 opinions = self._opinions_of(
1090 [int(c['id']) for c in needed], court = court)
1091 for cluster in needed:
1092 saved.append(self._save(
1093 cluster, opinions.get(int(cluster['id']), []), folder,
1094 court = information, docket = dockets))
1095 # A trimmed page is read again next time, so that the cases left
1096 # out are not skipped.
1097 state['next'] = url if trimmed else next_url
1098 state['last'] = url
1099 _save_json(state_path, state)
1100 logger.info(
1101 '%s: %d cases saved (%d requests so far)', court, len(saved),
1102 self.requests_made)
1103 if trimmed or (max_cases is not None and len(saved) >= max_cases):
1104 break
1105 url = next_url
1106 return saved
1108 def _list_bucket(self, prefix: str) -> list[str]:
1109 """Returns the keys in the bucket of bulk data that start with `prefix`.
1111 The bucket is listed with Amazon S3's "ListObjectsV2" request, which
1112 returns at most 1,000 keys at a time as XML, with a token for the next
1113 part of the list when there are more.
1115 Args:
1116 prefix: the start of the keys (file paths) to list, such as
1117 "bulk-data/opinions-".
1119 Raises:
1120 requests.HTTPError: if the bucket cannot be listed.
1122 Returns:
1123 The keys, in the order the bucket lists them.
1125 """
1126 keys: list[str] = []
1127 token = None
1128 while True:
1129 params = {'list-type': '2', 'prefix': prefix}
1130 if token: 1130 ↛ 1131line 1130 didn't jump to line 1131 because the condition on line 1130 was never true
1131 params['continuation-token'] = token
1132 response = self.session.get(
1133 self.bulk_url, params = params, timeout = self.timeout)
1134 response.raise_for_status()
1135 # The listing comes from the bucket's own server.
1136 root = ET.fromstring(response.content) # noqa: S314
1137 namespace = (
1138 root.tag.split('}')[0] + '}' if root.tag.startswith('{')
1139 else '')
1140 keys.extend(
1141 element.text or ''
1142 for element in root.iter(f'{namespace}Key'))
1143 truncated = root.findtext(f'{namespace}IsTruncated') == 'true'
1144 token = root.findtext(f'{namespace}NextContinuationToken')
1145 if not truncated or not token: 1145 ↛ 1128line 1145 didn't jump to line 1128 because the condition on line 1145 was always true
1146 return keys
1148 def _opinions_of(
1149 self,
1150 cluster_ids: Sequence[int],
1151 court: str | None = None) -> dict[int, list[dict[str, Any]]]:
1152 """Returns the opinions of the clusters in `cluster_ids`.
1154 The opinions of a page of clusters are requested together, by the
1155 range of their ids (and their court, to keep the range small).
1157 Args:
1158 cluster_ids: ids of opinion clusters.
1159 court: the court of the clusters. Defaults to `None`.
1161 Raises:
1162 CourtListenerError: if the API returns opinions of other clusters
1163 (which means that it did not apply the filter).
1165 Returns:
1166 The opinions of each cluster, by its id, with only one field of
1167 text each (see `options._TEXT_FIELDS`).
1169 """
1170 low, high = min(cluster_ids), max(cluster_ids)
1171 params: dict[str, Any] = {
1172 'cluster__id__range': f'{low},{high}',
1173 'order_by': 'id',
1174 'fields': ','.join((*options._OPINION_FIELDS, 'cluster'))}
1175 if court:
1176 params['cluster__docket__court'] = court
1177 wanted = set(cluster_ids)
1178 found: dict[int, list[dict[str, Any]]] = {i: [] for i in cluster_ids}
1179 for results, _ in self.pages('opinions/', params):
1180 for opinion in results:
1181 cluster_id = _cluster_id(opinion)
1182 if cluster_id is None or not low <= cluster_id <= high:
1183 message = (
1184 'CourtListener returned an opinion of a case that was '
1185 'not asked for, so the "cluster__id__range" filter may '
1186 'have changed. Please report this at '
1187 'https://github.com/WithPrecedent/courtpy/issues'
1188 )
1189 raise CourtListenerError(message)
1190 if cluster_id in wanted: 1190 ↛ 1180line 1190 didn't jump to line 1180 because the condition on line 1190 was always true
1191 found[cluster_id].append(slim_opinion(opinion))
1192 return found
1194 def _space_requests(self) -> None:
1195 """Waits until `min_interval` seconds have passed since the last one.
1197 Nothing is done before the first request (when `_last_request` is 0)
1198 or if enough time has passed already.
1200 """
1201 if self._last_request:
1202 wait = self.min_interval - (time.monotonic() - self._last_request)
1203 if wait > 0: 1203 ↛ 1204line 1203 didn't jump to line 1204 because the condition on line 1203 was never true
1204 time.sleep(wait)
1206 def _save(
1207 self,
1208 cluster: Mapping[str, Any],
1209 opinions: Sequence[Mapping[str, Any]],
1210 folder: pathlib.Path,
1211 *,
1212 court: Mapping[str, Any] | None,
1213 docket: bool) -> pathlib.Path:
1214 """Saves a cluster and its opinions (and docket, if asked) as a case.
1216 The case is saved in the folder of its court, which is the court's id
1217 from `court` or, if that is `None`, from the docket. A case whose court
1218 cannot be found is saved in a folder named "unknown". The cluster's
1219 list of opinion addresses ("sub_opinions") is not kept, because the
1220 opinions themselves are. Every field of the docket is kept but those
1221 in `options._DOCKET_SKIPPED`.
1223 Args:
1224 cluster: the opinion cluster, from the API.
1225 opinions: its opinions, each with one field of text (see
1226 `slim_opinion`).
1227 folder: the folder of saved cases.
1228 court: information about the case's court (see `court`), or `None`
1229 if it is not known. If it is `None` and the docket is
1230 downloaded, the court is looked up from the docket's
1231 "court_id".
1232 docket: whether to download the case's docket (one more request).
1234 Returns:
1235 The path of the saved case.
1237 """
1238 docket_record = None
1239 docket_id = cluster.get('docket_id') or _id_from_url(
1240 cluster.get('docket'))
1241 if docket and docket_id:
1242 docket_record = {
1243 k: v for k, v in self.get(f'dockets/{docket_id}/').items()
1244 if k not in options._DOCKET_SKIPPED}
1245 court_id = (
1246 (court or {}).get('id') or (docket_record or {}).get('court_id'))
1247 if court is None and docket_record and docket_record.get('court_id'):
1248 court = self.court(str(docket_record['court_id']))
1249 record = {
1250 'source': 'courtlistener',
1251 'court': dict(court or {'id': court_id}),
1252 'cluster': {
1253 k: v for k, v in cluster.items() if k != 'sub_opinions'},
1254 'docket': docket_record,
1255 'citations': citation_strings(cluster.get('citations', [])),
1256 'opinions': list(opinions)}
1257 path = case_path(folder, str(court_id or 'unknown'), cluster['id'])
1258 save_case(path, record)
1259 return path
1262@dataclasses.dataclass
1263class CourtListenerSource(base.Source):
1264 """Reads cases saved by `CourtListener`, from the bulk data or the API.
1266 Each case is a JSON file (see `read_case`), whose sections come from its
1267 data, so no rules are needed to find them. The "courtlistener_header"
1268 rules find the parties and judges in them.
1270 """
1272 name: ClassVar[str] = 'courtlistener'
1273 pattern: ClassVar[str] = '*.json'
1274 header: ClassVar[str] = 'courtlistener_header'
1276 """ Required Methods """
1278 def read(self, path: pathlib.Path) -> cases.Case:
1279 """Reads a saved case for parsing (see `read_case`).
1281 Args:
1282 path: the path of the saved case.
1284 Returns:
1285 The case.
1287 """
1288 return read_case(path)
1291""" Public Functions """
1294def add_opinions(
1295 path: pathlib.Path,
1296 opinions: Iterable[Mapping[str, Any]]) -> None:
1297 """Adds opinions to a saved case, replacing any with the same id.
1299 Args:
1300 path: path of the saved case.
1301 opinions: opinions to add.
1303 """
1304 record = json.loads(path.read_text(encoding = 'utf-8'))
1305 existing = {o.get('id'): o for o in record.get('opinions', [])}
1306 for opinion in opinions:
1307 existing[opinion.get('id')] = dict(opinion)
1308 record['opinions'] = list(existing.values())
1309 save_case(path, record)
1312def case_path(
1313 folder: pathlib.Path | str,
1314 court: str,
1315 cluster_id: int | str) -> pathlib.Path:
1316 """Returns the path of a saved case.
1318 Args:
1319 folder: the folder of saved cases.
1320 court: the case's CourtListener court id.
1321 cluster_id: the case's CourtListener cluster id.
1323 Returns:
1324 "{folder}/{court}/{cluster_id}.json".
1326 """
1327 return pathlib.Path(folder) / court / f'{cluster_id}.json'
1330def citation_strings(citations: Iterable[Any]) -> list[str]:
1331 """Returns citations as text, such as "123 F.3d 456".
1333 Args:
1334 citations: citations from CourtListener: `dict`s with "volume",
1335 "reporter", and "page", or text.
1337 Returns:
1338 The citations as text.
1340 """
1341 found = []
1342 for citation in citations or []:
1343 if isinstance(citation, Mapping): 1343 ↛ 1347line 1343 didn't jump to line 1347 because the condition on line 1343 was always true
1344 parts = (citation.get(k) for k in ('volume', 'reporter', 'page'))
1345 text = ' '.join(str(p) for p in parts if p not in (None, ''))
1346 else:
1347 text = str(citation)
1348 if text.strip(): 1348 ↛ 1342line 1348 didn't jump to line 1342 because the condition on line 1348 was always true
1349 found.append(text.strip())
1350 return found
1353def is_complete(path: pathlib.Path) -> bool:
1354 """Returns whether a case was saved with at least one opinion.
1356 Args:
1357 path: path of a saved case.
1359 Returns:
1360 Whether the file exists, can be read, and has an opinion.
1362 """
1363 if not path.is_file():
1364 return False
1365 try:
1366 record = json.loads(path.read_text(encoding = 'utf-8'))
1367 except (OSError, ValueError):
1368 return False
1369 return bool(record.get('opinions'))
1372def opinion_role(kind: str | None) -> str:
1373 """Classifies an opinion by its CourtListener type.
1375 Args:
1376 kind: the opinion's "type", such as "010combined", "020lead",
1377 "030concurrence", "035concurrenceinpart", or "040dissent".
1379 Returns:
1380 "majority" (combined, lead, unanimous, or plurality opinions, and
1381 opinions without a type), "concurrence", "dissent", "mixed" (an
1382 opinion concurring in part and dissenting in part), or "other"
1383 (such as an addendum).
1385 """
1386 text = (kind or '').lower()
1387 if not text:
1388 return 'majority'
1389 for fragment, role in _ROLES:
1390 if fragment in text:
1391 return role
1392 return 'other'
1395def opinion_text(opinion: Mapping[str, Any]) -> str:
1396 """Returns the plain text of an opinion.
1398 Args:
1399 opinion: an opinion from CourtListener.
1401 Returns:
1402 The text of the first field in `options._TEXT_FIELDS` that is not
1403 blank, converted from HTML or XML, or an empty `str`.
1405 """
1406 for field in options._TEXT_FIELDS: 1406 ↛ 1410line 1406 didn't jump to line 1410 because the loop on line 1406 didn't complete
1407 value = opinion.get(field)
1408 if isinstance(value, str) and value.strip():
1409 return amos.mungers.html_to_text(value)
1410 return ''
1413def read_case(path: pathlib.Path | str) -> cases.Case:
1414 """Reads a saved CourtListener case for parsing.
1416 The sections of text have the same names as the sections that rules find
1417 in Lexis-Nexis cases (such as "party", "history", "counsel", and
1418 "judges"), so that the same rules work for both. "court_num" and
1419 "court_name" are courtpy's number and name for the case's court, found
1420 by CourtListener's id for it in the table of courts of
1421 `options._DEFAULT_JURISDICTION` (see
1422 `courtpy.courts.court_numbers_by_courtlistener_name`), and
1423 "lower_court_num" and "lower_court_name" are those of the court appealed
1424 from, by the docket's id for it. Each is `None` if the table does not
1425 have the court (the header rules then look for the court appealed from
1426 in the history).
1428 Args:
1429 path: path of a case saved by `CourtListener`.
1431 Returns:
1432 The case.
1434 """
1435 path = pathlib.Path(path)
1436 record = json.loads(path.read_text(encoding = 'utf-8'))
1437 cluster = record.get('cluster') or {}
1438 docket = record.get('docket') or {}
1439 court = record.get('court') or {}
1440 opinions = sorted(
1441 record.get('opinions') or [],
1442 key = lambda o: (
1443 o.get('ordering_key') is None, o.get('ordering_key') or 0,
1444 str(o.get('type') or ''), o.get('id') or 0))
1445 roles = [opinion_role(o.get('type')) for o in opinions]
1447 def authors(*kinds: str) -> str:
1448 """Returns the authors of the case's opinions with some roles.
1450 Args:
1451 *kinds: roles of opinions (see `opinion_role`), such as
1452 "majority" or "dissent".
1454 Returns:
1455 The "author_str" of each opinion with one of those roles, one per
1456 line, leaving out blank ones.
1458 """
1459 return '\n'.join(
1460 str(o.get('author_str') or '').strip()
1461 for o, role in zip(opinions, roles, strict = True)
1462 if role in kinds and str(o.get('author_str') or '').strip())
1464 majority = [
1465 o for o, role in zip(opinions, roles, strict = True)
1466 if role == 'majority']
1467 texts = [opinion_text(o) for o in opinions]
1468 sections = {
1469 'party': _first(
1470 cluster.get('case_name_full'), docket.get('case_name_full'),
1471 cluster.get('case_name')),
1472 'court': _first(court.get('full_name'), court.get('id')),
1473 'docket_number': _first(docket.get('docket_number')),
1474 'citation': '; '.join(record.get('citations') or []),
1475 'history': '\n'.join(_texts(
1476 cluster.get('procedural_history'), cluster.get('history'),
1477 docket.get('appeal_from_str'))),
1478 'counsel': _first(cluster.get('attorneys')),
1479 'disposition': _first(cluster.get('disposition')),
1480 'judges': _first(cluster.get('judges'), docket.get('panel_str')),
1481 'opinion_by': authors('majority'),
1482 'concurring_lines': authors('concurrence', 'mixed'),
1483 'dissenting_lines': authors('dissent', 'mixed'),
1484 'posture': _first(cluster.get('posture')),
1485 'syllabus': _first(cluster.get('syllabus')),
1486 'pdf_header': _first(record.get('pdf_header')),
1487 'opinion': '\n\n'.join(t for t in texts if t)}
1488 sections = {
1489 k: amos.mungers.html_to_text(v) if '<' in v else v
1490 for k, v in sections.items() if v}
1491 date_filed = _first(cluster.get('date_filed'))
1492 status = _first(cluster.get('precedential_status'))
1493 court_id = court.get('id') or docket.get('court_id')
1494 lower_id = _court_id_from(
1495 docket.get('appeal_from_id') or docket.get('appeal_from'))
1496 numbers = courts.court_numbers_by_courtlistener_name(
1497 options._DEFAULT_JURISDICTION)
1498 names = courts.court_names_by_courtlistener_name(
1499 options._DEFAULT_JURISDICTION)
1500 metadata: dict[str, Any] = {
1501 'source': 'courtlistener',
1502 'cluster_id': cluster.get('id'),
1503 'docket_id': cluster.get('docket_id') or docket.get('id') or (
1504 _id_from_url(cluster.get('docket'))),
1505 'court': court_id,
1506 'court_num': numbers.get(str(court_id or '').lower()),
1507 'court_name': names.get(str(court_id or '').lower()),
1508 'lower_court_num': numbers.get(lower_id or ''),
1509 'lower_court_name': names.get(lower_id or ''),
1510 'case_name': _first(cluster.get('case_name')),
1511 'docket_number': sections.get('docket_number'),
1512 'citation': sections.get('citation'),
1513 'disposition': sections.get('disposition'),
1514 'judges': sections.get('judges'),
1515 'date_filed': date_filed or None,
1516 'date_argued': _first(docket.get('date_argued')) or None,
1517 'year': int(date_filed[:4]) if date_filed[:4].isdigit() else None,
1518 'precedential_status': status or None,
1519 'published': status.lower() == 'published' if status else None,
1520 'per_curiam': any(_true(o.get('per_curiam')) for o in majority),
1521 'opinions': len(opinions),
1522 'author_id': next(
1523 (o.get('author_id') for o in majority if o.get('author_id')), None),
1524 'panel_ids': [
1525 i for i in (_id_from_url(p) for p in cluster.get('panel') or [])
1526 if i is not None],
1527 'citation_count': cluster.get('citation_count'),
1528 'nature_of_suit': _first(
1529 cluster.get('nature_of_suit'), docket.get('nature_of_suit'))
1530 or None,
1531 'url': _url(cluster)}
1532 # Only cases of the Supreme Court have an id in the Supreme Court
1533 # Database, so other tables of cases get no column for it.
1534 if _first(cluster.get('scdb_id')):
1535 metadata['scdb_id'] = _first(cluster.get('scdb_id'))
1536 return cases.Case(
1537 id = str(cluster.get('id') or path.stem),
1538 source = 'courtlistener',
1539 sections = sections,
1540 metadata = metadata,
1541 path = path)
1544def save_case(path: pathlib.Path, record: Mapping[str, Any]) -> None:
1545 """Saves a case as a JSON file, replacing any file at `path` safely.
1547 Args:
1548 path: path to save the case to. Its folder is created if needed.
1549 record: the case: "source", "court", "cluster", "docket",
1550 "citations", and "opinions".
1552 """
1553 path.parent.mkdir(parents = True, exist_ok = True)
1554 temporary = path.with_suffix('.json.part')
1555 temporary.write_text(
1556 json.dumps(record, ensure_ascii = False), encoding = 'utf-8')
1557 temporary.replace(path)
1560def slim_opinion(opinion: Mapping[str, Any]) -> dict[str, Any]:
1561 """Returns an opinion with only one field of text, to save space.
1563 Args:
1564 opinion: an opinion from the API or the bulk data.
1566 Returns:
1567 The fields in `_OPINION_KEPT` that it has, and the first field in
1568 `options._TEXT_FIELDS` that is not blank.
1570 """
1571 slim = {k: opinion[k] for k in _OPINION_KEPT if k in opinion}
1572 if 'cluster_id' not in slim: 1572 ↛ 1573line 1572 didn't jump to line 1573 because the condition on line 1572 was never true
1573 slim['cluster_id'] = _cluster_id(opinion)
1574 for field in options._TEXT_FIELDS: 1574 ↛ 1579line 1574 didn't jump to line 1579 because the loop on line 1574 didn't complete
1575 value = opinion.get(field)
1576 if isinstance(value, str) and value.strip():
1577 slim[field] = value
1578 break
1579 return slim
1582""" Private Functions """
1585def _cluster_id(opinion: Mapping[str, Any]) -> int | None:
1586 """Returns the cluster id of an opinion.
1588 Args:
1589 opinion: an opinion from the API or the bulk data.
1591 Returns:
1592 Its "cluster_id" or, if that is missing, the id at the end of its
1593 "cluster" address (as the API gives it), or `None` if it has
1594 neither.
1596 """
1597 value = opinion.get('cluster_id')
1598 if value not in (None, ''): 1598 ↛ 1600line 1598 didn't jump to line 1600 because the condition on line 1598 was always true
1599 return int(value)
1600 return _id_from_url(opinion.get('cluster'))
1603def _detail(response: Any) -> str:
1604 """Returns the explanation in an error response, shortened.
1606 Args:
1607 response: a response from the API, like a `requests.Response`.
1609 Returns:
1610 The "detail" of its JSON (where CourtListener explains an error) or,
1611 if there is none, the text of the response, cut to 300
1612 characters.
1614 """
1615 try:
1616 detail = response.json().get('detail')
1617 except Exception: # noqa: BLE001
1618 detail = None
1619 return str(detail or getattr(response, 'text', ''))[:300]
1622def _fetch_pdf_header(
1623 session: Any,
1624 url: str,
1625 timeout: float) -> tuple[str, str]:
1626 """Returns the text of the first page of an opinion's PDF.
1628 Args:
1629 session: an object with a `get` method like a `requests.Session`.
1630 url: the address of the PDF.
1631 timeout: seconds to wait for a response.
1633 A court that moved its PDFs is asked at their new address (see
1634 `_PDF_MOVES`) when the old one is not found.
1636 Returns:
1637 The text, with single spaces (or blank if it could not be read), and
1638 the status of the request (see `CourtListener.fetch_pdf_headers`).
1640 """
1641 addresses = [url] + [
1642 pattern.sub(moved, url) for pattern, moved in _PDF_MOVES
1643 if pattern.search(url)]
1644 for place, address in enumerate(addresses): 1644 ↛ 1654line 1644 didn't jump to line 1654 because the loop on line 1644 didn't complete
1645 try:
1646 response = session.get(address, timeout = timeout)
1647 except requests.RequestException as error:
1648 return '', f'failed: {type(error).__name__}'
1649 code = getattr(response, 'status_code', 200)
1650 if code == 200:
1651 break
1652 if code != 404 or place == len(addresses) - 1:
1653 return '', f'http {code}'
1654 content = bytes(response.content or b'')
1655 if not content.startswith(b'%PDF'):
1656 return '', 'not a pdf'
1657 try:
1658 reader = pypdf.PdfReader(io.BytesIO(content))
1659 text = reader.pages[0].extract_text() if reader.pages else ''
1660 except (pypdf.errors.PyPdfError, ValueError, KeyError, IndexError):
1661 return '', 'unreadable'
1662 return ' '.join((text or '').split()), 'ok'
1665def _first(*values: Any) -> str:
1666 """Returns the first value that is not blank, as text.
1668 Args:
1669 *values: values to check, in order of preference (such as a case's
1670 full name and then its short name).
1672 Returns:
1673 The first value that is not `None` or blank, with spaces trimmed from
1674 each end, or an empty `str` if they are all blank.
1676 """
1677 for value in values:
1678 if value not in (None, '') and str(value).strip():
1679 return str(value).strip()
1680 return ''
1683def _convert_bulk_row(row: Mapping[str, str]) -> dict[str, Any]:
1684 """Returns a row of a bulk file with numbers, booleans, and missing values.
1686 Args:
1687 row: the row, with every value as text.
1689 Returns:
1690 The row, with ids and counts as `int`s, "t" and "f" as `bool`s, and
1691 empty text as `None`.
1693 """
1694 converted: dict[str, Any] = {}
1695 for key, value in row.items():
1696 if value == '':
1697 converted[key] = None
1698 elif key in _BULK_INTEGERS:
1699 converted[key] = _integer(value)
1700 elif key in _BULK_BOOLEANS:
1701 converted[key] = value == 't'
1702 else:
1703 converted[key] = value
1704 return converted
1707def _court_id_from(value: Any) -> str | None:
1708 """Returns CourtListener's id for a court that a docket refers to.
1710 Bulk dockets name the court appealed from by its id ("appeal_from_id",
1711 such as "mad"), and the API by its address ("appeal_from", such as
1712 "https://www.courtlistener.com/api/rest/v4/courts/mad/").
1714 Args:
1715 value: a court's id, its address, a `dict` with its "id", or `None`.
1717 Returns:
1718 The id in lower case, or `None` if `value` is blank.
1720 """
1721 if isinstance(value, Mapping): 1721 ↛ 1722line 1721 didn't jump to line 1722 because the condition on line 1721 was never true
1722 value = value.get('id')
1723 if value in (None, ''):
1724 return None
1725 text = str(value).strip().rstrip('/')
1726 return text.rsplit('/', 1)[-1].lower() or None
1729def _id_from_url(url: Any) -> int | None:
1730 """Returns the id at the end of an API address.
1732 The API refers to related objects by their addresses, such as
1733 "https://www.courtlistener.com/api/rest/v4/people/101/".
1735 Args:
1736 url: an address that ends in a number (with or without a final
1737 slash), an id itself, or `None`.
1739 Returns:
1740 The id, or `None` if `url` is blank or does not end in a number.
1742 """
1743 if url in (None, ''): 1743 ↛ 1744line 1743 didn't jump to line 1744 because the condition on line 1743 was never true
1744 return None
1745 if isinstance(url, int): 1745 ↛ 1746line 1745 didn't jump to line 1746 because the condition on line 1745 was never true
1746 return url
1747 match = re.search(r'(\d+)/?$', str(url))
1748 return int(match.group(1)) if match else None
1751def _integer(value: Any) -> int | None:
1752 """Returns `value` as an `int`, if it is a whole number.
1754 Args:
1755 value: a value from a bulk file, usually text such as "4567890".
1757 Returns:
1758 The number, or `None` if `value` is missing or is not a whole number.
1760 """
1761 try:
1762 return int(value)
1763 except (TypeError, ValueError):
1764 return None
1767def _load_json(path: pathlib.Path) -> dict[str, Any] | None:
1768 """Returns the contents of a JSON file.
1770 Args:
1771 path: path of the file, such as a download's state file.
1773 Returns:
1774 The contents, or `None` if there is no file.
1776 """
1777 if not path.is_file():
1778 return None
1779 return dict(json.loads(path.read_text(encoding = 'utf-8')))
1782def _pdf_url(record: Mapping[str, Any]) -> str:
1783 """Returns the address of a saved case's PDF on its court's website.
1785 Args:
1786 record: a saved case.
1788 Returns:
1789 The first web address among the "download_url" of its opinions, or
1790 an empty `str`.
1792 """
1793 for opinion in record.get('opinions') or []:
1794 url = str(opinion.get('download_url') or '').strip()
1795 if url.lower().startswith(('http://', 'https://')):
1796 return url
1797 return ''
1800def _retry_after(response: Any) -> float:
1801 """Returns how many seconds a 429 response asks the client to wait.
1803 Args:
1804 response: the response, like a `requests.Response`.
1806 Returns:
1807 The seconds in the "Retry-After" header (a number of seconds or a
1808 date) or in the message ("Expected available in N seconds"), or
1809 60 if neither says.
1811 """
1812 headers = getattr(response, 'headers', {})
1813 header = str(headers.get('Retry-After', '')).strip()
1814 if header:
1815 try:
1816 return max(float(header), 0.0)
1817 except ValueError:
1818 moment = email.utils.parsedate_to_datetime(header)
1819 if moment is not None:
1820 return max(moment.timestamp() - time.time(), 0.0)
1821 match = re.search(r'available in (\d+)', _detail(response))
1822 return float(match.group(1)) if match else 60.0
1825def _save_json(path: pathlib.Path, contents: Mapping[str, Any]) -> None:
1826 """Saves `contents` as a JSON file, creating its folder if needed.
1828 Args:
1829 path: path to save the file to.
1830 contents: what to save. It must be something that `json` can write.
1832 """
1833 path.parent.mkdir(parents = True, exist_ok = True)
1834 path.write_text(json.dumps(contents, indent = 2), encoding = 'utf-8')
1837def _texts(*values: Any) -> list[str]:
1838 """Returns the values that are not blank, as text.
1840 Args:
1841 *values: values to keep, if they are not blank (such as a case's
1842 procedural history and the court it was appealed from).
1844 Returns:
1845 Each value that is not `None` or blank, with spaces trimmed from each
1846 end, in order.
1848 """
1849 return [
1850 str(v).strip() for v in values
1851 if v not in (None, '') and str(v).strip()]
1854def _true(value: Any) -> bool:
1855 """Returns whether a value from the API or bulk data is true.
1857 The API gives booleans, but the bulk data (written by PostgreSQL) gives
1858 "t" and "f".
1860 Args:
1861 value: a boolean, or text such as "t", "true", or "1" (in any case).
1863 Returns:
1864 Whether `value` is true.
1866 """
1867 if isinstance(value, str): 1867 ↛ 1868line 1867 didn't jump to line 1868 because the condition on line 1867 was never true
1868 return value.strip().lower() in {'t', 'true', '1'}
1869 return bool(value)
1872def _url(cluster: Mapping[str, Any]) -> str | None:
1873 """Returns the address of a case on CourtListener.
1875 Args:
1876 cluster: the case's opinion cluster.
1878 Returns:
1879 Its "absolute_url" on CourtListener's website or, if it has none (as
1880 in the bulk data), an address made from its id and "slug", or
1881 `None` if it has no id either.
1883 """
1884 if cluster.get('absolute_url'):
1885 return f'{_SITE}{cluster["absolute_url"]}'
1886 if cluster.get('id'): 1886 ↛ 1889line 1886 didn't jump to line 1889 because the condition on line 1886 was always true
1887 slug = cluster.get('slug') or 'case'
1888 return f'{_SITE}/opinion/{cluster["id"]}/{slug}/'
1889 return None
1892def _write_buffered_opinions(
1893 buffer: dict[int, list[dict[str, Any]]],
1894 paths: Mapping[int, pathlib.Path]) -> None:
1895 """Writes buffered opinions to their cases and empties the buffer.
1897 Args:
1898 buffer: opinions that have not been written yet, by the cluster id of
1899 their case. It is emptied.
1900 paths: the path of each saved case, by its cluster id.
1902 """
1903 for cluster_id, opinions in buffer.items():
1904 add_opinions(paths[cluster_id], opinions)
1905 buffer.clear()