extract-python 0.12.3__py3-none-any.whl → 0.13.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -22,15 +22,28 @@ except ModuleNotFoundError:
22
22
  MinerUPipeline = None
23
23
 
24
24
  try:
25
+ from .hybrid_liteparse_ import (
26
+ HybridLiteParsePipeline,
27
+ LiteParseLayoutReason,
28
+ LiteParseOCRReason,
29
+ )
25
30
  from .liteparse_ import LiteParsePipeline
26
31
  except ModuleNotFoundError:
27
32
  logger.warning("liteparse is not available, might be optional...")
33
+ HybridLiteParsePipeline, LiteParseLayoutReason, LiteParseOCRReason = (
34
+ None,
35
+ None,
36
+ None,
37
+ )
28
38
  LiteParsePipeline = None
29
39
 
30
40
  __all__ = [
31
41
  "DoclingPipeline",
32
42
  "DOCLING_DEFAULT_ARTIFACTS_PATH",
43
+ "HybridLiteParsePipeline",
44
+ "LiteParseLayoutReason",
45
+ "LiteParseOCRReason",
46
+ "LiteParsePipeline",
33
47
  "MarkerPipeline",
34
48
  "MinerUPipeline",
35
- "LiteParsePipeline",
36
49
  ]
@@ -28,10 +28,12 @@ from extract_core import (
28
28
  DoclingPipelineConfig,
29
29
  Error,
30
30
  InputDoc,
31
+ InputPages,
31
32
  MarkdownDoc,
32
33
  OutputFormat,
33
34
  Pipeline,
34
35
  PipelineType,
36
+ Range,
35
37
  Result,
36
38
  Status,
37
39
  )
@@ -41,7 +43,6 @@ from pydantic_core.core_schema import SerializerFunctionWrapHandler
41
43
 
42
44
  from .constants import ARTIFACTS, DEFAULT_MD_PAGE_SEP
43
45
  from .utils import (
44
- Range,
45
46
  ResultBuffer,
46
47
  batch_per_pages,
47
48
  chdir,
@@ -77,24 +78,36 @@ class DoclingPipeline(Pipeline):
77
78
  ) -> AsyncIterable[Result]:
78
79
  settings = self._config.settings
79
80
  logger.info("starting extraction with settings: %s", settings)
80
- with self._scoped_settings, self._result_buffer as buffer:
81
+ with self._scoped_settings:
81
82
  max_page_batches = settings.perf.max_page_batches
82
83
  page_batch_size = settings.perf.page_batch_size
