Coverage for src/courtpy/cli.py: 90%

151 statements  

« prev     ^ index     » next       coverage.py v7.16.2, created at 2026-11-22 15:51 +0000

1"""Command line interface for courtpy. 

2 

3Run `courtpy --help` (or `courtpy {command} --help`) in a terminal for help. 

4 

5| Command | Does | 

6| --- | --- | 

7| `courtpy key set` | Stores your CourtListener API key outside of any project. | 

8| `courtpy key show` | Shows where your key is found (with most of it hidden). | 

9| `courtpy key delete` | Removes your stored key. | 

10| `courtpy download` | Downloads cases from CourtListener's bulk data (no key needed), or with its API ("--method api", a key is needed). | 

11| `courtpy split` | Divides Lexis-Nexis files of many cases into one file per case. | 

12| `courtpy parse` | Parses saved cases into a table (a CSV or parquet file). | 

13| `courtpy rules` | Checks a rulebook and lists the variables it makes. | 

14| `courtpy judges` | Makes and saves the roster of judges from the Federal Judicial Center's files. | 

15| `courtpy run` | Collects, parses, and analyzes cases as a settings file describes. | 

16 

17Each command is a private function that takes the parsed arguments and 

18returns the program's exit code (0 for success). `_parser` connects each 

19command's name to its function. 

20 

21A study built on courtpy can have a program of its own with courtpy's 

22commands and its own, by passing a function that adds them to `main`: 

23 

24```python 

25def main(argv: Sequence[str] | None = None) -> int: 

26 return courtpy.cli.main( 

27 argv, prog = 'my-study', add_commands = _add_commands) 

28 

29 

30def _add_commands(commands: Any) -> None: 

31 scores = commands.add_parser('scores', help = 'score the judges') 

32 scores.add_argument('votes') 

33 scores.set_defaults(command = _scores) 

34 # The study's own rules for the judges' careers. 

35 commands.choices['judges'].set_defaults(rulebook = CAREERS) 

36``` 

37 

38Contents: 

39 main: runs a command. 

40 

41""" 

42 

43from __future__ import annotations 

44 

45import argparse 

46import getpass 

47import logging 

48import pathlib 

49import sys 

50from collections.abc import Callable, Sequence 

51from typing import Any 

52 

53import amos 

54import requests 

55 

56from . import __version__ 

57from .core import datasets, options, secrets 

58from .references import judges 

59 

60# Importing the modules of the sources adds them to `base.SOURCES`. 

61from .sources import base, courtlistener, lexis 

62from .wrangler import coders, parsers 

63 

64 

65def main( 

66 argv: Sequence[str] | None = None, 

67 *, 

68 prog: str = 'courtpy', 

69 description: str | None = None, 

70 add_commands: Callable[[Any], None] | None = None) -> int: 

71 """Runs a courtpy command, or a command that a study adds. 

72 

73 Messages about progress are shown unless "--quiet" is passed. Errors that 

74 a user can fix (such as a missing API key, a misspelled file, an invalid 

75 rule, or a failed download) are shown as one line instead of a 

76 traceback. 

77 

78 Args: 

79 argv: the command's arguments. Defaults to `None`, in which case the 

80 arguments of the program are used. 

81 prog: the name of the program, for help and error messages. Defaults 

82 to "courtpy". 

83 description: what the program does, for its help. Defaults to 

84 `None`, which describes courtpy. 

85 add_commands: a function that adds commands to the program's 

86 subparsers (an `argparse` "subparsers" object, whose `choices` 

87 has courtpy's commands by name). Each command's "command" default 

88 is the function that runs it, which takes the parsed arguments 

89 and returns the exit code. Defaults to `None`, which adds none. 

90 

91 Returns: 

92 0 if the command succeeded, and 1 if it failed. 

93 

94 """ 

95 parser = _parser( 

96 prog = prog, description = description, add_commands = add_commands) 

97 arguments = parser.parse_args(argv) 

98 logging.basicConfig( 

99 level = logging.WARNING if arguments.quiet else logging.INFO, 

100 format = '%(levelname)s: %(message)s') 

