structa-maestro 0.2.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.
Files changed (55) hide show
  1. structa_maestro/__init__.py +294 -0
  2. structa_maestro/batch.py +564 -0
  3. structa_maestro/binding.py +206 -0
  4. structa_maestro/builder/__init__.py +0 -0
  5. structa_maestro/builder/result_builder.py +308 -0
  6. structa_maestro/cli.py +730 -0
  7. structa_maestro/confidence/__init__.py +49 -0
  8. structa_maestro/confidence/calibration.py +990 -0
  9. structa_maestro/confidence/normalizer.py +203 -0
  10. structa_maestro/config.py +111 -0
  11. structa_maestro/contracts/__init__.py +0 -0
  12. structa_maestro/contracts/enums.py +86 -0
  13. structa_maestro/contracts/models.py +229 -0
  14. structa_maestro/contracts/serialization.py +169 -0
  15. structa_maestro/documents/__init__.py +32 -0
  16. structa_maestro/documents/docx_parser.py +215 -0
  17. structa_maestro/documents/eml_parser.py +360 -0
  18. structa_maestro/documents/html_parser.py +337 -0
  19. structa_maestro/documents/inputs.py +277 -0
  20. structa_maestro/documents/loader.py +675 -0
  21. structa_maestro/documents/markdown_parser.py +225 -0
  22. structa_maestro/documents/models.py +33 -0
  23. structa_maestro/documents/normalization.py +24 -0
  24. structa_maestro/documents/pdf_parser.py +186 -0
  25. structa_maestro/documents/txt_parser.py +169 -0
  26. structa_maestro/engine.py +1201 -0
  27. structa_maestro/exceptions.py +38 -0
  28. structa_maestro/provenance/__init__.py +0 -0
  29. structa_maestro/provenance/associator.py +234 -0
  30. structa_maestro/py.typed +0 -0
  31. structa_maestro/review.py +1234 -0
  32. structa_maestro/schema/__init__.py +19 -0
  33. structa_maestro/schema/loader.py +616 -0
  34. structa_maestro/schema/models.py +269 -0
  35. structa_maestro/schema/pydantic_adapter.py +566 -0
  36. structa_maestro/schema/rules.py +526 -0
  37. structa_maestro/schema/serializer.py +156 -0
  38. structa_maestro/strategies/__init__.py +45 -0
  39. structa_maestro/strategies/base.py +101 -0
  40. structa_maestro/strategies/llm_anthropic.py +1142 -0
  41. structa_maestro/strategies/llm_config.py +154 -0
  42. structa_maestro/strategies/llm_gemini.py +1171 -0
  43. structa_maestro/strategies/llm_helpers.py +240 -0
  44. structa_maestro/strategies/llm_openai_compat.py +1183 -0
  45. structa_maestro/strategies/schema_compiler.py +248 -0
  46. structa_maestro/strategies/testing.py +71 -0
  47. structa_maestro/telemetry.py +800 -0
  48. structa_maestro/validation/__init__.py +0 -0
  49. structa_maestro/validation/cross_field.py +463 -0
  50. structa_maestro/validation/validator.py +531 -0
  51. structa_maestro-0.2.0.dist-info/METADATA +394 -0
  52. structa_maestro-0.2.0.dist-info/RECORD +55 -0
  53. structa_maestro-0.2.0.dist-info/WHEEL +4 -0
  54. structa_maestro-0.2.0.dist-info/entry_points.txt +2 -0
  55. structa_maestro-0.2.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,1201 @@