83
- batches = batch_per_pages(
84
+ pages = batch_per_pages(
84
85
  docs, page_batch_size, max_page_batches=max_page_batches
85
86
  )
86
- for batch in batches:
87
- page_range = list({pages.page_range for pages in batch})
87
+ async for res in self.extract_pages_content(
88
+ pages, output_format, output_path
89
+ ):
90
+ yield res
91
+
92
+ async def extract_pages_content(
93
+ self,
94
+ pages: Iterable[InputPages],
95
+ output_format: OutputFormat,
96
+ output_path: Path,
97
+ ) -> AsyncIterable[Result]:
98
+ with self._result_buffer as buffer:
99
+ for input_pages in pages:
100
+ page_range = list({pages.page_range for pages in input_pages})
88
101
  if len(page_range) > 1:
89
102
  msg = "convert_all only accept 1 page range for all docs"
90
103
  raise ValueError(msg)
91
104
  page_range = page_range[0]
92
105
  page_range = _docling_range(page_range)
93
- docling_docs = (pages.doc.to_docling() for pages in batch)
106
+ docling_docs = (pages.doc.to_docling() for pages in input_pages)
94
107
  outputs = self._converter.convert_all(
95
108
  docling_docs, raises_on_error=False, page_range=page_range
96
109
  )
97
- processed = iter(batch)
110
+ processed = iter(input_pages)
98
111
  sentinel = object()
99
112
  while True:
100
113
  res = await asyncio.to_thread(next, outputs, sentinel)
@@ -0,0 +1,152 @@
1
+ import logging
2
+ from collections.abc import AsyncIterable, Iterable, Iterator
3
+ from itertools import chain, groupby
4
+ from pathlib import Path
5
+ from typing import TYPE_CHECKING, Self
6
+
7
+ from extract_core import (
8
+ HybridLiteParsePipelineConfig,
9
+ InputDoc,
10
+ InputPages,
11
+ LiteParseLayoutReason,
12
+ LiteParseOCRReason,
13
+ LiteParseRouterConfig,
14
+ OutputFormat,
15
+ Pipeline,
16
+ PipelineType,
17
+ Result,
18
+ )
19
+
20
+ from .liteparse_ import LiteParsePipeline
21
+
22
+ _IS_ADVANCED = "is_advanced"
23
+
24
+ LITEPARSE_RANGE = "liteparse_range"
25
+
26
+ logger = logging.getLogger(__name__)
27
+ if TYPE_CHECKING:
28
+ from liteparse.types import PageComplexityStats
29
+
30
+
31
+ class LiteParseRouter:
32
+ def __init__(self, config: LiteParseRouterConfig):
33
+ self._config = config
34
+
35
+ def is_advanced(self, complexity: "PageComplexityStats") -> bool:
36
+ config = self._config
37
+ if config.needs_ocr_is_advanced and complexity.needs_ocr:
38
+ return True
39
+ layout = complexity.layout
40
+ if config.complex_layout_is_advanced and layout.is_complex:
41
+ return True
42
+ if config.advanced_ocr_reasons and any(
43
+ LiteParseOCRReason(r) in config.advanced_ocr_reasons
44
+ for r in complexity.reasons
45
+ ):
46
+ return True
47
+ if config.advanced_layout_reasons and any( # noqa: SIM103
48
+ LiteParseLayoutReason(r) in config.advanced_layout_reasons
49
+ for r in layout.reasons
50
+ ):
51
+ return True
52
+ return False
53
+
54
+
55
+ @Pipeline.register(PipelineType.HYBRID_LITEPARSE)
56
+ class HybridLiteParsePipeline(Pipeline):
57
+ def __init__(
58
+ self, router: LiteParseRouter, liteparse: LiteParsePipeline, advanced: Pipeline
59
+ ):
60
+ self._router = router
61
+ self._liteparse = liteparse
62
+ self._advanced = advanced
63
+
64
+ @classmethod
65
+ def _from_config(cls, config: HybridLiteParsePipelineConfig) -> Self:
66
+ router = LiteParseRouter(config.router)
67
+ liteparse = LiteParsePipeline(config.liteparse)
68
+ advanced = Pipeline.from_config(config.advanced)
69
+ return cls(router, liteparse, advanced)
70
+
71
+ async def extract_content(
72
+ self, docs: Iterable[InputDoc], output_format: OutputFormat, output_path: Path
73
+ ) -> AsyncIterable[Result]:
74
+ complexities = await self._liteparse.compute_complexities(docs)
75
+ simple, advanced = self._route(complexities)
76
+ async for res in self.extract_pages_content(simple, output_format, output_path):
77
+ yield res
78
+ async for res in self.extract_pages_content(
79
+ advanced, output_format, output_path
80
+ ):
81
+ yield res
82
+
83
+ async def extract_pages_content(
84
+ self,
85
+ pages: Iterable[InputPages],
86
+ output_format: OutputFormat,
87
+ output_path: Path,
88
+ ) -> AsyncIterable[Result]:
89
+ pages = _ensure_same_parser(pages)
90
+ first = next(pages, None)
91
+ if first is None:
92
+ return
93
+ pages = chain((first,), pages)
94
+ is_advanced = first.metadata[_IS_ADVANCED]
95
+ pipeline = self._advanced if is_advanced else self._liteparse
96
+ async for res in pipeline.extract_pages_content(
97
+ pages, output_format, output_path
98
+ ):
99
+ yield res
100
+
101
+ def _route(
102
+ self, complexities: list[tuple[InputDoc, list["PageComplexityStats"]]]
103
+ ) -> tuple[list[InputPages], list[InputPages]]:
104
+ simple, advanced = [], []
105
+ for doc_ix, (doc, doc_complexities) in enumerate(complexities):
106
+ current_page = 0
107
+ grouped = groupby(doc_complexities, key=self._router.is_advanced)
108
+ for is_advanced, group in grouped:
109
+ group = tuple(group) # noqa: PLW2901
110
+ input_pages = _group_to_input_pages(
111
+ group, current_page, doc, doc_ix=doc_ix, is_advanced=is_advanced
112
+ )
113
+ if is_advanced:
114
+ advanced.append(input_pages)
115
+ else:
116
+ simple.append(input_pages)
117
+ current_page += input_pages.n_pages
118
+ return simple, advanced
119
+
120
+
121
+ def _group_to_input_pages(
122
+ group: tuple["PageComplexityStats", ...],
123
+ rng_start: int,
124
+ doc: InputDoc,
125
+ *,
126
+ doc_ix: int,
127
+ is_advanced: bool,
128
+ ) -> InputPages:
129
+ n_pages = len(group)
130
+ start = rng_start
131
+ end = start + n_pages
132
+ rng = (start, end)
133
+ expected_page_nums = list(range(start + 1, end + 1))
134
+ page_nums = [p.page_number for p in group]
135
+ if page_nums != expected_page_nums:
136
+ msg = (
137
+ f"inconsistent page numbers within group, expected {page_nums} found {rng}"
138
+ )
139
+ raise ValueError(msg)
140
+ meta = {_IS_ADVANCED: is_advanced}
141
+ input_pages = InputPages(doc=doc, doc_idx=doc_ix, page_range=rng, metadata=meta)
142
+ return input_pages
143
+
144
+
145
+ def _ensure_same_parser(pages: Iterable[InputPages]) -> Iterator[InputPages]:
146
+ is_advanced = None
147
+ for p in pages:
148
+ if is_advanced is None:
149
+ is_advanced = p.metadata["is_advanced"]
150
+ elif p.metadata["is_advanced"] != is_advanced:
151
+ raise ValueError("expected all pages to have the same complexities")
152
+ yield p
@@ -17,20 +17,21 @@ from extract_core import (
17
17
  ConversionOutput,
18
18
  Error,
19
19
  InputDoc,
20
+ InputPages,
20
21
  LiteParsePipelineConfig,
21
22
  OutputFormat,
22
23
  Pipeline,
23
24
  PipelineType,
25
+ Range,
24
26
  Result,
25
27
  Status,
26
28
  SupportedExt,
27
29
  )
30
+ from icij_common.pydantic_utils import safe_copy
28
31
  from pydantic import TypeAdapter
29
32
 
30
33
  from .constants import ARTIFACTS, DEFAULT_MD_PAGE_SEP
31
34
  from .utils import (
32
- ProcessedPages,
33
- Range,
34
35
  ResultBuffer,
35
36
  UsageTracker,
36
37
  _run_with_concurrency,
@@ -40,6 +41,8 @@ from .utils import (
40
41
  write_pages,
41
42
  )
42
43
 
44
+ LITEPARSE_RANGE = "liteparse_range"
45
+
43
46
  logger = logging.getLogger(__name__)
44
47
  if TYPE_CHECKING:
45
48
  import pypdfium2 as pdfium
@@ -55,8 +58,8 @@ if TYPE_CHECKING:
55
58
 
56
59
  _LITEPARSE_CONVERSION_ERRORS = tuple()
57
60
 
58
-
59
- OrientedBatch = tuple[int | None, tuple[ProcessedPages]]
61
+ Orientation = int | None
62
+ OrientedBatch = tuple[tuple[Range, Orientation] | None, tuple[InputPages, ...]]
60
63
  LiteParseOutputFormat = Literal["text", "json", "markdown"]
61
64
 
62
65
 
@@ -76,7 +79,7 @@ class LiteParsePageResult:
76
79
  dict[int, tuple["ParsedPage", list["ExtractedImage"], list["PageError"]]] | None
77
80
  ) = None
78
81
 
79
- def filter(self, page: ProcessedPages) -> Self:
82
+ def filter(self, page: InputPages) -> Self:
80
83
  if self._by_ix is None:
81
84
  self._by_ix = self._results_by_index()
82
85
  pages, images, errors = [], [], []
@@ -119,23 +122,47 @@ class LiteParsePipeline(Pipeline):
119
122
  self._tessdata_path = Path(tessdata_path)
120
123
  if self._config.detect_page_orientation:
121
124
  logger.info("reading docs page orientation detection...")
122
- batches = await self._batch_per_orientation(docs)
125
+ pages = await self._group_per_page_range_and_orientation(docs)
123
126
  else:
124
- batches = chunk_docs(docs, self._config.page_batch_size)
125
- batches = ((None, (c,)) for c in batches)
127
+ pages = chunk_docs(docs, self._config.page_batch_size)
126
128
  logger.info("parsing pages...")
127
- async for res in self._parse(batches, output_format, output_path):
129
+ async for res in self.extract_pages_content(pages, output_format, output_path):
128
130
  yield res
129
131
 
130
- async def _batch_per_orientation(
132
+ async def extract_pages_content(
133
+ self,
134
+ pages: Iterable[InputPages],
135
+ output_format: OutputFormat,
136
+ output_path: Path,
137
+ ) -> AsyncIterable[Result]:
138
+ match output_format:
139
+ case OutputFormat.MARKDOWN:
140
+ liteparse_o_fmt, postprocess_fn = "markdown", aggregate_pages_md
141
+ case _:
142
+ fmt = (
143
+ f"unsupported output format for {LiteParsePipeline.__name__}"
144
+ f" {output_format}"
145
+ )
146
+ raise NotImplementedError(fmt)
147
+ result_queue = asyncio.Queue()
148
+ # Buffer partial conversion to filesystem as large docs are chunked into pieces
149
+ with self._result_buffer() as buffer:
150
+ publisher = self._parse_publisher(pages, liteparse_o_fmt, result_queue)
151
+ consumer = self._parse_consumer(
152
+ result_queue, buffer, postprocess_fn, output_path
153
+ )
154
+ async for res in publish_and_consume(publisher, consumer=consumer):
155
+ yield res
156
+
157
+ async def _group_per_page_range_and_orientation(
131
158
  self, docs: Iterable[InputDoc]
132
- ) -> list[OrientedBatch]:
159
+ ) -> list[InputPages]:
133
160
  logger.info("computing page complexities...")
134
- complexities = await self._compute_complexities(docs)
135
- batches = [b async for b in self._batch_with_orientation(complexities)]
161
+ complexities = await self.compute_complexities(docs)
162
+ batches = [b async for b in self._groups_from_complexities(complexities)]
136
163
  return batches
137
164
 
138
- async def _compute_complexities(
165
+ async def compute_complexities(
139
166
  self, docs: Iterable[InputDoc]
140
167
  ) -> list[tuple[InputDoc, list["PageComplexityStats"]]]:
141
168
  docs = list(docs)
@@ -150,21 +177,26 @@ class LiteParsePipeline(Pipeline):
150
177
  ]
151
178
  return batches
152
179
 
153
- async def _batch_with_orientation(
180
+ async def _groups_from_complexities(
154
181
  self, complexities: list[tuple[InputDoc, list["PageComplexityStats"]]]
155
- ) -> AsyncIterable[OrientedBatch]:
182
+ ) -> AsyncIterable[InputPages]:
156
183
  batch_size = self._config.page_batch_size
157
- batches_per_orientation = defaultdict(list)
158
- not_pdfs = [doc for doc, comps in complexities if comps is None]
184
+ groups = defaultdict(list)
185
+ not_pdfs = (doc for doc, comps in complexities if comps is None)
159
186
  for doc in not_pdfs:
160
187
  for batch in chunk_docs([doc], batch_size):
161
- rng = _liteparse_range(batch.page_range)
162
- batches_per_orientation[(rng, None)].append(batch)
188
+ rng, orientation = None, None
189
+ if batch.page_range is not None:
190
+ rng = _liteparse_range(batch.page_range)
191
+ update = {"liteparse_range": rng, "orientation": orientation}
192
+ update = {"metadata": update}
193
+ batch = tuple(safe_copy(b, update) for b in batch) # noqa: PLW2901
194
+ groups[(rng, orientation)].extend(batch)
163
195
  complexities = [
164
196
  (doc, comps) for doc, comps in complexities if comps is not None
165
197
  ]
166
198
  logger.info("reading complex pages orientation...")
167
- offset = len(not_pdfs)
199
+ offset = sum(len(v) for v in groups.values())
168
200
  with self._executor() as executor:
169
201
  for doc, comps in complexities:
170
202
  pages_by_orientation = await _doc_pages_by_orientation(
@@ -174,42 +206,18 @@ class LiteParsePipeline(Pipeline):
174
206
  for batch in batched(pages, batch_size, strict=False):
175
207
  batch = _pages_from_complexities(doc, offset, *batch) # noqa: PLW2901
176
208
  rng = _liteparse_range_from_pages(*batch)
177
- batches_per_orientation[(rng, orientation)].append(batch)
209
+ update = {"liteparse_range": rng, "orientation": orientation}
210
+ update = {"metadata": update}
211
+ batch = tuple(safe_copy(b, update) for b in batch) # noqa: PLW2901
212
+ groups[(rng, orientation)].extend(batch)
178
213
  offset += 1
179
- # We yield pages per orientation only here to make sure to yield
180
- # (orientation, range) in the most regular way and avoid reload
181
- for (_, orientation), batches in batches_per_orientation.items():
182
- for batch in batches:
183
- yield orientation, batch
184
-
185
- async def _parse(
186
- self,
187
- batches: Iterable[OrientedBatch],
188
- output_format: OutputFormat,
189
- output_path: Path,
190
- ) -> AsyncIterable[Result]:
191
- match output_format:
192
- case OutputFormat.MARKDOWN:
193
- liteparse_o_fmt, postprocess_fn = "markdown", aggregate_pages_md
194
- case _:
195
- fmt = (
196
- f"unsupported output format for {LiteParsePipeline.__name__}"
197
- f" {output_format}"
198
- )
199
- raise NotImplementedError(fmt)
200
- result_queue = asyncio.Queue()
201
- # Buffer partial conversion to filesystem as large docs are chunked into pieces
202
- with self._result_buffer() as buffer:
203
- publisher = self._parse_publisher(batches, liteparse_o_fmt, result_queue)
204
- consumer = self._parse_consumer(
205
- result_queue, buffer, postprocess_fn, output_path
206
- )
207
- async for res in publish_and_consume(publisher, consumer=consumer):
208
- yield res
214
+ for group in groups.values():
215
+ for input_pages in sorted(group, key=lambda p: p.n_pages):
216
+ yield input_pages
209
217
 
210
218
  async def _parse_publisher(
211
219
  self,
212
- batches: Iterable[OrientedBatch],
220
+ pages: Iterable[InputPages],
213
221
  output_format: LiteParseOutputFormat,
214
222
  queue: asyncio.Queue,
215
223
  ) -> None:
@@ -225,24 +233,29 @@ class LiteParsePipeline(Pipeline):
225
233
  publish_tasks = []
226
234
  with _close_parsers(parsers):
227
235
  async with asyncio.TaskGroup() as tg:
228
- for orientation, batch in batches:
236
+ for input_pages in pages:
237
+ page_range = input_pages.metadata.get(LITEPARSE_RANGE)
238
+ orientation = input_pages.metadata.get("orientation")
229
239
  # We avoid recreating the parser at each iteration since it creates
230
- # a worker pool, instead process in (orientation, page range) order
231
- # and cache the parser
232
- page_range = _liteparse_range_from_pages(*batch)
233
- n_pages = sum(p.n_pages for p in batch)
234
- key = (page_range, orientation)
235
- if key != current_key:
240
+ # a worker pool
241
+ parser_key = (
242
+ (page_range, orientation, None)
243
+ if orientation is None
244
+ else (page_range, orientation, input_pages.n_pages)
245
+ )
246
+ if parser_key != current_key:
236
247
  if parser is not None:
237
248
  close_t = tg.create_task(_await_and_close(tracker, parser))
238
249
  close_parsers_tasks.append(close_t)
239
- logger.debug("loading parser for %s", key)
240
- parser = self._make_parser(output_format, key, n_pages=n_pages)
250
+ logger.debug("loading parser for %s", parser_key)
251
+ parser = self._make_parser(output_format, *parser_key)
241
252
  parsers.append(parser)
242
253
  parser.__enter__().warm_up()
243
- current_key = key
254
+ current_key = parser_key
244
255
  await sem.acquire(), await tracker.acquire(parser)
245
- task = self._convert_and_queue(parser, batch, queue, sem, tracker)
256
+ task = self._convert_and_queue(
257
+ parser, input_pages, queue, sem, tracker
258
+ )
246
259
  publish_tasks.append(tg.create_task(task))
247
260
  await asyncio.gather(*publish_tasks)
248
261
  queue.put_nowait(None)
@@ -256,12 +269,11 @@ class LiteParsePipeline(Pipeline):
256
269
  output_path: Path,
257
270
  ) -> AsyncIterable[Result]:
258
271
  while (queued := await queue.get()) is not None:
259
- pages, res = queued
260
- for p in pages:
261
- filtered = res.filter(p)
262
- buffer.add(p, filtered)
263
- doc_ix = pages[0].doc_idx
264
- doc = pages[0].doc
272
+ input_pages, res = queued
273
+ filtered = res.filter(input_pages)
274
+ buffer.add(input_pages, filtered)
275
+ doc_ix = input_pages.doc_idx
276
+ doc = input_pages.doc
265
277
  if buffer.is_complete(doc_ix):
266
278
  res = result_aggregator(doc, buffer.pop_complete(doc_ix), output_path)
267
279
  yield res
@@ -269,12 +281,12 @@ class LiteParsePipeline(Pipeline):
269
281
  async def _convert_and_queue(
270
282
  self,
271
283
  parser: "LiteParse",
272
- pages: tuple[ProcessedPages],
284
+ pages: InputPages,
273
285
  queue: asyncio.Queue,
274
286
  sem: asyncio.Semaphore,
275
287
  tracker: UsageTracker,
276
288
  ) -> None:
277
- res = await parser.aparse(pages[0].doc.path)
289
+ res = await parser.aparse(pages.doc.path)
278
290
  sem.release(), await tracker.release(parser)
279
291
  res = LiteParsePageResult(
280
292
  pages=res.pages, errors=res.page_errors, images=res.images
@@ -284,8 +296,9 @@ class LiteParsePipeline(Pipeline):
284
296
  def _make_parser(
285
297
  self,
286
298
  output_format: LiteParseOutputFormat,
287
- key: tuple[str, int | None],
288
- n_pages: int,
299
+ target_pages: str,
300
+ orientation: int | None,
301
+ n_pages: int | None,
289
302
  ) -> "LiteParse":
290
303
  from liteparse.parser import LiteParse # noqa: PLC0415
291
304
 
@@ -293,7 +306,6 @@ class LiteParsePipeline(Pipeline):
293
306
  parse_timeout = self._config.per_page_timeout
294
307
  if parse_timeout is not None:
295
308
  parse_timeout = parse_timeout * page_batch_size
296
- target_pages, orientation = key
297
309
  if orientation is not None:
298
310
  orientation = [(p + 1, orientation) for p in range(n_pages)]
299
311
  pool_size = max(1, self._config.n_cpus - 1)
@@ -340,8 +352,8 @@ class LiteParsePipeline(Pipeline):
340
352
 
341
353
 
342
354
  async def _compute_batch_complexities(
343
- pages: ProcessedPages,
344
- ) -> tuple[ProcessedPages, list["PageComplexityStats"]]:
355
+ pages: InputPages,
356
+ ) -> tuple[InputPages, list["PageComplexityStats"]]:
345
357
  from liteparse.parser import LiteParse # noqa: PLC0415
346
358
 
347
359
  target_pages = _liteparse_range_from_pages(pages)
@@ -428,15 +440,18 @@ def _liteparse_range(rng: Range) -> str:
428
440
  return f"{rng[0] + 1}-{rng[1]}"
429
441
 
430
442
 
431
- def _liteparse_range_from_pages(*pages: ProcessedPages) -> str:
432
- pages = sorted(pages, key=lambda p: p.page_range[0])
433
- ranges = (_liteparse_range(p.page_range) for p in pages)
443
+ def _liteparse_range_from_pages(*pages: InputPages) -> str:
444
+ pages = sorted(pages, key=lambda p: p.page_range or -1)
445
+ ranges = (
446
+ p.page_range if p.page_range is not None else (0, p.doc.n_pages) for p in pages
447
+ )
448
+ ranges = (_liteparse_range(r) for r in ranges)
434
449
  return ",".join(ranges)
435
450
 
436
451
 
437
452
  def _pages_from_complexities(
438
453
  doc: InputDoc, doc_ix: int, *complexities: "PageComplexityStats"
439
- ) -> tuple[ProcessedPages]:
454
+ ) -> tuple[InputPages]:
440
455
  complexities = sorted(complexities, key=lambda p: p.page_number)
