Coverage for src/courtpy/wrangler/parsers.py: 93%
210 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"""Turns saved court opinions into a table, one row for each case.
3Parsing has three stages:
51. A source (`courtpy.sources.Source`, such as CourtListener or
6 Lexis-Nexis, or one that a study adds) reads each saved case into a `Case`
7 with sections of text (such as "party", "judges", and "opinion") and
8 information that needs no parsing (such as CourtListener's date filed).
92. For Lexis-Nexis, the "lexis_nexis" rules find the sections of the header
10 (see `courtpy.lexis`). CourtListener's sections come from its data.
113. Rules find variables in the sections. The source's header rules (its
12 `header`, such as "lexis_nexis_header": the parties, their roles, and
13 the agencies among them, the court, the disposition, and the judges; see
14 `courtpy.rules.make_header_rules`) and the "general" rules (the decision,
15 procedure, and standards of review) are always applied, and then the
16 rulebooks that are named (by default, the
17 "federal" rules, which add citations, civil (with tort, contract, and
18 intellectual property), constitutional, and criminal issues, and
19 agencies; "citations", "civil", "constitutional", "criminal", and
20 "agencies" can be named alone). Each rulebook
21 has the rules of its "general" file and then those of its "federal"
22 file, if there is one (see `courtpy.rules`).
24The rulebooks are those of `amos` (`amos.parsers.Rulebook`, and courtpy's own
25in `courtpy.rules`), which search a table of the sections of many cases at
26once, a row for each case and a column for each section.
28Every section except those whose names end in "_lines" is collapsed onto one
29line between stages 2 and 3, so that phrases broken across lines are found.
31With "keep_text", the table keeps the text of every section, so that
32`parse_all` (`ParseAll`) can parse the cases again after the rules change,
33without reading the saved files again.
35Contents:
36 ParseAll: finds information in text with rules, or parses cases again
37 from their kept text with every rulebook that fits them.
38 Parser: parses cases with rulebooks.
39 find_files: returns the saved cases of a source in a folder.
40 parse: parses a folder of saved cases into a table.
41 logger: the module's logger, which reports parsing progress and cases
42 that could not be parsed.
44"""
46from __future__ import annotations
48import concurrent.futures
49import dataclasses
50import logging
51import pathlib
52from collections.abc import Iterable, Iterator, Sequence
53from typing import Any
55import amos
56import numpy as np
57import pandas as pd
59from ..core import cases, options, utilities
61# Importing the modules of the sources adds them to `base.SOURCES`.
62from ..sources import base, courtlistener, lexis # noqa: F401
64# Importing `rules` adds courtpy's rulebooks to the `amos` library, so that
65# rulebooks can be named (such as "federal").
66from . import rules as _rules # noqa: F401
68logger = logging.getLogger(__name__)
69# Sections that are not kept with "keep_text": a Lexis-Nexis case's whole
70# text, whose parts ("header", "opinion", and the parts of the header) are.
71_NOT_KEPT: frozenset[str] = frozenset({'text'})
74@dataclasses.dataclass
75class ParseAll(amos.parsers.ParseAll):
76 """Finds information in text with rules, or parses cases again.
78 This is `amos`'s `parse_all`, which it replaces in the `amos` library:
79 given "rules", it applies them as `amos.parsers.ParseAll` does. Given
80 none, it parses the cases of a table again from the text of their
81 sections, which the table has if they were loaded with "keep_text" (such
82 as after a change to the rules). Each case is parsed with every rulebook
83 that fits it: the header rules of its source (by its "source" column;
84 see `courtpy.sources.Source`), the rules of
85 `options._REQUIRED_RULEBOOKS`, and "rulebooks" (by default, those of the
86 jurisdiction, `options._DEFAULT_JURISDICTION`). Then "author",
87 "panel_size", "concurrences", "dissents", and "word_count" are made
88 again.
90 A value that the rules find replaces the table's. Where the rules find
91 nothing, the table's value is kept, such as a CourtListener case's court
92 from CourtListener's id for it.
94 """
96 """ Required Methods """
98 def parse(
99 self,
100 data: pd.DataFrame,
101 *,
102 rules: Any = None,
103 column: str = 'text',
104 rulebooks: Any = None,
105 source: str | None = None,
106 **kwargs: Any) -> pd.DataFrame:
107 """Applies rules to the text of `data`, or parses its cases again.
109 Args:
110 data: the data to parse.
111 rules: the rules to apply (see `amos.parsers.Rulebook.create`).
112 Defaults to `None`, which parses the cases again with every
113 rulebook that fits them.
114 column: the column of text that rules with a blank `column`
115 search, if `rules` is given. Defaults to "text".
116 rulebooks: names of rulebooks (such as "federal" or "civil") or
117 paths to CSV files of rules, applied to every case after its
118 source's header rules and `options._REQUIRED_RULEBOOKS`, if
119 `rules` is not given. Defaults to `None`, which applies
120 `options._DEFAULT_JURISDICTION`.
121 source: the source of cases with no "source" column (or a blank
122 one), such as "courtlistener". Defaults to `None`, in which
123 case they get only the header rules that fit every source.
124 **kwargs: passed to `amos.parsers.ParseAll.parse` if `rules` is
125 given.
127 Returns:
128 The data, with the columns that the rules make.
130 """
131 if rules is not None:
132 return super().parse(data, rules = rules, column = column, **kwargs)
133 return self._parse_again(data, rulebooks, source)
135 """ Private Methods """
137 def _parse_again(
138 self,
139 data: pd.DataFrame,
140 rulebooks: Any,
141 source: str | None) -> pd.DataFrame:
142 """Parses the cases of a table again from their sections' text.
144 Args:
145 data: the cases, with the text of their sections.
146 rulebooks: the rulebooks applied after the header rules and
147 `options._REQUIRED_RULEBOOKS`, or `None` for
148 `options._DEFAULT_JURISDICTION`.
149 source: the source of cases with no "source", or `None`.
151 Raises:
152 ValueError: if the cases have no "opinion" column, as when they
153 were not loaded with "keep_text".
155 Returns:
156 The cases, with what the rules find and the columns that
157 summarize them.
159 """
160 if 'opinion' not in data.columns:
161 message = (
162 "parse_all needs the text of the cases' sections: load them "
163 'with "keep_text" (or pass "rules")')
164 raise ValueError(message)
165 named = (
166 utilities.listify(rulebooks) if rulebooks
167 else [options._DEFAULT_JURISDICTION])
168 sources = (
169 data['source'].astype('string').fillna(source or '')
170 if 'source' in data.columns
171 else pd.Series(source or '', index = data.index, dtype = 'string'))
172 found: list[pd.DataFrame] = []
173 for name, rows in sources.groupby(sources, sort = False).groups.items():
174 known = base.SOURCES.get(str(name))
175 header = known.header if known is not None else base.Source.header
176 rulebook = amos.parsers.Rulebook.create(
177 header, *options._REQUIRED_RULEBOOKS, *named)
178 texts = [c for c in rulebook.columns if c in data.columns]
179 sections = data.loc[rows, texts].astype('str')
180 _, made = _apply(rulebook, sections)
181 found.append(made)
182 if not found: 182 ↛ 183line 182 didn't jump to line 183 because the condition on line 182 was never true
183 return data
184 made = pd.concat(found).reindex(data.index)
185 # The columns are made all at once, since adding hundreds of columns
186 # one at a time fragments the table.
187 updated = pd.DataFrame({
188 name: (
189 made[name].combine_first(data[name]) if name in data.columns
190 else made[name])
191 for name in made.columns}, index = data.index)
192 order = [
193 *data.columns, *(c for c in updated.columns if c not in data)]
194 data = pd.concat(
195 [data.drop(columns = updated.columns, errors = 'ignore'), updated],
196 axis = 1)[order]
197 return cases.tidy(_derive(data, data))
201@dataclasses.dataclass
202class Parser:
203 """Parses cases with rulebooks.
205 Args:
206 rulebook: the rules of the jurisdiction, applied to every case after
207 its source's header rules.
208 source_rules: the rulebooks of the sources (those that find the
209 sections of their cases and those of their headers), by name.
210 Defaults to an empty `dict`, in which case they are loaded when
211 first needed.
212 keep_text: whether to keep the text of every section of each case
213 (such as "party", "history", "judges", and "opinion") in the
214 table, except a Lexis-Nexis case's whole "text", whose parts are
215 kept instead. Defaults to `False`.
217 """
219 rulebook: amos.parsers.Rulebook
220 source_rules: dict[str, amos.parsers.Rulebook] = dataclasses.field(
221 default_factory = dict)
222 keep_text: bool = False
224 """ Class Methods """
226 @classmethod
227 def create(
228 cls,
229 rulebooks: str | pathlib.Path | Sequence[str | pathlib.Path] = (
230 options._DEFAULT_JURISDICTION),
231 *,
232 keep_text: bool = False) -> Parser:
233 """Returns a parser with the rules in `rulebooks`.
235 The rules of `options._REQUIRED_RULEBOOKS` are always applied first
236 (after the header rules of each case's source), whether or not they
237 are named.
239 Args:
240 rulebooks: names of rulebooks (such as "federal" or "civil") or
241 paths to CSV files or folders of them, applied in order.
242 Defaults to `options._DEFAULT_JURISDICTION`.
243 keep_text: whether to keep the text of the cases' sections in the
244 table. Defaults to `False`.
246 Raises:
247 FileNotFoundError: if a rulebook is not the name of one, a CSV
248 file, or a folder with CSV files.
249 ValueError: if a file is missing a column or a row is not a valid
250 rule. The message names the file and row.
252 Returns:
253 The parser.
255 """
256 if isinstance(rulebooks, str):
257 rulebooks = utilities.listify(rulebooks)
258 elif isinstance(rulebooks, pathlib.Path): 258 ↛ 259line 258 didn't jump to line 259 because the condition on line 258 was never true
259 rulebooks = [rulebooks]
260 rulebook = amos.parsers.Rulebook.create(
261 *options._REQUIRED_RULEBOOKS, *rulebooks)
262 return cls(rulebook = rulebook, keep_text = keep_text)
264 """ Public Methods """
266 def parse(self, case: cases.Case) -> dict[str, Any]:
267 """Returns one row of the table for `case`.
269 Args:
270 case: the case to parse.
272 Returns:
273 The case's variables, by the names of their columns, with `None`
274 for those that are missing (see `parse_cases`).
276 """
277 row = self.parse_cases([case]).iloc[0].to_dict()
278 return {
279 str(k): None if _is_missing(v) else v for k, v in row.items()}
281 def parse_cases(self, found: Sequence[cases.Case]) -> pd.DataFrame:
282 """Returns a table of `found`, with a row for each case.
284 The cases of each source are parsed together, with every rule
285 searching every case at once.
287 Args:
288 found: the cases to parse.
290 Returns:
291 The table, with a row for each case, in order, labeled 0, 1, 2,
292 and so on. Information from a case's `metadata` comes first
293 and is used instead of any variable of the same name that the
294 rules find (unless it is missing).
296 """
297 groups: dict[str, list[int]] = {}
298 for position, case in enumerate(found):
299 groups.setdefault(case.source, []).append(position)
300 tables = [
301 self._parse_source([found[p] for p in positions]).set_axis(
302 positions)
303 for positions in groups.values()]
304 if not tables: 304 ↛ 305line 304 didn't jump to line 305 because the condition on line 304 was never true
305 return pd.DataFrame()
306 return pd.concat(tables).sort_index() if len(tables) > 1 else tables[0]
308 def parse_file(
309 self,
310 path: pathlib.Path,
311 source: str) -> tuple[str, dict[str, Any]]:
312 """Reads and parses one saved case.
314 Args:
315 path: path of the saved case.
316 source: the name of its source, such as "courtlistener".
318 Returns:
319 The case's id and its row of the table.
321 """
322 case = base.find_source(source).read(path)
323 return case.id, self.parse(case)
325 """ Private Methods """
327 def _parse_source(self, group: Sequence[cases.Case]) -> pd.DataFrame:
328 """Returns a table of cases that all come from one source.
330 Args:
331 group: the cases.
333 Returns:
334 The table, with a row for each case, labeled 0, 1, 2, and so on.
336 """
337 known = base.SOURCES.get(group[0].source)
338 source = known() if known is not None else None
339 sections = pd.DataFrame(
340 [case.sections for case in group],
341 index = pd.RangeIndex(len(group))).astype('str')
342 found = pd.DataFrame(index = sections.index)
343 if source is not None and source.structure:
344 sections, found = _apply(
345 self._source_rulebook(source.structure), sections)
346 for column in sections.columns:
347 if not str(column).endswith('_lines'):
348 sections[column] = sections[column].str.replace(
349 r'\s+', ' ', regex = True).str.strip()
350 header = source.header if source is not None else base.Source.header
351 for rulebook in (self._source_rulebook(header), self.rulebook):
352 sections, made = _apply(rulebook, sections)
353 found = pd.concat(
354 [found.drop(columns = made.columns, errors = 'ignore'), made],
355 axis = 1)
356 table = pd.DataFrame(
357 [case.metadata for case in group], index = sections.index)
358 shared = [c for c in found.columns if c in table.columns]
359 for column in shared:
360 table[column] = table[column].combine_first(found[column])
361 table = pd.concat([table, found.drop(columns = shared)], axis = 1)
362 # Only a source that adds columns needs its rows one at a time.
363 if source is not None and (
364 type(source).finish is not base.Source.finish):
365 rows = [
366 {str(k): None if _is_missing(v) else v for k, v in row.items()}
367 for row in table.to_dict('records')]
368 for row in rows:
369 source.finish(row)
370 table = pd.DataFrame(rows, index = table.index)
371 table = _derive(table, sections)
372 table = table.drop(columns = [
373 c for c in table.columns
374 if c in options._LARGE_SECTIONS or str(c).endswith('_lines')])
375 if self.keep_text:
376 kept = [
377 c for c in sections.columns
378 if c not in table.columns and c not in _NOT_KEPT]
379 table = pd.concat([table, sections[kept]], axis = 1)
380 return table
382 def _source_rulebook(self, name: str) -> amos.parsers.Rulebook:
383 """Returns a rulebook of a source.
385 The rulebook is loaded the first time it is needed and kept in
386 `source_rules`, so its CSV files are read only once.
388 Args:
389 name: the name of a rulebook or the path to a CSV file (a
390 `Source`'s `structure` or `header`, such as "lexis_nexis" or
391 "lexis_nexis_header").
393 Returns:
394 The rulebook.
396 """
397 if name not in self.source_rules:
398 self.source_rules[name] = amos.parsers.Rulebook.create(name)
399 return self.source_rules[name]
402def find_files(
403 folder: pathlib.Path | str,
404 source: str = 'courtlistener') -> list[pathlib.Path]:
405 """Returns the saved cases of a source in a folder and its subfolders.
407 Args:
408 folder: the folder.
409 source: the name of the source (see `courtpy.sources.SOURCES`).
410 Defaults to "courtlistener".
412 Raises:
413 ValueError: if there is no source named `source`.
415 Returns:
416 The paths, sorted. Files in hidden folders (such as ".courtpy", where
417 downloads keep their place) are left out.
419 """
420 return base.find_source(source).find_files(folder)
423def parse(
424 files: pathlib.Path | str | Iterable[pathlib.Path | str],
425 source: str = 'courtlistener',
426 rulebooks: str | pathlib.Path | Sequence[str | pathlib.Path] = (
427 options._DEFAULT_JURISDICTION),
428 *,
429 keep_text: bool = False,
430 limit: int | None = None,
431 workers: int = 1) -> pd.DataFrame:
432 """Parses saved cases into a table, one row for each case.
434 Columns with several values in a case (such as "panel_judges" and
435 "citations_case") are text, with "; " between the values. The
436 `split_values` technique (`coders.SplitValues`) turns them into lists or
437 into a column for each value.
439 Args:
440 files: a folder of saved cases (searched with its subfolders), or the
441 paths of saved cases.
442 source: the name of the source the cases came from, such as
443 "courtlistener" (the default) or "lexis_nexis" (see
444 `courtpy.sources.SOURCES`).
445 rulebooks: names of rulebooks (such as "federal") or paths to CSV
446 files or folders of them. Defaults to
447 `options._DEFAULT_JURISDICTION`.
448 keep_text: whether to keep the text of the cases' sections in the
449 table (see `ParseAll`). Defaults to `False`.
450 limit: most cases to parse, for trying out rules. Defaults to `None`
451 (every case).
452 workers: number of processes to parse with. Defaults to 1.
454 Raises:
455 ValueError: if there is no source named `source`.
457 Returns:
458 The table, labeled by each case's id ("case_id"). A case that cannot
459 be read is left out, with a warning.
461 """
462 reader = base.find_source(source)
463 if isinstance(files, str | pathlib.Path):
464 paths = reader.find_files(files)
465 else:
466 paths = [pathlib.Path(p) for p in files]
467 if limit is not None:
468 paths = paths[:limit]
469 parser = Parser.create(rulebooks, keep_text = keep_text)
470 labels: list[str] = []
471 tables: list[pd.DataFrame] = []
472 failures = 0
473 outcomes: list[Any] = []
474 for chunk_outcomes, table in _parse_all(parser, paths, reader, workers):
475 outcomes.extend(chunk_outcomes)
476 tables.append(table)
477 taken: set[str] = set()
478 for path, outcome in zip(paths, outcomes, strict = True):
479 if isinstance(outcome, BaseException):
480 failures += 1
481 logger.warning('%s could not be parsed: %s', path, outcome)
482 continue
483 unique, number = outcome, 1
484 while unique in taken: 484 ↛ 485line 484 didn't jump to line 485 because the condition on line 484 was never true
485 number += 1
486 unique = f'{outcome}_{number}'
487 taken.add(unique)
488 labels.append(unique)
489 logger.info(
490 'parsed %d cases (%d could not be parsed)', len(labels), failures)
491 tables = [t for t in tables if not t.empty]
492 data = pd.concat(tables, ignore_index = True) if tables else pd.DataFrame()
493 data.index = pd.Index(labels, name = 'case_id')
494 return cases.tidy(data)
497""" Private Functions """
500def _apply(
501 rulebook: amos.parsers.Rulebook,
502 sections: pd.DataFrame) -> tuple[pd.DataFrame, pd.DataFrame]:
503 """Applies a rulebook to a table of sections of text.
505 A section that the rules search but no case has is added as missing
506 text, so that its rules find nothing rather than raising an error.
508 Args:
509 rulebook: the rules.
510 sections: the sections of each case, a column for each.
512 Returns:
513 The sections with every column that the rules made or changed, and
514 a table of the columns that the rules made.
516 """
517 missing = [c for c in rulebook.columns if c not in sections.columns]
518 if missing:
519 blank = pd.DataFrame(
520 {c: pd.Series(None, index = sections.index, dtype = 'str')
521 for c in missing})
522 sections = pd.concat([sections, blank], axis = 1)
523 result = rulebook.apply(sections)
524 names = set(rulebook.names)
525 made = [
526 c for c in result.columns if c not in sections.columns or c in names]
527 return result, result[made]
530def _count(table: pd.DataFrame, column: str) -> pd.Series:
531 """Returns the number of values in each row of a column of `table`.
533 Args:
534 table: parsed cases.
535 column: a column with several values in each row: lists, or text
536 with `cases._SEPARATOR` between them.
538 Returns:
539 The number of values in each row (0 if the column is missing).
541 """
542 if column not in table.columns:
543 return pd.Series(0, index = table.index, dtype = 'int64')
544 return table[column].map(
545 lambda v: len(v) if isinstance(v, list | tuple)
546 else 0 if _is_missing(v) or not str(v)
547 else len(str(v).split(cases._SEPARATOR))).astype('int64')
550def _derive(table: pd.DataFrame, sections: pd.DataFrame) -> pd.DataFrame:
551 """Adds columns that summarize others to a table of parsed cases.
553 The columns are "author" (the first of "authors", unless the case's
554 metadata already gave one), "panel_size" (the number of judges named, or
555 of CourtListener's panel ids if there are more of them), "concurrences"
556 and "dissents" (the number of judges who concurred or dissented), and
557 "word_count" (the number of words in the opinions). They are added all
558 at once, since inserting columns one at a time into a table of hundreds
559 of columns fragments it.
561 Args:
562 table: parsed cases.
563 sections: their sections of text, after the rules were applied.
565 Returns:
566 The table, with the new columns.
568 """
569 if 'authors' in table.columns: 569 ↛ 574line 569 didn't jump to line 574 because the condition on line 569 was always true
570 first = table['authors'].map(
571 lambda v: None if _is_missing(v) or not str(v)
572 else str(v).split(cases._SEPARATOR)[0])
573 else:
574 first = pd.Series(None, index = table.index, dtype = object)
575 if 'author' in table.columns:
576 first = table['author'].combine_first(first)
577 if 'opinion' in sections.columns: 577 ↛ 580line 577 didn't jump to line 580 because the condition on line 577 was always true
578 words = sections['opinion'].str.count(r'\S+').fillna(0).astype('int64')
579 else:
580 words = pd.Series(0, index = table.index, dtype = 'int64')
581 derived = pd.DataFrame({
582 'author': first,
583 'panel_size': np.maximum(
584 _count(table, 'panel_judges'), _count(table, 'panel_ids')),
585 'concurrences': _count(table, 'concurring'),
586 'dissents': _count(table, 'dissenting'),
587 'word_count': words}, index = table.index)
588 kept = table.drop(columns = [c for c in derived if c in table.columns])
589 return pd.concat([kept, derived], axis = 1)
592def _is_missing(value: Any) -> bool:
593 """Returns whether a value of a table is missing.
595 Args:
596 value: a value, which may be a list.
598 Returns:
599 Whether it is `None` or another missing value (such as `NaN`). A
600 list is never missing.
602 """
603 return not isinstance(value, list | tuple | dict) and bool(pd.isna(value))
606def _parse_all(
607 parser: Parser,
608 paths: Sequence[pathlib.Path],
609 source: base.Source,
610 workers: int) -> list[tuple[list[Any], pd.DataFrame]]:
611 """Parses each saved case, in one process or several.
613 The cases are split into chunks of `options._CHUNK_SIZE`, and progress is
614 logged after each chunk. With one worker (or one chunk), the chunks are
615 parsed in this process. Otherwise, each chunk is a task for a pool of
616 `workers` processes, since a task for each case overwhelms the pool when
617 there are hundreds of thousands of them.
619 Args:
620 parser: the parser to use. It is copied to each process with each
621 chunk.
622 paths: the paths of the saved cases.
623 source: their source. It is copied to each process with each
624 chunk, which imports the module that defines it.
625 workers: number of processes to parse with.
627 Returns:
628 The outcomes and table of each chunk, in order (see `_parse_chunk`).
630 """
631 size = max(options._CHUNK_SIZE, 1)
632 chunks = [paths[start:start + size] for start in range(0, len(paths), size)]
633 results: list[tuple[list[Any], pd.DataFrame]] = []
634 done = 0
635 for outcomes, table in _parse_chunks(parser, chunks, source, workers):
636 results.append((outcomes, table))
637 done += len(outcomes)
638 logger.info('%d of %d cases parsed', done, len(paths))
639 return results
642def _parse_chunk(
643 parser: Parser,
644 paths: Sequence[pathlib.Path],
645 source: base.Source) -> tuple[list[Any], pd.DataFrame]:
646 """Reads a chunk of saved cases and parses them together.
648 A case that cannot be read does not stop the others: the error takes the
649 place of the case's outcome. If parsing the cases fails, that error takes
650 the place of every case's outcome.
652 Args:
653 parser: the parser to use.
654 paths: the paths of the saved cases.
655 source: their source.
657 Returns:
658 For each path, in order, the case's id or the error that reading or
659 parsing it raised, and a table with a row for each case that was
660 parsed, in order.
662 """
663 outcomes: list[Any] = []
664 read: list[cases.Case] = []
665 for path in paths:
666 try:
667 case = source.read(path)
668 except Exception as error: # noqa: BLE001
669 outcomes.append(error)
670 continue
671 read.append(case)
672 outcomes.append(case.id)
673 try:
674 table = parser.parse_cases(read)
675 except Exception as error: # noqa: BLE001
676 failed = [
677 o if isinstance(o, BaseException) else error for o in outcomes]
678 return failed, pd.DataFrame()
679 return outcomes, table
682def _parse_chunks(
683 parser: Parser,
684 chunks: Sequence[Sequence[pathlib.Path]],
685 source: base.Source,
686 workers: int) -> Iterator[tuple[list[Any], pd.DataFrame]]:
687 """Parses chunks of saved cases, in one process or several.
689 If a process fails on a chunk as a whole (for instance, because it
690 stopped), that error takes the place of each of the chunk's outcomes.
692 Args:
693 parser: the parser to use. It is copied to each process with each
694 chunk.
695 chunks: the paths of the saved cases, in chunks.
696 source: their source. It is copied to each process with each
697 chunk, which imports the module that defines it.
698 workers: number of processes to parse with.
700 Yields:
701 tuple[list[Any], pd.DataFrame]: the outcomes and table of each chunk
702 (see `_parse_chunk`), in order.
704 """
705 if workers <= 1 or len(chunks) <= 1:
706 for chunk in chunks:
707 yield _parse_chunk(parser, chunk, source)
708 return
709 with concurrent.futures.ProcessPoolExecutor(max_workers = workers) as pool:
710 futures = [
711 pool.submit(_parse_chunk, parser, chunk, source)
712 for chunk in chunks]
713 for chunk, future in zip(chunks, futures, strict = True):
714 try:
715 yield future.result()
716 except Exception as error: # noqa: BLE001
717 yield [error] * len(chunk), pd.DataFrame()