1
+ """Main ExtractionEngine, extract/aextract & batch orchestration with stage failure isolation."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import time
7
+ from collections.abc import Mapping, Sequence
8
+ from pathlib import Path
9
+ from typing import Any
10
+ from uuid import uuid4
11
+
12
+ from structa_maestro.batch import (
13
+ BatchDocumentInput,
14
+ BatchExtractionResult,
15
+ BatchOptions,
16
+ _PreparedBatchItem,
17
+ normalize_batch_inputs,
18
+ prepare_batch_items,
19
+ run_async_batch_extraction,
20
+ run_batch_extraction,
21
+ )
22
+ from structa_maestro.builder.result_builder import ResultBuilder
23
+ from structa_maestro.confidence.calibration import ConfidenceCalibrator, validate_calibrator
24
+ from structa_maestro.config import DocumentLimits, get_logger, sanitize_message
25
+ from structa_maestro.contracts.enums import IssueSeverity, PipelineStage
26
+ from structa_maestro.contracts.models import DiagnosticIssue, ExtractionResult, SchemaMetadata
27
+ from structa_maestro.documents.inputs import DocumentInput, sanitize_filename
28
+ from structa_maestro.documents.loader import (
29
+ DocumentLoadResult,
30
+ load_document,
31
+ load_document_input,
32
+ )
33
+ from structa_maestro.exceptions import ConfigurationError, SchemaDefinitionError
34
+ from structa_maestro.schema.models import ExtractionSchema
35
+ from structa_maestro.strategies.base import (
36
+ AsyncExtractionStrategy,
37
+ ExtractionStrategy,
38
+ StrategyOutput,
39
+ )
40
+ from structa_maestro.telemetry import (
41
+ AnyExtractionObserver,
42
+ BatchProgress,
43
+ ExtractionEvent,
44
+ ExtractionEventKind,
45
+ ExtractionObserver,
46
+ StageTiming,
47
+ StrategyTelemetry,
48
+ dispatch_event_async,
49
+ dispatch_event_sync,
50
+ utc_now_iso,
51
+ validate_observers,
52
+ )
53
+
54
+ _logger = get_logger(__name__)
55
+
56
+ AnyExtractionStrategy = ExtractionStrategy | AsyncExtractionStrategy
57
+
58
+
59
+ def _coerce_schema(schema: ExtractionSchema | Mapping[str, Any]) -> ExtractionSchema:
60
+ if isinstance(schema, ExtractionSchema):
61
+ return schema
62
+ if isinstance(schema, Mapping):
63
+ return ExtractionSchema.from_dict(schema)
64
+ raise SchemaDefinitionError(
65
+ f"Expected ExtractionSchema or mapping schema definition, got {type(schema).__name__}."
66
+ )
67
+
68
+
69
+ def _validate_document_id_override(document_id: str | None) -> None:
70
+ if document_id is not None and (not isinstance(document_id, str) or not document_id.strip()):
71
+ raise ConfigurationError("document_id must be a non-empty string or None.")
72
+
73
+
74
+ def _initial_doc_meta(
75
+ document: Any,
76
+ document_id: str | None,
77
+ ) -> tuple[str | None, str | None]:
78
+ clean_id = document_id.strip() if isinstance(document_id, str) and document_id.strip() else None
79
+ if isinstance(document, DocumentInput):
80
+ return clean_id or document.document_id, document.filename
81
+ if isinstance(document, (str, Path)):
82
+ raw_name = Path(document).name if str(document).strip() else None
83
+ safe_name = sanitize_filename(raw_name) if raw_name is not None else None
84
+ return clean_id, safe_name
85
+ return clean_id, None
86
+
87
+
88
+ class ExtractionEngine:
89
+ """Stateless structured extraction orchestrator (sync and asyncio) isolating all stages."""
90
+
91
+ def __init__(
92
+ self,
93
+ strategy: AnyExtractionStrategy,
94
+ *,
95
+ limits: DocumentLimits | None = None,
96
+ result_builder: ResultBuilder | None = None,
97
+ observers: Sequence[AnyExtractionObserver] | None = None,
98
+ calibrator: ConfidenceCalibrator | None = None,
99
+ ) -> None:
100
+ if not isinstance(strategy, (ExtractionStrategy, AsyncExtractionStrategy)):
101
+ raise ConfigurationError(
102
+ "ExtractionEngine requires a strategy implementing ExtractionStrategy "
103
+ "or AsyncExtractionStrategy."
104
+ )
105
+ if limits is not None and not isinstance(limits, DocumentLimits):
106
+ raise ConfigurationError("limits must be a DocumentLimits instance or None.")
107
+ if result_builder is not None and calibrator is not None:
108
+ raise ConfigurationError(
109
+ "Cannot pass both result_builder and calibrator to ExtractionEngine."
110
+ )
111
+ validated_calibrator = validate_calibrator(calibrator)
112
+ self._strategy: AnyExtractionStrategy = strategy
113
+ self._limits = limits or DocumentLimits()
114
+ self._builder = result_builder or ResultBuilder(calibrator=validated_calibrator)
115
+ self._observers: tuple[AnyExtractionObserver, ...] = validate_observers(
116
+ observers,
117
+ require_sync=False,
118
+ )
119
+
120
+ @property
121
+ def limits(self) -> DocumentLimits:
122
+ """Configured document safety limits."""
123
+ return self._limits
124
+
125
+ def _require_sync_strategy(self) -> ExtractionStrategy:
126
+ if not isinstance(self._strategy, ExtractionStrategy):
127
+ raise ConfigurationError(
128
+ f"Strategy {self._strategy.name!r} implements AsyncExtractionStrategy only; "
129
+ "use 'await engine.aextract(...)' or 'await engine.aextract_batch(...)' instead."
130
+ )
131
+ return self._strategy
132
+
133
+ def _compose_observers(
134
+ self,
135
+ call_observers: Sequence[Any] | None,
136
+ *,
137
+ require_sync: bool,
138
+ ) -> tuple[AnyExtractionObserver, ...]:
139
+ if require_sync and self._observers:
140
+ validate_observers(self._observers, require_sync=True)
141
+ validated_call = validate_observers(call_observers, require_sync=require_sync)
142
+ if not validated_call:
143
+ return self._observers
144
+ return self._observers + validated_call
145
+
146
+ def _finalize_from_strategy_output(
147
+ self,
148
+ load_result: DocumentLoadResult,
149
+ parsed_schema: ExtractionSchema,
150
+ strategy_output: StrategyOutput,
151
+ *,
152
+ extraction_id: str | None = None,
153
+ calibrator: ConfidenceCalibrator | None = None,
154
+ ) -> ExtractionResult:
155
+ if load_result.document is None:
156
+ return self._build_load_failure(
157
+ load_result,
158
+ parsed_schema,
159
+ extraction_id=extraction_id,
160
+ )
161
+ try:
162
+ return self._builder.build(
163
+ document=load_result.document,
164
+ schema=parsed_schema,
165
+ strategy_output=strategy_output,
166
+ document_warnings=load_result.warnings,
167
+ extraction_id=extraction_id,
168
+ calibrator=calibrator,
169
+ )
170
+ except Exception as exc:
171
+ safe_msg = sanitize_message(
172
+ f"Canonical result assembly failed unexpectedly: {type(exc).__name__}"
173
+ )
174
+ return self._builder.build_failed(
175
+ schema=parsed_schema,
176
+ source=load_result.source,
177
+ errors=[
178
+ DiagnosticIssue(
179
+ code="result_assembly_error",
180
+ severity=IssueSeverity.ERROR,
181
+ stage=PipelineStage.VALIDATION,
182
+ message=safe_msg,
183
+ )
184
+ ],
185
+ warnings=load_result.warnings,
186
+ extraction_id=extraction_id,
187
+ )
188
+
189
+ def _build_load_failure(
190
+ self,
191
+ load_result: DocumentLoadResult,
192
+ parsed_schema: ExtractionSchema,
193
+ *,
194
+ extraction_id: str | None = None,
195
+ ) -> ExtractionResult:
196
+ _logger.debug(
197
+ "Document loading failed for document_id=%s with %d error(s)",
198
+ load_result.source.document_id,
199
+ len(load_result.errors),
200
+ )
201
+ return self._builder.build_failed(
202
+ schema=parsed_schema,
203
+ source=load_result.source,
204
+ errors=load_result.errors
205
+ or [
206
+ DiagnosticIssue(
207
+ code="document_processing_failed",
208
+ severity=IssueSeverity.ERROR,
209
+ stage=PipelineStage.DOCUMENT_PROCESSING,
210
+ message="Document processing failed without producing prepared text.",
211
+ )
212
+ ],
213
+ warnings=load_result.warnings,
214
+ extraction_id=extraction_id,
215
+ )
216
+
217
+ def _build_invalid_input_failure(
218
+ self,
219
+ parsed_schema: ExtractionSchema,
220
+ *,
221
+ extraction_id: str | None = None,
222
+ ) -> ExtractionResult:
223
+ return self._builder.build_failed(
224
+ schema=parsed_schema,
225
+ source=None,
226
+ errors=[
227
+ DiagnosticIssue(
228
+ code="invalid_input",
229
+ severity=IssueSeverity.ERROR,
230
+ stage=PipelineStage.INPUT,
231
+ message=(
232
+ "Document input must be a file path (str or pathlib.Path) "
233
+ "or a DocumentInput instance."
234
+ ),
235
+ )
236
+ ],
237
+ extraction_id=extraction_id,
238
+ )
239
+
240
+ def _build_strategy_failure(
241
+ self,
242
+ load_result: DocumentLoadResult,
243
+ parsed_schema: ExtractionSchema,
244
+ exc: Exception,
245
+ *,
246
+ extraction_id: str | None = None,
247
+ ) -> ExtractionResult:
248
+ safe_msg = sanitize_message(
249
+ f"Extraction strategy '{self._strategy.name}' failed: {type(exc).__name__}"
250
+ )
251
+ _logger.debug(
252
+ "Strategy error for document_id=%s: %s",
253
+ load_result.source.document_id,
254
+ safe_msg,
255
+ )
256
+ return self._builder.build_failed(
257
+ schema=parsed_schema,
258
+ source=load_result.source,
259
+ errors=[
260
+ DiagnosticIssue(
261
+ code="extraction_strategy_error",
262
+ severity=IssueSeverity.ERROR,
263
+ stage=PipelineStage.EXTRACTION,
264
+ message=safe_msg,
265
+ )
266
+ ],
267
+ warnings=load_result.warnings,
268
+ extraction_id=extraction_id,
269
+ )
270
+
271
+ def _make_started_event(
272
+ self,
273
+ *,
274
+ extraction_id: str,
275
+ batch_id: str | None,
276
+ document_id: str | None,
277
+ filename: str | None,
278
+ schema: ExtractionSchema,
279
+ ) -> ExtractionEvent:
280
+ return ExtractionEvent(
281
+ event_kind=ExtractionEventKind.EXTRACTION_STARTED,
282
+ timestamp=utc_now_iso(),
283
+ extraction_id=extraction_id,
284
+ batch_id=batch_id,
285
+ document_id=document_id,
286
+ filename=filename,
287
+ schema_id=schema.schema_id,
288
+ schema_version=schema.schema_version,
289
+ strategy_name=self._strategy.name,
290
+ )
291
+
292
+ def _make_document_loaded_event(
293
+ self,
294
+ *,
295
+ extraction_id: str,
296
+ batch_id: str | None,
297
+ load_result: DocumentLoadResult | None,
298
+ schema: ExtractionSchema,
299
+ stage_timing: StageTiming,
300
+ error_codes: tuple[str, ...],
301
+ warning_codes: tuple[str, ...],
302
+ ) -> ExtractionEvent:
303
+ src = load_result.source if load_result is not None else None
304
+ return ExtractionEvent(
305
+ event_kind=ExtractionEventKind.DOCUMENT_LOADED,
306
+ timestamp=utc_now_iso(),
307
+ extraction_id=extraction_id,
308
+ batch_id=batch_id,
309
+ document_id=src.document_id if src is not None else None,
310
+ filename=src.filename if src is not None else None,
311
+ media_type=src.media_type if src is not None else None,
312
+ schema_id=schema.schema_id,
313
+ schema_version=schema.schema_version,
314
+ strategy_name=self._strategy.name,
315
+ elapsed_ms=stage_timing.elapsed_ms,
316
+ error_count=len(error_codes),
317
+ warning_count=len(warning_codes),
318
+ error_codes=error_codes,
319
+ warning_codes=warning_codes,
320
+ stage_timing=stage_timing,
321
+ )
322
+
323
+ def _make_strategy_completed_event(
324
+ self,
325
+ *,
326
+ extraction_id: str,
327
+ batch_id: str | None,
328
+ load_result: DocumentLoadResult,
329
+ schema: ExtractionSchema,
330
+ stage_timing: StageTiming,
331
+ strategy_telemetry: StrategyTelemetry | None,
332
+ error_codes: tuple[str, ...],
333
+ warning_codes: tuple[str, ...],
334
+ ) -> ExtractionEvent:
335
+ src = load_result.source
336
+ return ExtractionEvent(
337
+ event_kind=ExtractionEventKind.STRATEGY_COMPLETED,
338
+ timestamp=utc_now_iso(),
339
+ extraction_id=extraction_id,
340
+ batch_id=batch_id,
341
+ document_id=src.document_id,
342
+ filename=src.filename,
343
+ media_type=src.media_type,
344
+ schema_id=schema.schema_id,
345
+ schema_version=schema.schema_version,
346
+ strategy_name=self._strategy.name,
347
+ elapsed_ms=stage_timing.elapsed_ms,
348
+ error_count=len(error_codes),
349
+ warning_count=len(warning_codes),
350
+ error_codes=error_codes,
351
+ warning_codes=warning_codes,
352
+ stage_timing=stage_timing,
353
+ strategy_telemetry=strategy_telemetry,
354
+ )
355
+
356
+ def _make_extraction_completed_event(
357
+ self,
358
+ *,
359
+ result: ExtractionResult,
360
+ batch_id: str | None,
361
+ schema: ExtractionSchema,
362
+ elapsed_ms: float,
363
+ stage_timings: tuple[StageTiming, ...],
364
+ strategy_telemetry: StrategyTelemetry | None,
365
+ ) -> ExtractionEvent:
366
+ src = result.source
367
+ return ExtractionEvent(
368
+ event_kind=ExtractionEventKind.EXTRACTION_COMPLETED,
369
+ timestamp=utc_now_iso(),
370
+ extraction_id=result.extraction_id,
371
+ batch_id=batch_id,
372
+ document_id=src.document_id if src is not None else None,
373
+ filename=src.filename if src is not None else None,
374
+ media_type=src.media_type if src is not None else None,
375
+ schema_id=schema.schema_id,
376
+ schema_version=schema.schema_version,
377
+ strategy_name=self._strategy.name,
378
+ elapsed_ms=elapsed_ms,
379
+ status=result.status,
380
+ validation_status=result.validation.status,
381
+ record_count=len(result.records),
382
+ error_count=len(result.errors),
383
+ warning_count=len(result.warnings),
384
+ error_codes=tuple(e.code for e in result.errors),
385
+ warning_codes=tuple(w.code for w in result.warnings),
386
+ stage_timings=stage_timings,
387
+ strategy_telemetry=strategy_telemetry,
388
+ )
389
+
390
+ def _make_batch_item_completed_event(
391
+ self,
392
+ *,
393
+ result: ExtractionResult,
394
+ batch_id: str,
395
+ schema: ExtractionSchema,
396
+ elapsed_ms: float,
397
+ progress: BatchProgress,
398
+ ) -> ExtractionEvent:
399
+ src = result.source
400
+ return ExtractionEvent(
401
+ event_kind=ExtractionEventKind.BATCH_ITEM_COMPLETED,
402
+ timestamp=utc_now_iso(),
403
+ extraction_id=result.extraction_id,
404
+ batch_id=batch_id,
405
+ document_id=src.document_id if src is not None else None,
406
+ filename=src.filename if src is not None else None,
407
+ media_type=src.media_type if src is not None else None,
408
+ schema_id=schema.schema_id,
409
+ schema_version=schema.schema_version,
410
+ strategy_name=self._strategy.name,
411
+ elapsed_ms=elapsed_ms,
412
+ status=result.status,
413
+ validation_status=result.validation.status,
414
+ record_count=len(result.records),
415
+ error_count=len(result.errors),
416
+ warning_count=len(result.warnings),
417
+ error_codes=tuple(e.code for e in result.errors),
418
+ warning_codes=tuple(w.code for w in result.warnings),
419
+ batch_progress=progress,
420
+ )
421
+
422
+ def _extract_single_sync(
423
+ self,
424
+ document: str | Path | DocumentInput,
425
+ parsed_schema: ExtractionSchema,
426
+ sync_strategy: ExtractionStrategy,
427
+ *,
428
+ document_id: str | None,
429
+ observers: tuple[AnyExtractionObserver, ...],
430
+ batch_id: str | None = None,
431
+ preloaded_error: DocumentLoadResult | None = None,
432
+ item_timings: dict[str, float] | None = None,
433
+ calibrator: ConfidenceCalibrator | None = None,
434
+ ) -> ExtractionResult:
435
+ emit = bool(observers)
436
+ extraction_id = str(uuid4()) if emit else None
437
+ op_started = time.perf_counter()
438
+
439
+ if emit and extraction_id is not None:
440
+ init_doc_id, init_filename = _initial_doc_meta(document, document_id)
441
+ dispatch_event_sync(
442
+ observers,
443
+ self._make_started_event(
444
+ extraction_id=extraction_id,
445
+ batch_id=batch_id,
446
+ document_id=init_doc_id,
447
+ filename=init_filename,
448
+ schema=parsed_schema,
449
+ ),
450
+ )
451
+
452
+ load_started = time.perf_counter()
453
+ load_result: DocumentLoadResult | None
454
+ invalid_type = False
455
+ if preloaded_error is not None:
456
+ load_result = preloaded_error
457
+ elif isinstance(document, DocumentInput):
458
+ load_result = load_document_input(
459
+ document,
460
+ limits=self._limits,
461
+ document_id=document_id,
462
+ )
463
+ elif isinstance(document, (str, Path)):
464
+ load_result = load_document(document, limits=self._limits, document_id=document_id)
465
+ else:
466
+ load_result = None
467
+ invalid_type = True
468
+ load_ms = (time.perf_counter() - load_started) * 1000.0
469
+
470
+ load_ok = load_result is not None and load_result.document is not None
471
+ doc_timing = StageTiming(stage="document_load", elapsed_ms=load_ms, succeeded=load_ok)
472
+
473
+ if emit and extraction_id is not None:
474
+ if invalid_type:
475
+ load_err_codes: tuple[str, ...] = ("invalid_input",)
476
+ load_warn_codes: tuple[str, ...] = ()
477
+ elif load_result is not None:
478
+ load_err_codes = (
479
+ tuple(e.code for e in load_result.errors)
480
+ if load_result.errors
481
+ else (() if load_ok else ("document_processing_failed",))
482
+ )
483
+ load_warn_codes = tuple(w.code for w in load_result.warnings)
484
+ else:
485
+ load_err_codes = ("document_processing_failed",)
486
+ load_warn_codes = ()
487
+ dispatch_event_sync(
488
+ observers,
489
+ self._make_document_loaded_event(
490
+ extraction_id=extraction_id,
491
+ batch_id=batch_id,
492
+ load_result=load_result,
493
+ schema=parsed_schema,
494
+ stage_timing=doc_timing,
495
+ error_codes=load_err_codes,
496
+ warning_codes=load_warn_codes,
497
+ ),
498
+ )
499
+
500
+ if invalid_type or load_result is None or load_result.document is None:
501
+ fin_started = time.perf_counter()
502
+ if invalid_type or load_result is None:
503
+ result = self._build_invalid_input_failure(
504
+ parsed_schema,
505
+ extraction_id=extraction_id,
506
+ )
507
+ else:
508
+ result = self._build_load_failure(
509
+ load_result,
510
+ parsed_schema,
511
+ extraction_id=extraction_id,
512
+ )
513
+ fin_ms = (time.perf_counter() - fin_started) * 1000.0
514
+ op_ms = (time.perf_counter() - op_started) * 1000.0
515
+ if item_timings is not None:
516
+ item_timings[result.extraction_id] = op_ms
517
+ if emit:
518
+ fin_timing = StageTiming(stage="finalization", elapsed_ms=fin_ms, succeeded=True)
519
+ dispatch_event_sync(
520
+ observers,
521
+ self._make_extraction_completed_event(
522
+ result=result,
523
+ batch_id=batch_id,
524
+ schema=parsed_schema,
525
+ elapsed_ms=op_ms,
526
+ stage_timings=(doc_timing, fin_timing),
527
+ strategy_telemetry=None,
528
+ ),
529
+ )
530
+ return result
531
+
532
+ strat_started = time.perf_counter()
533
+ strategy_output: StrategyOutput | None = None
534
+ strategy_exc: Exception | None = None
535
+ try:
536
+ strategy_output = sync_strategy.extract_raw(load_result.document, parsed_schema)
537
+ except Exception as exc:
538
+ strategy_exc = exc
539
+ strat_ms = (time.perf_counter() - strat_started) * 1000.0
540
+
541
+ if strategy_exc is not None or strategy_output is None:
542
+ strat_timing = StageTiming(stage="strategy", elapsed_ms=strat_ms, succeeded=False)
543
+ if emit and extraction_id is not None:
544
+ dispatch_event_sync(
545
+ observers,
546
+ self._make_strategy_completed_event(
547
+ extraction_id=extraction_id,
548
+ batch_id=batch_id,
549
+ load_result=load_result,
550
+ schema=parsed_schema,
551
+ stage_timing=strat_timing,
552
+ strategy_telemetry=None,
553
+ error_codes=("extraction_strategy_error",),
554
+ warning_codes=(),
555
+ ),
556
+ )
557
+ fin_started = time.perf_counter()
558
+ err_exc = strategy_exc if strategy_exc is not None else RuntimeError("Strategy failed")
559
+ result = self._build_strategy_failure(
560
+ load_result,
561
+ parsed_schema,
562
+ err_exc,
563
+ extraction_id=extraction_id,
564
+ )
565
+ fin_ms = (time.perf_counter() - fin_started) * 1000.0
566
+ op_ms = (time.perf_counter() - op_started) * 1000.0
567
+ if item_timings is not None:
568
+ item_timings[result.extraction_id] = op_ms
569
+ if emit:
570
+ fin_timing = StageTiming(stage="finalization", elapsed_ms=fin_ms, succeeded=True)
571
+ dispatch_event_sync(
572
+ observers,
573
+ self._make_extraction_completed_event(
574
+ result=result,
575
+ batch_id=batch_id,
576
+ schema=parsed_schema,
577
+ elapsed_ms=op_ms,
578
+ stage_timings=(doc_timing, strat_timing, fin_timing),
579
+ strategy_telemetry=None,
580
+ ),
581
+ )
582
+ return result
583
+
584
+ strat_timing = StageTiming(
585
+ stage="strategy",
586
+ elapsed_ms=strat_ms,
587
+ succeeded=not strategy_output.failed,
588
+ )
589
+ if emit and extraction_id is not None:
590
+ dispatch_event_sync(
591
+ observers,
592
+ self._make_strategy_completed_event(
593
+ extraction_id=extraction_id,
594
+ batch_id=batch_id,
595
+ load_result=load_result,
596
+ schema=parsed_schema,
597
+ stage_timing=strat_timing,
598
+ strategy_telemetry=strategy_output.telemetry,
599
+ error_codes=tuple(e.code for e in strategy_output.errors),
600
+ warning_codes=tuple(w.code for w in strategy_output.warnings),
601
+ ),
602
+ )
603
+
604
+ fin_started = time.perf_counter()
605
+ result = self._finalize_from_strategy_output(
606
+ load_result,
607
+ parsed_schema,
608
+ strategy_output,
609
+ extraction_id=extraction_id,
610
+ calibrator=calibrator,
611
+ )
612
+ fin_ms = (time.perf_counter() - fin_started) * 1000.0
613
+ op_ms = (time.perf_counter() - op_started) * 1000.0
614
+ if item_timings is not None:
615
+ item_timings[result.extraction_id] = op_ms
616
+ if emit:
617
+ fin_ok = not any(e.code == "result_assembly_error" for e in result.errors)
618
+ fin_timing = StageTiming(stage="finalization", elapsed_ms=fin_ms, succeeded=fin_ok)
619
+ dispatch_event_sync(
620
+ observers,
621
+ self._make_extraction_completed_event(
622
+ result=result,
623
+ batch_id=batch_id,
624
+ schema=parsed_schema,
625
+ elapsed_ms=op_ms,
626
+ stage_timings=(doc_timing, strat_timing, fin_timing),
627
+ strategy_telemetry=strategy_output.telemetry,
628
+ ),
629
+ )
630
+ return result
631
+
632
+ async def _extract_single_async(
633
+ self,
634
+ document: str | Path | DocumentInput,
635
+ parsed_schema: ExtractionSchema,
636
+ *,
637
+ document_id: str | None,
638
+ observers: tuple[AnyExtractionObserver, ...],
639
+ batch_id: str | None = None,
640
+ preloaded_error: DocumentLoadResult | None = None,
641
+ item_timings: dict[str, float] | None = None,
642
+ calibrator: ConfidenceCalibrator | None = None,
643
+ ) -> ExtractionResult:
644
+ if preloaded_error is None and isinstance(document, DocumentInput):
645
+ _validate_document_id_override(document_id)
646
+
647
+ emit = bool(observers)
648
+ extraction_id = str(uuid4()) if emit else None
649
+ op_started = time.perf_counter()
650
+
651
+ if emit and extraction_id is not None:
652
+ init_doc_id, init_filename = _initial_doc_meta(document, document_id)
653
+ await dispatch_event_async(
654
+ observers,
655
+ self._make_started_event(
656
+ extraction_id=extraction_id,
657
+ batch_id=batch_id,
658
+ document_id=init_doc_id,
659
+ filename=init_filename,
660
+ schema=parsed_schema,
661
+ ),
662
+ )
663
+
664
+ load_started = time.perf_counter()
665
+ load_result: DocumentLoadResult | None
666
+ invalid_type = False
667
+ if preloaded_error is not None:
668
+ load_result = preloaded_error
669
+ elif isinstance(document, DocumentInput):
670
+ load_result = await asyncio.to_thread(
671
+ load_document_input,
672
+ document,
673
+ limits=self._limits,
674
+ document_id=document_id,
675
+ )
676
+ elif isinstance(document, (str, Path)):
677
+ load_result = await asyncio.to_thread(
678
+ load_document,
679
+ document,
680
+ limits=self._limits,
681
+ document_id=document_id,
682
+ )
683
+ else:
684
+ load_result = None
685
+ invalid_type = True
686
+ load_ms = (time.perf_counter() - load_started) * 1000.0
687
+
688
+ load_ok = load_result is not None and load_result.document is not None
689
+ doc_timing = StageTiming(stage="document_load", elapsed_ms=load_ms, succeeded=load_ok)
690
+
691
+ if emit and extraction_id is not None:
692
+ if invalid_type:
693
+ load_err_codes: tuple[str, ...] = ("invalid_input",)
694
+ load_warn_codes: tuple[str, ...] = ()
695
+ elif load_result is not None:
696
+ load_err_codes = (
697
+ tuple(e.code for e in load_result.errors)
698
+ if load_result.errors
699
+ else (() if load_ok else ("document_processing_failed",))
700
+ )
701
+ load_warn_codes = tuple(w.code for w in load_result.warnings)
702
+ else:
703
+ load_err_codes = ("document_processing_failed",)
704
+ load_warn_codes = ()
705
+ await dispatch_event_async(
706
+ observers,
707
+ self._make_document_loaded_event(
708
+ extraction_id=extraction_id,
709
+ batch_id=batch_id,
710
+ load_result=load_result,
711
+ schema=parsed_schema,
712
+ stage_timing=doc_timing,
713
+ error_codes=load_err_codes,
714
+ warning_codes=load_warn_codes,
715
+ ),
716
+ )
717
+
718
+ if invalid_type or load_result is None or load_result.document is None:
719
+ fin_started = time.perf_counter()
720
+ if invalid_type or load_result is None:
721
+ result = self._build_invalid_input_failure(
722
+ parsed_schema,
723
+ extraction_id=extraction_id,
724
+ )
725
+ else:
726
+ result = self._build_load_failure(
727
+ load_result,
728
+ parsed_schema,
729
+ extraction_id=extraction_id,
730
+ )
731
+ fin_ms = (time.perf_counter() - fin_started) * 1000.0
732
+ op_ms = (time.perf_counter() - op_started) * 1000.0
733
+ if item_timings is not None:
734
+ item_timings[result.extraction_id] = op_ms
735
+ if emit:
736
+ fin_timing = StageTiming(stage="finalization", elapsed_ms=fin_ms, succeeded=True)
737
+ await dispatch_event_async(
738
+ observers,
739
+ self._make_extraction_completed_event(
740
+ result=result,
741
+ batch_id=batch_id,
742
+ schema=parsed_schema,
743
+ elapsed_ms=op_ms,
744
+ stage_timings=(doc_timing, fin_timing),
745
+ strategy_telemetry=None,
746
+ ),
747
+ )
748
+ return result
749
+
750
+ strat_started = time.perf_counter()
751
+ strategy_output: StrategyOutput | None = None
752
+ strategy_exc: Exception | None = None
753
+ try:
754
+ if isinstance(self._strategy, AsyncExtractionStrategy):
755
+ strategy_output = await self._strategy.aextract_raw(
756
+ load_result.document,
757
+ parsed_schema,
758
+ )
759
+ else:
760
+ strategy_output = await asyncio.to_thread(
761
+ self._strategy.extract_raw,
762
+ load_result.document,
763
+ parsed_schema,
764
+ )
765
+ except Exception as exc:
766
+ # asyncio.CancelledError subclasses BaseException so it propagates cleanly
767
+ strategy_exc = exc
768
+ strat_ms = (time.perf_counter() - strat_started) * 1000.0
769
+
770
+ if strategy_exc is not None or strategy_output is None:
771
+ strat_timing = StageTiming(stage="strategy", elapsed_ms=strat_ms, succeeded=False)
772
+ if emit and extraction_id is not None:
773
+ await dispatch_event_async(
774
+ observers,
775
+ self._make_strategy_completed_event(
776
+ extraction_id=extraction_id,
777
+ batch_id=batch_id,
778
+ load_result=load_result,
779
+ schema=parsed_schema,
780
+ stage_timing=strat_timing,
781
+ strategy_telemetry=None,
782
+ error_codes=("extraction_strategy_error",),
783
+ warning_codes=(),
784
+ ),
785
+ )
786
+ fin_started = time.perf_counter()
787
+ err_exc = strategy_exc if strategy_exc is not None else RuntimeError("Strategy failed")
788
+ result = self._build_strategy_failure(
789
+ load_result,
790
+ parsed_schema,
791
+ err_exc,
792
+ extraction_id=extraction_id,
793
+ )
794
+ fin_ms = (time.perf_counter() - fin_started) * 1000.0
795
+ op_ms = (time.perf_counter() - op_started) * 1000.0
796
+ if item_timings is not None:
797
+ item_timings[result.extraction_id] = op_ms
798
+ if emit:
799
+ fin_timing = StageTiming(stage="finalization", elapsed_ms=fin_ms, succeeded=True)
800
+ await dispatch_event_async(
801
+ observers,
802
+ self._make_extraction_completed_event(
803
+ result=result,
804
+ batch_id=batch_id,
805
+ schema=parsed_schema,
806
+ elapsed_ms=op_ms,
807
+ stage_timings=(doc_timing, strat_timing, fin_timing),
808
+ strategy_telemetry=None,
809
+ ),
810
+ )
811
+ return result
812
+
813
+ strat_timing = StageTiming(
814
+ stage="strategy",
815
+ elapsed_ms=strat_ms,
816
+ succeeded=not strategy_output.failed,
817
+ )
818
+ if emit and extraction_id is not None:
819
+ await dispatch_event_async(
820
+ observers,
821
+ self._make_strategy_completed_event(
822
+ extraction_id=extraction_id,
823
+ batch_id=batch_id,
824
+ load_result=load_result,
825
+ schema=parsed_schema,
826
+ stage_timing=strat_timing,
827
+ strategy_telemetry=strategy_output.telemetry,
828
+ error_codes=tuple(e.code for e in strategy_output.errors),
829
+ warning_codes=tuple(w.code for w in strategy_output.warnings),
830
+ ),
831
+ )
832
+
833
+ fin_started = time.perf_counter()
834
+ result = self._finalize_from_strategy_output(
835
+ load_result,
836
+ parsed_schema,
837
+ strategy_output,
838
+ extraction_id=extraction_id,
839
+ calibrator=calibrator,
840
+ )
841
+ fin_ms = (time.perf_counter() - fin_started) * 1000.0
842
+ op_ms = (time.perf_counter() - op_started) * 1000.0
843
+ if item_timings is not None:
844
+ item_timings[result.extraction_id] = op_ms
845
+ if emit:
846
+ fin_ok = not any(e.code == "result_assembly_error" for e in result.errors)
847
+ fin_timing = StageTiming(stage="finalization", elapsed_ms=fin_ms, succeeded=fin_ok)
848
+ await dispatch_event_async(
849
+ observers,
850
+ self._make_extraction_completed_event(
851
+ result=result,
852
+ batch_id=batch_id,
853
+ schema=parsed_schema,
854
+ elapsed_ms=op_ms,
855
+ stage_timings=(doc_timing, strat_timing, fin_timing),
856
+ strategy_telemetry=strategy_output.telemetry,
857
+ ),
858
+ )
859
+ return result
860
+
861
+ def extract(
862
+ self,
863
+ document: str | Path | DocumentInput,
864
+ schema: ExtractionSchema | Mapping[str, Any],
865
+ *,
866
+ document_id: str | None = None,
867
+ observers: Sequence[ExtractionObserver] | None = None,
868
+ calibrator: ConfidenceCalibrator | None = None,
869
+ ) -> ExtractionResult:
870
+ """Extract validated canonical structured records synchronously."""
871
+ sync_strategy = self._require_sync_strategy()
872
+ effective_observers = self._compose_observers(observers, require_sync=True)
873
+ validated_calibrator = validate_calibrator(calibrator)
874
+ parsed_schema = _coerce_schema(schema)
875
+ return self._extract_single_sync(
876
+ document,
877
+ parsed_schema,
878
+ sync_strategy,
879
+ document_id=document_id,
880
+ observers=effective_observers,
881
+ calibrator=validated_calibrator,
882
+ )
883
+
884
+ async def aextract(
885
+ self,
886
+ document: str | Path | DocumentInput,
887
+ schema: ExtractionSchema | Mapping[str, Any],
888
+ *,
889
+ document_id: str | None = None,
890
+ observers: Sequence[AnyExtractionObserver] | None = None,
891
+ calibrator: ConfidenceCalibrator | None = None,
892
+ ) -> ExtractionResult:
893
+ """Asynchronously extract validated canonical structured records without blocking."""
894
+ effective_observers = self._compose_observers(observers, require_sync=False)
895
+ validated_calibrator = validate_calibrator(calibrator)
896
+ parsed_schema = _coerce_schema(schema)
897
+ return await self._extract_single_async(
898
+ document,
899
+ parsed_schema,
900
+ document_id=document_id,
901
+ observers=effective_observers,
902
+ calibrator=validated_calibrator,
903
+ )
904
+
905
+ def extract_batch(
906
+ self,
907
+ documents: Sequence[str | Path | BatchDocumentInput | DocumentInput],
908
+ schema: ExtractionSchema | Mapping[str, Any],
909
+ *,
910
+ options: BatchOptions | None = None,
911
+ observers: Sequence[ExtractionObserver] | None = None,
912
+ calibrator: ConfidenceCalibrator | None = None,
913
+ ) -> BatchExtractionResult:
914
+ """Statelessly extract a mixed collection of paths and in-memory documents in order."""
915
+ sync_strategy = self._require_sync_strategy()
916
+ effective_observers = self._compose_observers(observers, require_sync=True)
917
+ validated_calibrator = validate_calibrator(calibrator)
918
+ parsed_schema = _coerce_schema(schema)
919
+ resolved_options = options if options is not None else BatchOptions()
920
+ if not isinstance(resolved_options, BatchOptions):
921
+ raise ConfigurationError("options must be a BatchOptions instance or None.")
922
+ normalized_inputs = normalize_batch_inputs(documents)
923
+ prepared_items = prepare_batch_items(
924
+ normalized_inputs,
925
+ limits=self._limits,
926
+ max_workers=resolved_options.max_workers,
927
+ )
928
+ schema_meta = SchemaMetadata(
929
+ schema_id=parsed_schema.schema_id,
930
+ schema_version=parsed_schema.schema_version,
931
+ )
932
+
933
+ batch_id = str(uuid4())
934
+ emit = bool(effective_observers)
935
+ item_timings: dict[str, float] | None = {} if emit else None
936
+
937
+ if emit:
938
+ dispatch_event_sync(
939
+ effective_observers,
940
+ ExtractionEvent(
941
+ event_kind=ExtractionEventKind.BATCH_STARTED,
942
+ timestamp=utc_now_iso(),
943
+ batch_id=batch_id,
944
+ schema_id=parsed_schema.schema_id,
945
+ schema_version=parsed_schema.schema_version,
946
+ strategy_name=self._strategy.name,
947
+ batch_progress=BatchProgress(
948
+ batch_id=batch_id,
949
+ total_documents=len(prepared_items),
950
+ processed_documents=0,
951
+ skipped_documents=0,
952
+ ),
953
+ ),
954
+ )
955
+
956
+ def _extract_one(item: _PreparedBatchItem) -> ExtractionResult:
957
+ return self._extract_single_sync(
958
+ item.document_input,
959
+ parsed_schema,
960
+ sync_strategy,
961
+ document_id=None,
962
+ observers=effective_observers,
963
+ batch_id=batch_id,
964
+ preloaded_error=item.preloaded_error,
965
+ item_timings=item_timings,
966
+ calibrator=validated_calibrator,
967
+ )
968
+
969
+ def _on_item_complete(
970
+ _idx: int,
971
+ res: ExtractionResult,
972
+ progress: BatchProgress,
973
+ ) -> None:
974
+ elapsed = item_timings.get(res.extraction_id, 0.0) if item_timings is not None else 0.0
975
+ dispatch_event_sync(
976
+ effective_observers,
977
+ self._make_batch_item_completed_event(
978
+ result=res,
979
+ batch_id=batch_id,
980
+ schema=parsed_schema,
981
+ elapsed_ms=elapsed,
982
+ progress=progress,
983
+ ),
984
+ )
985
+
986
+ batch_res = run_batch_extraction(
987
+ inputs=prepared_items,
988
+ schema_metadata=schema_meta,
989
+ options=resolved_options,
990
+ extract_one=_extract_one,
991
+ batch_id=batch_id,
992
+ on_item_complete=_on_item_complete if emit else None,
993
+ )
994
+
995
+ if emit:
996
+ summary = batch_res.summary
997
+ dispatch_event_sync(
998
+ effective_observers,
999
+ ExtractionEvent(
1000
+ event_kind=ExtractionEventKind.BATCH_COMPLETED,
1001
+ timestamp=utc_now_iso(),
1002
+ batch_id=batch_id,
1003
+ schema_id=parsed_schema.schema_id,
1004
+ schema_version=parsed_schema.schema_version,
1005
+ strategy_name=self._strategy.name,
1006
+ elapsed_ms=summary.elapsed_ms,
1007
+ batch_progress=BatchProgress(
1008
+ batch_id=batch_id,
1009
+ total_documents=summary.total_documents,
1010
+ processed_documents=summary.processed_documents,
1011
+ skipped_documents=summary.skipped_documents,
1012
+ completed_count=summary.completed_count,
1013
+ partial_count=summary.partial_count,
1014
+ failed_count=summary.failed_count,
1015
+ aborted_early=summary.aborted_early,
1016
+ ),
1017
+ ),
1018
+ )
1019
+
1020
+ return batch_res
1021
+
1022
+ async def aextract_batch(
1023
+ self,
1024
+ documents: Sequence[str | Path | BatchDocumentInput | DocumentInput],
1025
+ schema: ExtractionSchema | Mapping[str, Any],
1026
+ *,
1027
+ options: BatchOptions | None = None,
1028
+ observers: Sequence[AnyExtractionObserver] | None = None,
1029
+ calibrator: ConfidenceCalibrator | None = None,
1030
+ ) -> BatchExtractionResult:
1031
+ """Asynchronously extract a mixed collection of documents with bounded concurrency."""
1032
+ effective_observers = self._compose_observers(observers, require_sync=False)
1033
+ validated_calibrator = validate_calibrator(calibrator)
1034
+ parsed_schema = _coerce_schema(schema)
1035
+ resolved_options = options if options is not None else BatchOptions()
1036
+ if not isinstance(resolved_options, BatchOptions):
1037
+ raise ConfigurationError("options must be a BatchOptions instance or None.")
1038
+ normalized_inputs = normalize_batch_inputs(documents)
1039
+ if resolved_options.max_workers > 1:
1040
+ prepared_items = await asyncio.to_thread(
1041
+ prepare_batch_items,
1042
+ normalized_inputs,
1043
+ limits=self._limits,
1044
+ max_workers=resolved_options.max_workers,
1045
+ )
1046
+ else:
1047
+ prepared_items = tuple(
1048
+ _PreparedBatchItem(document_input=item) for item in normalized_inputs
1049
+ )
1050
+ schema_meta = SchemaMetadata(
1051
+ schema_id=parsed_schema.schema_id,
1052
+ schema_version=parsed_schema.schema_version,
1053
+ )
1054
+
1055
+ batch_id = str(uuid4())
1056
+ emit = bool(effective_observers)
1057
+ item_timings: dict[str, float] | None = {} if emit else None
1058
+
1059
+ if emit:
1060
+ await dispatch_event_async(
1061
+ effective_observers,
1062
+ ExtractionEvent(
1063
+ event_kind=ExtractionEventKind.BATCH_STARTED,
1064
+ timestamp=utc_now_iso(),
1065
+ batch_id=batch_id,
1066
+ schema_id=parsed_schema.schema_id,
1067
+ schema_version=parsed_schema.schema_version,
1068
+ strategy_name=self._strategy.name,
1069
+ batch_progress=BatchProgress(
1070
+ batch_id=batch_id,
1071
+ total_documents=len(prepared_items),
1072
+ processed_documents=0,
1073
+ skipped_documents=0,
1074
+ ),
1075
+ ),
1076
+ )
1077
+
1078
+ async def _aextract_one(item: _PreparedBatchItem) -> ExtractionResult:
1079
+ return await self._extract_single_async(
1080
+ item.document_input,
1081
+ parsed_schema,
1082
+ document_id=None,
1083
+ observers=effective_observers,
1084
+ batch_id=batch_id,
1085
+ preloaded_error=item.preloaded_error,
1086
+ item_timings=item_timings,
1087
+ calibrator=validated_calibrator,
1088
+ )
1089
+
1090
+ async def _aon_item_complete(
1091
+ _idx: int,
1092
+ res: ExtractionResult,
1093
+ progress: BatchProgress,
1094
+ ) -> None:
1095
+ elapsed = item_timings.get(res.extraction_id, 0.0) if item_timings is not None else 0.0
1096
+ await dispatch_event_async(
1097
+ effective_observers,
1098
+ self._make_batch_item_completed_event(
1099
+ result=res,
1100
+ batch_id=batch_id,
1101
+ schema=parsed_schema,
1102
+ elapsed_ms=elapsed,
1103
+ progress=progress,
1104
+ ),
1105
+ )
1106
+
1107
+ batch_res = await run_async_batch_extraction(
1108
+ inputs=prepared_items,
1109
+ schema_metadata=schema_meta,
1110
+ options=resolved_options,
1111
+ extract_one=_aextract_one,
1112
+ batch_id=batch_id,
1113
+ aon_item_complete=_aon_item_complete if emit else None,
1114
+ )
1115
+
1116
+ if emit:
1117
+ summary = batch_res.summary
1118
+ await dispatch_event_async(
1119
+ effective_observers,
1120
+ ExtractionEvent(
1121
+ event_kind=ExtractionEventKind.BATCH_COMPLETED,
1122
+ timestamp=utc_now_iso(),
1123
+ batch_id=batch_id,
1124
+ schema_id=parsed_schema.schema_id,
1125
+ schema_version=parsed_schema.schema_version,
1126
+ strategy_name=self._strategy.name,
1127
+ elapsed_ms=summary.elapsed_ms,
1128
+ batch_progress=BatchProgress(
1129
+ batch_id=batch_id,
1130
+ total_documents=summary.total_documents,
1131
+ processed_documents=summary.processed_documents,
1132
+ skipped_documents=summary.skipped_documents,
1133
+ completed_count=summary.completed_count,
1134
+ partial_count=summary.partial_count,
1135
+ failed_count=summary.failed_count,
1136
+ aborted_early=summary.aborted_early,
1137
+ ),
1138
+ ),
1139
+ )
1140
+
1141
+ return batch_res
1142
+
1143
+
1144
+ def extract(
1145
+ document: str | Path | DocumentInput,
1146
+ schema: ExtractionSchema | Mapping[str, Any],
1147
+ *,
1148
+ strategy: ExtractionStrategy,
1149
+ limits: DocumentLimits | None = None,
1150
+ document_id: str | None = None,
1151
+ observers: Sequence[ExtractionObserver] | None = None,
1152
+ calibrator: ConfidenceCalibrator | None = None,
1153
+ ) -> ExtractionResult:
1154
+ """Convenience synchronous entry point delegating directly to ExtractionEngine."""
1155
+ engine = ExtractionEngine(strategy=strategy, limits=limits, calibrator=calibrator)
1156
+ return engine.extract(document, schema, document_id=document_id, observers=observers)
1157
+
1158
+
1159
+ async def aextract(
1160
+ document: str | Path | DocumentInput,
1161
+ schema: ExtractionSchema | Mapping[str, Any],
1162
+ *,
1163
+ strategy: AnyExtractionStrategy,
1164
+ limits: DocumentLimits | None = None,
1165
+ document_id: str | None = None,
1166
+ observers: Sequence[AnyExtractionObserver] | None = None,
1167
+ calibrator: ConfidenceCalibrator | None = None,
1168
+ ) -> ExtractionResult:
1169
+ """Convenience asyncio entry point delegating directly to ExtractionEngine.aextract."""
1170
+ engine = ExtractionEngine(strategy=strategy, limits=limits, calibrator=calibrator)
1171
+ return await engine.aextract(document, schema, document_id=document_id, observers=observers)
1172
+
1173
+
1174
+ def extract_batch(
1175
+ documents: Sequence[str | Path | BatchDocumentInput | DocumentInput],
1176
+ schema: ExtractionSchema | Mapping[str, Any],
1177
+ *,
1178
+ strategy: ExtractionStrategy,
1179
+ limits: DocumentLimits | None = None,
1180
+ options: BatchOptions | None = None,
1181
+ observers: Sequence[ExtractionObserver] | None = None,
1182
+ calibrator: ConfidenceCalibrator | None = None,
1183
+ ) -> BatchExtractionResult:
1184
+ """Convenience synchronous batch entry point delegating directly to ExtractionEngine."""
1185
+ engine = ExtractionEngine(strategy=strategy, limits=limits, calibrator=calibrator)
1186
+ return engine.extract_batch(documents, schema, options=options, observers=observers)
1187
+
1188
+
1189
+ async def aextract_batch(
1190
+ documents: Sequence[str | Path | BatchDocumentInput | DocumentInput],
1191
+ schema: ExtractionSchema | Mapping[str, Any],
1192
+ *,
1193
+ strategy: AnyExtractionStrategy,
1194
+ limits: DocumentLimits | None = None,
1195
+ options: BatchOptions | None = None,
1196
+ observers: Sequence[AnyExtractionObserver] | None = None,
1197
+ calibrator: ConfidenceCalibrator | None = None,
1198
+ ) -> BatchExtractionResult:
1199
+ """Convenience asyncio batch entry point delegating directly to ExtractionEngine."""
1200
+ engine = ExtractionEngine(strategy=strategy, limits=limits, calibrator=calibrator)
1201
+ return await engine.aextract_batch(documents, schema, options=options, observers=observers)