101 try: 

102 return int(arguments.command(arguments) or 0) 

103 except ( 

104 courtlistener.CourtListenerError, 

105 secrets.MissingAPIKeyError, 

106 LookupError, 

107 OSError, 

108 ValueError, 

109 requests.RequestException) as error: 

110 print(f'{prog}: {error}', file = sys.stderr) 

111 return 1 

112 

113 

114""" Commands """ 

115 

116 

117def _download(arguments: argparse.Namespace) -> int: 

118 """Downloads cases from CourtListener ("courtpy download"). 

119 

120 The cases are downloaded with `courtlistener.CourtListener.download`: 

121 from the bulk data (the default, which needs no key) or with the API 

122 ("--method api", which needs a key). 

123 

124 Args: 

125 arguments: the parsed arguments: "method", "courts", "start", "end", 

126 "folder", "max_cases", "refresh", "dockets", "bulk_folder", 

127 "bulk_date", and "stream". 

128 

129 Returns: 

130 0. 

131 

132 """ 

133 folder = pathlib.Path(arguments.folder) 

134 client = courtlistener.CourtListener( 

135 bulk_folder = arguments.bulk_folder, 

136 bulk_date = arguments.bulk_date, 

137 stream = arguments.stream) 

138 saved = client.download( 

139 arguments.courts or [], 

140 arguments.start, 

141 arguments.end, 

142 folder, 

143 method = arguments.method, 

144 max_cases = arguments.max_cases, 

145 dockets = arguments.dockets, 

146 refresh = arguments.refresh) 

147 print(f'{len(saved)} cases saved in {folder}') 

148 return 0 

149 

150 

151def _judges(arguments: argparse.Namespace) -> int: 

152 """Makes and saves the roster of judges ("courtpy judges"). 

153 

154 The roster is made from the Federal Judicial Center's files (see 

155 `judges.Roster.from_fjc`), which are downloaded first if they are not 

156 there, and saved where the techniques look for it unless "--output" 

157 names another file. 

158 

159 Args: 

160 arguments: the parsed arguments: "update" (whether to download the 

161 files again), "no_jcs", "martin_quinn", "rulebook" (the rules of 

162 the judges' careers), and "output". 

163 

164 Returns: 

165 0. 

166 

167 """ 

168 roster = judges.Roster.from_fjc( 

169 update = arguments.update, 

170 jcs = not arguments.no_jcs, 

171 martin_quinn = arguments.martin_quinn, 

172 rulebook = arguments.rulebook) 

173 path = roster.save(arguments.output) 

174 people = roster.data['nid'].nunique() 

175 print(f'A roster of {people} judges was saved to {path}') 

176 return 0 

177 

178 

179def _key_delete(arguments: argparse.Namespace) -> int: # noqa: ARG001 

180 """Removes the stored API key ("courtpy key delete"). 

181 

182 The key is removed from the keyring and the secrets file. If a key is 

183 still found elsewhere (in an environment variable or a `.env` file, which 

184 courtpy does not change), where it is found is shown. 

185 

186 Args: 

187 arguments: the parsed arguments, which this command does not use. 

188 

189 Returns: 

190 0. 

191 

192 """ 

193 removed = secrets.delete_api_key() 

194 if removed: 194 ↛ 197line 194 didn't jump to line 197 because the condition on line 194 was always true

195 print('Removed the API key from ' + ' and '.join(removed)) 

196 else: 

197 print('No stored API key was found.') 

198 found = secrets.find_api_key() 

199 if found is not None: 199 ↛ 200line 199 didn't jump to line 200 because the condition on line 199 was never true

200 print( 

201 f'A key is still found in {found[1]}, which courtpy does not ' 

202 f'change.') 

203 return 0 

204 

205 

206def _key_set(arguments: argparse.Namespace) -> int: 

207 """Stores the API key ("courtpy key set"). 

208 

209 The key is asked for without being shown as it is typed, or read from 

210 standard input with "--stdin" (for scripts). 

211 

212 Args: 

213 arguments: the parsed arguments: "store" (where to store the key) and 

214 "stdin" (whether to read it from standard input). 

215 

216 Returns: 

217 0. 

218 

219 """ 