441
456
  pages = []
442
457
  start, end = None, None
@@ -445,11 +460,11 @@ def _pages_from_complexities(
445
460
  start = p.page_number - 1
446
461
  end = start + 1
447
462
  if p.page_number != end:
448
- processed = ProcessedPages(doc=doc, doc_idx=doc_ix, page_range=(start, end))
463
+ processed = InputPages(doc=doc, doc_idx=doc_ix, page_range=(start, end))
449
464
  pages.append(processed)
450
465
  start = p.page_number - 1
451
466
  end = p.page_number
452
- processed = ProcessedPages(doc=doc, doc_idx=doc_ix, page_range=(start, end))
467
+ processed = InputPages(doc=doc, doc_idx=doc_ix, page_range=(start, end))
453
468
  pages.append(processed)
454
469
  return pages
455
470
 
extract_python/marker_.py CHANGED
@@ -7,10 +7,12 @@ from typing import TYPE_CHECKING
7
7
 
8
8
  from extract_core import (
9
9
  InputDoc,
10
+ InputPages,
10
11
  MarkdownDoc,
11
12
  OutputFormat,
12
13
  Pipeline,
13
14
  PipelineType,
15
+ Range,
14
16
  Result,
15
17
  Status,
16
18
  )
@@ -30,6 +32,16 @@ _MARKER_CONVERSION_ERRORS = tuple()
30
32
  class MarkerPipeline(Pipeline):
31
33
  async def extract_content(
32
34
  self, docs: Iterable[InputDoc], output_format: OutputFormat, output_path: Path
35
+ ) -> AsyncIterable[Result]:
36
+ pages = (doc.to_all_pages(doc_ix) for doc_ix, doc in enumerate(docs))
37
+ async for res in self.extract_pages_content(pages, output_format, output_path):
38
+ yield res
39
+
40
+ async def extract_pages_content(
41
+ self,
42
+ pages: Iterable[InputPages],
43
+ output_format: OutputFormat,
44
+ output_path: Path,
33
45
  ) -> AsyncIterable[Result]:
34
46
  from marker.config.parser import ConfigParser # noqa: PLC0415
35
47
  from marker.converters.pdf import PdfConverter # noqa: PLC0415
@@ -37,16 +49,28 @@ class MarkerPipeline(Pipeline):
37
49
 
38
50
  config = deepcopy(self._config.config)
39
51
  config["output_format"] = output_format.to_marker()
40
- config_parser = ConfigParser(config)
41
- renderer = config_parser.get_renderer()
42
- converter = PdfConverter(
43
- config=config_parser.generate_config_dict(),
44
- artifact_dict=create_model_dict(device=self._device),
45
- processor_list=config_parser.get_processors(),
46
- renderer=renderer,
47
- )
48
- for doc in docs:
49
- yield await _process_doc(doc, converter, output_format, output_path)
52
+ current_rng = object()
53
+ for input_pages in pages:
54
+ if input_pages.page_range != current_rng:
55
+ current_rng = input_pages.page_range
56
+ if current_rng is not None:
57
+ config["page_range"] = _to_marker_page_range(current_rng)
58
+ config_parser = ConfigParser(config)
59
+ renderer = config_parser.get_renderer()
60
+ converter = PdfConverter(
61
+ config=config_parser.generate_config_dict(),
62
+ artifact_dict=create_model_dict(device=self._device),
63
+ processor_list=config_parser.get_processors(),
64
+ renderer=renderer,
65
+ )
66
+ res = await _process_doc(
67
+ input_pages.doc, converter, output_format, output_path
68
+ )
69
+ yield res
70
+
71
+
72
+ def _to_marker_page_range(rng: Range) -> str:
73
+ return f"{rng[0]}-{rng[1]}"
50
74
 
51
75
 
52
76
  @report_recoverable_errors(_MARKER_CONVERSION_ERRORS)
extract_python/mineru_.py CHANGED
@@ -9,6 +9,7 @@ from docvortex.schema import DocumentMetadata, PageInfo, Producer
9
9
  from extract_core import (
10
10
  ConversionOutput,
11
11
  InputDoc,
12
+ InputPages,
12
13
  MinerUPipelineConfig,
13
14
  OutputFormat,
14
15
  Pipeline,
@@ -16,6 +17,7 @@ from extract_core import (
16
17
  Result,
17
18
  Status,
18
19
  )
20
+ from extract_core.objects import Range
19
21
  from mineru import MiddleJson, MinerUParser, ParseResult
20
22
  from mineru.config import VlmConfig
21
23
 
@@ -35,7 +37,16 @@ class MinerUPipeline(Pipeline):
35
37
  async def extract_content(
36
38
  self, docs: Iterable[InputDoc], output_format: OutputFormat, output_path: Path
37
39
  ) -> AsyncIterable[Result]:
40
+ pages = (doc.to_all_pages(doc_ix) for doc_ix, doc in enumerate(docs))
41
+ async for res in self.extract_pages_content(pages, output_format, output_path):
42
+ yield res
38
43
 
44
+ async def extract_pages_content(
45
+ self,
46
+ pages: Iterable[InputPages],
47
+ output_format: OutputFormat,
48
+ output_path: Path,
49
+ ) -> AsyncIterable[Result]:
39
50
  with reset_env():
40
51
  os.environ["MINERU_DEVICE_MODE"] = self._device
41
52
  # TODO: exclude files which are not pdf and return an error
@@ -50,13 +61,24 @@ class MinerUPipeline(Pipeline):
50
61
  image_analysis=config.image_analysis,
51
62
  vlm_config=vlm_config,
52
63
  )
53
- for doc in docs:
54
- res = await parser.parse_async(doc.path)
64
+ for input_pages in pages:
65
+ page_rng = ""
66
+ if input_pages.page_range is not None:
67
+ page_rng = _to_mineru_page_range(input_pages.page_range)
68
+ doc = input_pages.doc
69
+ path = doc.path
70
+ res = await parser.parse_async(path, page_range=page_rng)
55
71
  yield _process_doc(
56
72
  doc, res, output_format=output_format, output_path=output_path
57
73
  )
58
74
 
59
75
 
76
+ def _to_mineru_page_range(rng: Range) -> str:
77
+ # page range is a Python range, MinerU indexes from 1 and upper bound
78
+ # is inclusive
79
+ return f"{rng[0] + 1}-{rng[1]}"
80
+
81
+
60
82
  def _process_doc(
61
83
  doc: InputDoc,
62
84
  result: ParseResult,
extract_python/utils.py CHANGED
@@ -17,16 +17,14 @@ from collections.abc import (
17
17
  )
18
18
  from contextlib import asynccontextmanager, contextmanager
19
19
  from copy import copy
20
- from dataclasses import dataclass
21
20
  from functools import wraps
22
21
  from itertools import tee
23
22
  from pathlib import Path, PurePath
24
23
  from tempfile import TemporaryDirectory
25
24
  from types import TracebackType
26
25
  from typing import Any, BinaryIO, Protocol, Self
27
- from warnings import deprecated
28
26
 
29
- from extract_core import Error, InputDoc, Pages, Result, Status
27
+ from extract_core import Error, InputDoc, InputPages, Pages, Result, Status
30
28
  from pympler import asizeof
31
29
 
32
30
  logger = logging.getLogger(__name__)
@@ -104,37 +102,19 @@ def write_pages(pages: Iterable[str], page_sep: str, out: BinaryIO) -> Pages:
104
102
  return Pages.from_pages_bytes_sizes(pages_byte_sizes)
105
103
 
106
104
 
107
- Range = tuple[int, int]
108
-
109
-
110
- @dataclass(frozen=True)
111
- class ProcessedPages:
112
- doc: InputDoc
113
- doc_idx: int
114
- page_range: Range | None = None
115
-
116
- @property
117
- def n_pages(self) -> int:
118
- if self.page_range is None:
119
- return self.doc.n_pages
120
- return self.page_range[1] - self.page_range[0]
121
-
122
- @property
123
- @deprecated("Use n_pages instead")
124
- def page_length(self) -> int:
125
- return self.n_pages
126
-
127
-
128
105
  def chunk_docs(
129
- docs: Iterable[InputDoc], n_pages: int, *, offset: int = 0
130
- ) -> Iterable[ProcessedPages]:
106
+ docs: Iterable[InputDoc], page_batch_size: int, *, offset: int = 0
107
+ ) -> Iterable[InputPages]:
131
108
  for doc_i, doc in enumerate(docs):
132
109
  doc_idx = offset + doc_i
133
- for i in range(0, doc.n_pages, n_pages):
110
+ if doc.n_pages >= page_batch_size:
111
+ yield doc.to_all_pages(doc_idx)
112
+ continue
113
+ for i in range(0, doc.n_pages, page_batch_size):
134
114
  start = i
135
- end = min(start + n_pages, doc.n_pages)
115
+ end = min(start + page_batch_size, doc.n_pages)
136
116
  rng = (start, end)
137
- pages = ProcessedPages(doc=doc, doc_idx=doc_idx, page_range=rng)
117
+ pages = InputPages(doc=doc, doc_idx=doc_idx, page_range=rng)
138
118
  yield pages
139
119
 
140
120
 
@@ -228,7 +208,7 @@ class ResultBuffer[R]:
228
208
  raise ValueError(msg)
229
209
  return self.__fs_buffer_path
230
210
 
231
- def add(self, processed: ProcessedPages, result: R) -> bool:
211
+ def add(self, processed: InputPages, result: R) -> bool:
232
212
  size = asizeof.asizeof(result)
233
213
  if self._current_size + size > self._max_bytes:
234
214
  path = self._page_path(processed.doc_idx)
@@ -284,7 +264,7 @@ def batch_per_pages(
284
264
  *,
285
265
  max_page_batches: int,
286
266
  chunk_size: int = 1000,
287
- ) -> Iterable[tuple[ProcessedPages]]:
267
+ ) -> Iterable[tuple[InputPages]]:
288
268
  # convert_all only accept to process docs on the exact same page_range