220 if arguments.stdin: 220 ↛ 223line 220 didn't jump to line 223 because the condition on line 220 was always true

221 key = sys.stdin.readline() 

222 else: 

223 key = getpass.getpass('CourtListener API key (it will not be shown): ') 

224 place = secrets.set_api_key(key, store = arguments.store) 

225 print(f'Stored the API key in {place}.') 

226 return 0 

227 

228 

229def _key_show(arguments: argparse.Namespace) -> int: # noqa: ARG001 

230 """Shows where the API key is found, with most of it hidden. 

231 

232 This is "courtpy key show". It also shows the path of the secrets file. 

233 

234 Args: 

235 arguments: the parsed arguments, which this command does not use. 

236 

237 Returns: 

238 0 if a key was found, and 1 (with an explanation of how to store one) 

239 if not. 

240 

241 """ 

242 found = secrets.find_api_key() 

243 if found is None: 

244 print(secrets.MissingAPIKeyError()) 

245 return 1 

246 key, place = found 

247 print(f'API key {secrets.mask(key)} found in {place}.') 

248 print(f'(The secrets file is {secrets.secrets_path()}.)') 

249 return 0 

250 

251 

252def _parse(arguments: argparse.Namespace) -> int: 

253 """Parses saved cases into a table ("courtpy parse"). 

254 

255 Unless "--no-code" is passed, the default coders are applied (see 

256 `coders.code`) before the table is saved. 

257 

258 Args: 

259 arguments: the parsed arguments: "folder", "source", "rulebooks", 

260 "keep_text", "limit", "workers", "no_code", and "output". 

261 

262 Returns: 

263 0 if cases were parsed, and 1 if the folder had none. 

264 

265 """ 

266 data = parsers.parse( 

267 arguments.folder, 

268 source = arguments.source, 

269 rulebooks = arguments.rulebooks or options._DEFAULT_JURISDICTION, 

270 keep_text = arguments.keep_text, 

271 limit = arguments.limit, 

272 workers = arguments.workers) 

273 if data.empty: 273 ↛ 274line 273 didn't jump to line 274 because the condition on line 273 was never true

274 print(f'courtpy: no {arguments.source} cases in {arguments.folder}', 

275 file = sys.stderr) 

276 return 1 

277 dataset = datasets.Cases.create( 

278 data if arguments.no_code else coders.code(data)) 

279 path = pathlib.Path(arguments.output) 

280 dataset.save(path) 

281 print(f'{len(dataset.data)} cases parsed into {path}') 

282 return 0 

283 

284 

285def _rules(arguments: argparse.Namespace) -> int: 

286 """Checks a rulebook and lists the variables it makes ("courtpy rules"). 

287 

288 An invalid rule raises a `ValueError` naming its file and row, which 

289 `main` shows. 

290 

291 Args: 

292 arguments: the parsed arguments: "rulebooks" (names of built-in 

293 rulebooks or paths to CSV files). 

294 

295 Returns: 

296 0. 

297 

298 """ 

299 rulebook = amos.parsers.Rulebook.create(*arguments.rulebooks) 

300 print(f'{len(rulebook)} rules are valid ({rulebook.name}).') 

301 print(f'They search: {", ".join(rulebook.columns)}') 

302 print(f'They make {len(rulebook.names)} columns:') 

303 for name in rulebook.names: 

304 print(f' {name}') 

305 return 0 

306 

307 

308def _run(arguments: argparse.Namespace) -> int: 

309 """Collects, parses, and analyzes cases as a settings file describes. 

310 

311 This is "courtpy run". The project's report is shown, and its results are 

312 exported if "--export" is passed (see `amos.Project.export`). 

313 

314 Args: 

315 arguments: the parsed arguments: "settings" (the path to a settings 

316 file) and "export". 

317 

318 Returns: 

319 0. 

320 

321 """ 

322 project = amos.Project.create(arguments.settings) 

323 print(project.report.contents if project.report else project.result) 

324 if arguments.export: 

325 folder = project.export() 

326 print(f'Results exported to {folder}') 

327 return 0 

328 

329 

330def _split(arguments: argparse.Namespace) -> int: 

331 """Divides Lexis-Nexis files of many cases ("courtpy split"). 

332 

333 Args: 

334 arguments: the parsed arguments: "files" (text files, or folders whose 

335 ".txt" files are used) and "folder" (where to save the cases). 

336 

337 Returns: 

338 0. 

339 

340 """ 

341 files = [pathlib.Path(f) for f in arguments.files] 

342 expanded = [ 

343 p for f in files for p in (sorted(f.glob('*.txt')) 

344 if f.is_dir() else [f])] 

345 saved = lexis.split(expanded, arguments.folder) 

346 print(f'{len(saved)} cases saved in {arguments.folder}') 

347 return 0 

348 

349 

350""" Private Functions """ 

351 

352 

353def _parser( 

354 *, 

355 prog: str = 'courtpy', 

356 description: str | None = None, 

357 add_commands: Callable[[Any], None] | None = None) -> ( 

358 argparse.ArgumentParser): 

359 """Returns the parser of the command line arguments. 

360 

361 Each command is a subparser whose "command" default is the function that 

362 runs it, which `main` calls with the parsed arguments. 

363 

364 Args: 

365 prog: the name of the program. Defaults to "courtpy". 

366 description: what the program does. Defaults to `None`, which 

367 describes courtpy. 

368 add_commands: a function that adds commands to the subparsers, after 

369 courtpy's. Defaults to `None`. 

370 

371 Returns: 

372 The parser, with the options shared by every command ("--version" 

373 and "--quiet") and a subparser for each command. 

374 

375 """ 

376 parser = argparse.ArgumentParser( 

377 prog = prog, 

378 description = ( 

379 description or 'Collect, parse, and analyze court opinions.')) 

380 parser.add_argument('--version', action = 'version', version = __version__) 

381 parser.add_argument( 

382 '-q', '--quiet', action = 'store_true', help = 'show only warnings') 

383 commands = parser.add_subparsers(title = 'commands', required = True) 

384 

385 key = commands.add_parser('key', help = 'manage the CourtListener API key') 

386 key_commands = key.add_subparsers(title = 'key commands', required = True) 

387 key_set = key_commands.add_parser('set', help = 'store the API key') 

388 key_set.add_argument( 

389 '--store', choices = ['auto', 'keyring', 'file'], default = 'auto', 

390 help = 'where to store it (default: the keyring, if there is one)') 

391 key_set.add_argument( 

392 '--stdin', action = 'store_true', 

393 help = 'read the key from standard input instead of asking') 

394 key_set.set_defaults(command = _key_set) 

395 key_commands.add_parser( 

396 'show', help = 'show where the key is found').set_defaults( 

397 command = _key_show) 

398 key_commands.add_parser( 

399 'delete', help = 'remove the stored key').set_defaults( 

400 command = _key_delete) 

401 

402 download = commands.add_parser( 

403 'download', help = 'download cases from CourtListener') 

404 download.add_argument( 

405 '--method', choices = courtlistener.DOWNLOAD_METHODS, default = 'bulk', 

406 help = ( 

407 'bulk (the default) extracts them from the bulk data (no key ' 

408 'needed); api downloads them with the API (a key is needed)')) 

409 download.add_argument( 

410 '--courts', nargs = '+', 

411 help = ( 

412 'court ids (such as ca1) or groups (such as ' 

413 'federal_geographic_circuits)')) 

414 download.add_argument('--start', help = 'earliest date filed (YYYY-MM-DD)') 

415 download.add_argument('--end', help = 'latest date filed (YYYY-MM-DD)') 

416 download.add_argument( 

417 '--folder', default = 'courtlistener', 

418 help = 'folder to save the cases in (default: courtlistener)') 

419 download.add_argument( 

420 '--max-cases', type = int, 

421 help = 'most cases to save (in each court, with the API)') 