289
269
  #
290
270
  # We collect by chunk to avoid collecting too many inputs, input docs are
@@ -307,14 +287,14 @@ def batch_per_pages(
307
287
 
308
288
  def _bin_fill(
309
289
  docs: Iterable[InputDoc], max_pages: int, offset: int = 0
310
- ) -> Generator[tuple[ProcessedPages], None, int]:
290
+ ) -> Generator[tuple[InputPages], None, int]:
311
291
  bins = defaultdict(deque)
312
292
  doc_idx = offset
313
293
  for doc in docs:
314
294
  if doc.n_pages > max_pages:
315
295
  msg = f"expected docs to have <= {max_pages} pages"
316
296
  raise ValueError(msg)
317
- pages = ProcessedPages(doc=doc, doc_idx=doc_idx)
297
+ pages = InputPages(doc=doc, doc_idx=doc_idx)
318
298
  doc_idx += 1
319
299
  available_space = (s for s in sorted(bins.keys()) if doc.n_pages <= s)
320
300
  available_space = next(available_space, max_pages)
@@ -334,7 +314,7 @@ def _bin_fill(
334
314
 
335
315
  def _by_page_ranges(
336
316
  docs: Iterable[InputDoc], max_pages: int, offset: int = 0
337
- ) -> Generator[tuple[ProcessedPages], None, int]:
317
+ ) -> Generator[tuple[InputPages], None, int]:
338
318
  by_range = defaultdict(list)