422 download.add_argument( 

423 '--refresh', action = 'store_true', 

424 help = 'download cases that were already saved') 

425 download.add_argument( 

426 '--dockets', action = 'store_true', 

427 help = 'with the API, also download dockets (one request per case)') 

428 download.add_argument( 

429 '--bulk-folder', help = 'folder to keep the bulk files in') 

430 download.add_argument( 

431 '--bulk-date', help = 'date of the bulk files (default: newest)') 

432 download.add_argument( 

433 '--stream', action = 'store_true', 

434 help = 'read the bulk files without saving them') 

435 download.set_defaults(command = _download) 

436 

437 split = commands.add_parser( 

438 'split', help = 'divide Lexis-Nexis files of many cases') 

439 split.add_argument('files', nargs = '+', help = 'files or folders') 

440 split.add_argument( 

441 '--folder', default = 'lexis_nexis', 

442 help = 'folder to save the cases in (default: lexis_nexis)') 

443 split.set_defaults(command = _split) 

444 

445 parse = commands.add_parser( 

446 'parse', help = 'parse saved cases into a table') 

447 parse.add_argument('folder', help = 'folder of saved cases') 

448 parse.add_argument( 

449 '--source', choices = sorted(base.SOURCES), 

450 default = 'courtlistener') 

451 parse.add_argument( 

452 '--rulebooks', nargs = '+', 

453 help = ( 

454 'built-in rulebooks (such as civil) or CSV files, applied after ' 

455 "the source's header rules and general (default: federal)")) 

456 parse.add_argument( 

457 '--output', default = 'cases.csv', 

458 help = ( 

459 'file to save the table to, with the whole dataset beside it ' 

460 'in a .joblib file (default: cases.csv)')) 

461 parse.add_argument( 

462 '--keep-text', action = 'store_true', help = "keep the text of the cases' sections") 

463 parse.add_argument('--limit', type = int, help = 'most cases to parse') 

464 parse.add_argument( 

465 '--workers', type = int, default = 1, help = 'processes to parse with') 

466 parse.add_argument( 

467 '--no-code', action = 'store_true', 

468 help = 'do not code parties, case types, and outcomes') 

469 parse.set_defaults(command = _parse) 

470 

471 check = commands.add_parser( 

472 'rules', help = 'check a rulebook and list its variables') 

473 check.add_argument( 

474 'rulebooks', nargs = '+', 

475 help = ( 

476 'built-in rulebooks (such as federal, civil, or lexis_nexis) or ' 

477 'CSV files')) 

478 check.set_defaults(command = _rules) 

479 

480 run = commands.add_parser( 

481 'run', help = 'collect, parse, and analyze cases from a settings file') 

482 run.add_argument('settings', help = 'settings file (ini, toml, json, yaml)') 

483 run.add_argument( 

484 '--export', action = 'store_true', help = 'export the results') 

485 run.set_defaults(command = _run) 

486 

487 roster = commands.add_parser( 

488 'judges', 

489 help = "make the roster of judges from the Federal Judicial Center's " 

490 'files') 

491 roster.add_argument( 

492 '--update', action = 'store_true', 

493 help = "download the Federal Judicial Center's files again") 

494 roster.add_argument( 

495 '--no-jcs', action = 'store_true', 

496 help = 'leave out the Judicial Common Space scores') 

497 roster.add_argument( 

498 '--martin-quinn', action = 'store_true', 

499 help = "add the justices' Martin-Quinn scores") 

500 roster.add_argument( 

501 '--rulebook', default = 'judges', 

502 help = "rules that code the judges' careers: a CSV file or a " 

503 'rulebook of fjc-biographies (default: judges)') 

504 roster.add_argument( 

505 '--output', 

506 help = 'file to save the roster to (default: where the techniques ' 

507 'look for it)') 

508 roster.set_defaults(command = _judges) 

509 if add_commands is not None: 

510 add_commands(commands) 

511 return parser 

512 

513 

514if __name__ == '__main__': 

515 sys.exit(main())