339
319
  doc_idx = offset
340
320
  for doc in docs:
@@ -348,7 +328,7 @@ def _by_page_ranges(
348
328
  rng = (start, end)
349
329
  rng_size = end - start
350
330
  alone_in_batch = rng_size == max_pages
351
- pages = ProcessedPages(doc=doc, doc_idx=doc_idx, page_range=rng)
331
+ pages = InputPages(doc=doc, doc_idx=doc_idx, page_range=rng)
352
332
  if alone_in_batch:
353
333
  yield (pages,)
354
334
  continue
@@ -1,13 +1,13 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: extract-python
3
- Version: 0.12.3
3
+ Version: 0.13.0
4
4
  Summary: Structured content extraction
5
5
  Project-URL: Homepage, https://github.com/ICIJ/extract-python
6
6
  Project-URL: Repository, https://github.com/ICIJ/extract-python
7
7
  Project-URL: Issues, https://github.com/ICIJ/extract-python/issues
8
8
  Author-email: Clément Doumouro <cdoumouro@icij.org>
9
9
  Requires-Python: <3.15,>=3.13
10
- Requires-Dist: extract-core~=0.12.3
10
+ Requires-Dist: extract-core~=0.13.0
11
11
  Requires-Dist: pympler~=1.1
12
12
  Provides-Extra: benches
13
13
  Requires-Dist: html2image~=2.0.7; extra == 'benches'
@@ -0,0 +1,16 @@
1
+ extract_python/__init__.py,sha256=j9krghYJCp_CjBGA3lLjuYchxLm_wI3MMNknzsHyVwo,1301
2
+ extract_python/__main__.py,sha256=g-fvS46zl9umKmGrSpl-OG-8PSuZgjqvTCqjpsZtSps,101
3
+ extract_python/constants.py,sha256=659V40LcTWJhX3IbuJLSSvI5AsGJh9ciMrGCfzJn2zA,98
4
+ extract_python/docling_.py,sha256=VSwl8jLxuzFeVvqLmVAXyTOdWzY8g-giNIoHvz53Mao,10404
5
+ extract_python/hybrid_liteparse_.py,sha256=XouvS6p3jPg1nKnLxyeRKvIn7sPTKtU8v9mkR-6uld8,5129
6
+ extract_python/liteparse_.py,sha256=Xmpj8XC5M2tcCdGZcr6kAIS8hnlMaiFHvT2P18ayc-4,21062
7
+ extract_python/marker_.py,sha256=y46W-T230h-NjY2wcuLFlhZFHr9Xo1EVJXaqf-pcL2c,4200
8
+ extract_python/mineru_.py,sha256=hmtOAhq-e09BNgZteiIGCmPa7uW4IVU2THBDFP5fHEs,4963
9
+ extract_python/utils.py,sha256=_0-HRDiLdvKLLFsF2mFjdOgMjjfTdy5yKT7rLZmrG0Q,13048
10
+ extract_python/cli/__init__.py,sha256=Xt3MB74fO8cimm0Xas8dIMmXu62O0dV-4o3-OUzZggo,1245
11
+ extract_python/cli/doc.py,sha256=SMwRs-7-u_lw3wpHO6m3vFYnbjYCn_qIVC-q2TIxcbg,2435
12
+ extract_python/cli/utils.py,sha256=Png7oGKKxDeStn27k-o4Hxlzl-G-u-QDSH6IfJqUk1I,667
13
+ extract_python-0.13.0.dist-info/METADATA,sha256=0hSfBHthPDtk9Dh7cFpCcrcceGXmLs_GhT1Ktkbx49w,1628
14
+ extract_python-0.13.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
15
+ extract_python-0.13.0.dist-info/entry_points.txt,sha256=noSkCWA0LRm0V7WbmYDPBnJrKeiYdpvXynAW6y72Z4M,64
16
+ extract_python-0.13.0.dist-info/RECORD,,
@@ -1,15 +0,0 @@
1
- extract_python/__init__.py,sha256=f6d2exh99z6uR30zDqrnhg5NAx8MFFExvexqM6AaILM,957
2
- extract_python/__main__.py,sha256=g-fvS46zl9umKmGrSpl-OG-8PSuZgjqvTCqjpsZtSps,101
3
- extract_python/constants.py,sha256=659V40LcTWJhX3IbuJLSSvI5AsGJh9ciMrGCfzJn2zA,98
4
- extract_python/docling_.py,sha256=2LaZHEHUcEhEEEHxzb6Ih-niOOpeS5G9k3nJzNB2jrY,10022
5
- extract_python/liteparse_.py,sha256=E39_g-iEar6Z2fL1NNHmPTQisdN5KYDHvZ2xoewyTrU,20372
6
- extract_python/marker_.py,sha256=bb0DJXrSWOznIuPnw4-adR5_R9QiwtFGGBh5KlXFxjM,3323
7
- extract_python/mineru_.py,sha256=D1dE9Qq7txWOrtK9cN1PjXEd6eKo7pKH6xR7zOs2q5I,4101
8
- extract_python/utils.py,sha256=jmxO8wHD99jO0f3fKQGhKxhCfQckf89_pEtPVlGnyJs,13435
9
- extract_python/cli/__init__.py,sha256=Xt3MB74fO8cimm0Xas8dIMmXu62O0dV-4o3-OUzZggo,1245
10
- extract_python/cli/doc.py,sha256=SMwRs-7-u_lw3wpHO6m3vFYnbjYCn_qIVC-q2TIxcbg,2435
11
- extract_python/cli/utils.py,sha256=Png7oGKKxDeStn27k-o4Hxlzl-G-u-QDSH6IfJqUk1I,667
12
- extract_python-0.12.3.dist-info/METADATA,sha256=T3rVACZOoXZWoJtlfMZIJlsbd4sEHnzixFS2Updgt48,1628
13
- extract_python-0.12.3.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
14
- extract_python-0.12.3.dist-info/entry_points.txt,sha256=noSkCWA0LRm0V7WbmYDPBnJrKeiYdpvXynAW6y72Z4M,64
15
- extract_python-0.12.3.dist-info/RECORD,,