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,675 @@
1
+ """Safe document input loader enforcing path checks, bounded streams, magic bytes, and limits."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import io
6
+ import os
7
+ import zipfile
8
+ from dataclasses import dataclass, field
9
+ from pathlib import Path
10
+ from typing import BinaryIO
11
+ from uuid import uuid4
12
+
13
+ from structa_maestro.config import DocumentLimits
14
+ from structa_maestro.contracts.enums import DocumentFormat, IssueSeverity, PipelineStage
15
+ from structa_maestro.contracts.models import DiagnosticIssue, SourceMetadata
16
+ from structa_maestro.documents.docx_parser import parse_docx_bytes
17
+ from structa_maestro.documents.eml_parser import parse_eml_bytes
18
+ from structa_maestro.documents.html_parser import parse_html_bytes
19
+ from structa_maestro.documents.inputs import (
20
+ SUPPORTED_MEDIA_TYPES,
21
+ DocumentInput,
22
+ DocumentInputKind,
23
+ sanitize_filename,
24
+ )
25
+ from structa_maestro.documents.markdown_parser import parse_markdown_bytes
26
+ from structa_maestro.documents.models import PreparedDocument
27
+ from structa_maestro.documents.pdf_parser import parse_pdf_bytes
28
+ from structa_maestro.documents.txt_parser import (
29
+ ParseResult,
30
+ _decode_text_bytes,
31
+ _looks_binary,
32
+ parse_txt_bytes,
33
+ )
34
+ from structa_maestro.exceptions import ConfigurationError
35
+
36
+ _MEDIA_TYPES: dict[DocumentFormat, str] = {
37
+ DocumentFormat.TXT: "text/plain",
38
+ DocumentFormat.PDF: "application/pdf",
39
+ DocumentFormat.DOCX: (
40
+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
41
+ ),
42
+ DocumentFormat.HTML: "text/html",
43
+ DocumentFormat.MARKDOWN: "text/markdown",
44
+ DocumentFormat.EML: "message/rfc822",
45
+ }
46
+
47
+ _EXTENSION_TO_FORMAT: dict[str, DocumentFormat] = {
48
+ ".txt": DocumentFormat.TXT,
49
+ ".pdf": DocumentFormat.PDF,
50
+ ".docx": DocumentFormat.DOCX,
51
+ ".html": DocumentFormat.HTML,
52
+ ".htm": DocumentFormat.HTML,
53
+ ".md": DocumentFormat.MARKDOWN,
54
+ ".markdown": DocumentFormat.MARKDOWN,
55
+ ".eml": DocumentFormat.EML,
56
+ }
57
+
58
+ _TEXT_FORMATS: frozenset[DocumentFormat] = frozenset(
59
+ {
60
+ DocumentFormat.TXT,
61
+ DocumentFormat.HTML,
62
+ DocumentFormat.MARKDOWN,
63
+ DocumentFormat.EML,
64
+ }
65
+ )
66
+ _EML_SNIFF_SECONDARY_HEADERS: frozenset[str] = frozenset(
67
+ {"subject", "date", "to", "mime-version", "content-type"}
68
+ )
69
+ _STREAM_CHUNK_BYTES: int = 65_536
70
+
71
+
72
+ @dataclass(frozen=True, slots=True)
73
+ class DocumentLoadResult:
74
+ """Result of document loading and text preparation."""
75
+
76
+ source: SourceMetadata
77
+ document: PreparedDocument | None = None
78
+ errors: list[DiagnosticIssue] = field(default_factory=list)
79
+ warnings: list[DiagnosticIssue] = field(default_factory=list)
80
+
81
+
82
+ def _sniff_extensionless_text_format(raw: bytes) -> DocumentFormat:
83
+ """Conservatively sniff unambiguous HTML or RFC 5322 EML on extensionless text payloads."""
84
+ decoded = _decode_text_bytes(raw[:4096])
85
+ if not decoded:
86
+ return DocumentFormat.TXT
87
+ stripped = decoded.lstrip("\ufeff \t\r\n")
88
+ lower_head = stripped[:64].lower()
89
+ if lower_head.startswith("<!doctype html") or lower_head.startswith("<html"):
90
+ return DocumentFormat.HTML
91
+
92
+ header_section = stripped.split("\r\n\r\n", 1)[0].split("\n\n", 1)[0]
93
+ header_names: set[str] = set()
94
+ valid_headers = True
95
+ for line in header_section.splitlines():
96
+ if not line:
97
+ continue
98
+ if line[0] in (" ", "\t") and header_names:
99
+ continue
100
+ if ":" not in line:
101
+ valid_headers = False
102
+ break
103
+ key = line.split(":", 1)[0].strip().lower()
104
+ if not key or any(not (ch.isalnum() or ch == "-") for ch in key):
105
+ valid_headers = False
106
+ break
107
+ header_names.add(key)
108
+
109
+ if valid_headers and "from" in header_names and (header_names & _EML_SNIFF_SECONDARY_HEADERS):
110
+ return DocumentFormat.EML
111
+
112
+ return DocumentFormat.TXT
113
+
114
+
115
+ def _detect_format(
116
+ raw: bytes,
117
+ extension: str,
118
+ media_type_hint: str | None = None,
119
+ ) -> tuple[DocumentFormat | None, str | None]:
120
+ """Detect actual document format from magic bytes, signatures, and safe hints."""
121
+ if raw.startswith(b"%PDF-"):
122
+ return DocumentFormat.PDF, None
123
+
124
+ if raw.startswith((b"PK\x03\x04", b"PK\x05\x06", b"PK\x07\x08")):
125
+ try:
126
+ with zipfile.ZipFile(io.BytesIO(raw), "r") as zf:
127
+ if "word/document.xml" in zf.namelist():
128
+ return DocumentFormat.DOCX, None
129
+ return None, "ZIP archive does not contain a DOCX document (word/document.xml)."
130
+ except zipfile.BadZipFile:
131
+ if extension == ".docx":
132
+ return DocumentFormat.DOCX, None
133
+ return None, "Corrupted archive or unsupported binary container."
134
+
135
+ if extension == ".pdf":
136
+ return None, "File has .pdf extension but does not start with a valid %PDF header."
137
+ if extension == ".docx":
138
+ return None, "File has .docx extension but is not a valid DOCX archive."
139
+
140
+ ext_format = _EXTENSION_TO_FORMAT.get(extension)
141
+ if ext_format is not None:
142
+ if _looks_binary(raw):
143
+ return (
144
+ None,
145
+ f"Input file with extension {extension!r} appears to contain binary data.",
146
+ )
147
+ return ext_format, None
148
+
149
+ if extension:
150
+ return None, f"Unsupported document format extension: {extension!r}."
151
+
152
+ # Extensionless payload: reject binary bytes before considering text formats
153
+ if _looks_binary(raw):
154
+ return None, "Input payload appears to contain unsupported binary data."
155
+
156
+ if media_type_hint is not None:
157
+ hinted = SUPPORTED_MEDIA_TYPES.get(media_type_hint)
158
+ if hinted in _TEXT_FORMATS:
159
+ return hinted, None
160
+ if hinted is not None:
161
+ return (
162
+ None,
163
+ f"Caller media_type hint {media_type_hint!r} does not match detected content.",
164
+ )
165
+
166
+ return _sniff_extensionless_text_format(raw), None
167
+
168
+
169
+ def _dispatch_parser(
170
+ detected_format: DocumentFormat,
171
+ raw: bytes,
172
+ source: SourceMetadata,
173
+ limits: DocumentLimits,
174
+ ) -> ParseResult:
175
+ if detected_format == DocumentFormat.TXT:
176
+ return parse_txt_bytes(raw, source, limits)
177
+ if detected_format == DocumentFormat.PDF:
178
+ return parse_pdf_bytes(raw, source, limits)
179
+ if detected_format == DocumentFormat.DOCX:
180
+ return parse_docx_bytes(raw, source, limits)
181
+ if detected_format == DocumentFormat.HTML:
182
+ return parse_html_bytes(raw, source, limits)
183
+ if detected_format == DocumentFormat.MARKDOWN:
184
+ return parse_markdown_bytes(raw, source, limits)
185
+ return parse_eml_bytes(raw, source, limits)
186
+
187
+
188
+ def read_stream_bounded(
189
+ stream: BinaryIO,
190
+ *,
191
+ max_bytes: int,
192
+ ) -> tuple[bytes | None, DiagnosticIssue | None]:
193
+ """Read binary stream incrementally up to ``max_bytes + 1`` bytes without closing it."""
194
+ if max_bytes < 1:
195
+ raise ConfigurationError("max_bytes must be a positive integer.")
196
+
197
+ chunks: list[bytes] = []
198
+ total_read = 0
199
+ cap = max_bytes + 1
200
+
201
+ while total_read < cap:
202
+ to_read = min(_STREAM_CHUNK_BYTES, cap - total_read)
203
+ try:
204
+ chunk = stream.read(to_read)
205
+ except (OSError, ValueError):
206
+ return None, DiagnosticIssue(
207
+ code="invalid_input",
208
+ severity=IssueSeverity.ERROR,
209
+ stage=PipelineStage.INPUT,
210
+ message="Failed to read bytes from input binary stream.",
211
+ )
212
+
213
+ if chunk is None:
214
+ break
215
+ if isinstance(chunk, str) or not isinstance(chunk, (bytes, bytearray, memoryview)):
216
+ return None, DiagnosticIssue(
217
+ code="invalid_input",
218
+ severity=IssueSeverity.ERROR,
219
+ stage=PipelineStage.INPUT,
220
+ message="Input stream did not yield binary bytes.",
221
+ )
222
+
223
+ raw_chunk = bytes(chunk)
224
+ if not raw_chunk:
225
+ break
226
+
227
+ chunks.append(raw_chunk)
228
+ total_read += len(raw_chunk)
229
+
230
+ if total_read > max_bytes:
231
+ return None, DiagnosticIssue(
232
+ code="resource_limit_exceeded",
233
+ severity=IssueSeverity.ERROR,
234
+ stage=PipelineStage.INPUT,
235
+ message=(
236
+ f"Input stream exceeds configured max_file_bytes limit ({max_bytes} bytes)."
237
+ ),
238
+ )
239
+
240
+ return b"".join(chunks), None
241
+
242
+
243
+ def _load_prepared_from_bytes(
244
+ raw: bytes,
245
+ *,
246
+ doc_id: str,
247
+ safe_filename: str | None,
248
+ limits: DocumentLimits,
249
+ media_type_hint: str | None = None,
250
+ ) -> DocumentLoadResult:
251
+ """Validate size, sniff magic bytes, reconcile media_type hint, and parse bytes in memory."""
252
+ base_source = SourceMetadata(document_id=doc_id, filename=safe_filename, media_type=None)
253
+
254
+ if len(raw) == 0:
255
+ return DocumentLoadResult(
256
+ source=base_source,
257
+ errors=[
258
+ DiagnosticIssue(
259
+ code="empty_document",
260
+ severity=IssueSeverity.ERROR,
261
+ stage=PipelineStage.INPUT,
262
+ message="Input document is empty (zero bytes).",
263
+ )
264
+ ],
265
+ )
266
+
267
+ if len(raw) > limits.max_file_bytes:
268
+ return DocumentLoadResult(
269
+ source=base_source,
270
+ errors=[
271
+ DiagnosticIssue(
272
+ code="resource_limit_exceeded",
273
+ severity=IssueSeverity.ERROR,
274
+ stage=PipelineStage.INPUT,
275
+ message=(
276
+ f"Input document size ({len(raw)} bytes) exceeds configured "
277
+ f"max_file_bytes limit ({limits.max_file_bytes} bytes)."
278
+ ),
279
+ )
280
+ ],
281
+ )
282
+
283
+ ext = Path(safe_filename).suffix.lower() if safe_filename else ""
284
+ detected_format, detect_err = _detect_format(raw, ext, media_type_hint=media_type_hint)
285
+ if detected_format is None:
286
+ return DocumentLoadResult(
287
+ source=base_source,
288
+ errors=[
289
+ DiagnosticIssue(
290
+ code="unsupported_format",
291
+ severity=IssueSeverity.ERROR,
292
+ stage=PipelineStage.INPUT,
293
+ message=detect_err or "Unsupported document format.",
294
+ )
295
+ ],
296
+ )
297
+
298
+ if media_type_hint is not None:
299
+ expected_format = SUPPORTED_MEDIA_TYPES.get(media_type_hint)
300
+ if expected_format is not None and detected_format != expected_format:
301
+ return DocumentLoadResult(
302
+ source=base_source,
303
+ errors=[
304
+ DiagnosticIssue(
305
+ code="unsupported_format",
306
+ severity=IssueSeverity.ERROR,
307
+ stage=PipelineStage.INPUT,
308
+ message=(
309
+ f"Caller media_type hint {media_type_hint!r} does not match "
310
+ f"detected content format {_MEDIA_TYPES[detected_format]!r}."
311
+ ),
312
+ )
313
+ ],
314
+ )
315
+
316
+ warnings: list[DiagnosticIssue] = []
317
+ ext_format = _EXTENSION_TO_FORMAT.get(ext)
318
+ if ext_format is not None and ext_format != detected_format:
319
+ warnings.append(
320
+ DiagnosticIssue(
321
+ code="extension_mismatch",
322
+ severity=IssueSeverity.WARNING,
323
+ stage=PipelineStage.INPUT,
324
+ message=(
325
+ f"File extension {ext!r} does not match detected content format "
326
+ f"{detected_format.value!r}; processed using detected format."
327
+ ),
328
+ )
329
+ )
330
+
331
+ source = SourceMetadata(
332
+ document_id=doc_id,
333
+ filename=safe_filename,
334
+ media_type=_MEDIA_TYPES[detected_format],
335
+ )
336
+
337
+ parsed = _dispatch_parser(detected_format, raw, source, limits)
338
+
339
+ return DocumentLoadResult(
340
+ source=source,
341
+ document=parsed.document,
342
+ errors=list(parsed.errors),
343
+ warnings=warnings + list(parsed.warnings),
344
+ )
345
+
346
+
347
+ def load_document(
348
+ path: str | Path,
349
+ *,
350
+ limits: DocumentLimits | None = None,
351
+ document_id: str | None = None,
352
+ filename_override: str | None = None,
353
+ media_type_hint: str | None = None,
354
+ ) -> DocumentLoadResult:
355
+ """Inspect, validate, and parse a single TXT, text-based PDF, or DOCX document safely."""
356
+ active_limits = limits or DocumentLimits()
357
+ doc_path = Path(path)
358
+ doc_id = document_id.strip() if document_id and document_id.strip() else str(uuid4())
359
+ # Basename only to avoid leaking local host paths in canonical metadata
360
+ safe_filename = (
361
+ filename_override
362
+ if filename_override is not None
363
+ else (doc_path.name if doc_path.name else None)
364
+ )
365
+ base_source = SourceMetadata(document_id=doc_id, filename=safe_filename, media_type=None)
366
+
367
+ if "\x00" in str(path):
368
+ return DocumentLoadResult(
369
+ source=base_source,
370
+ errors=[
371
+ DiagnosticIssue(
372
+ code="invalid_input",
373
+ severity=IssueSeverity.ERROR,
374
+ stage=PipelineStage.INPUT,
375
+ message="Document path contains invalid null byte.",
376
+ )
377
+ ],
378
+ )
379
+
380
+ try:
381
+ exists = doc_path.exists()
382
+ except OSError:
383
+ exists = False
384
+
385
+ if not exists:
386
+ return DocumentLoadResult(
387
+ source=base_source,
388
+ errors=[
389
+ DiagnosticIssue(
390
+ code="file_not_found",
391
+ severity=IssueSeverity.ERROR,
392
+ stage=PipelineStage.INPUT,
393
+ message="Input document path does not exist.",
394
+ )
395
+ ],
396
+ )
397
+
398
+ if doc_path.is_dir():
399
+ return DocumentLoadResult(
400
+ source=base_source,
401
+ errors=[
402
+ DiagnosticIssue(
403
+ code="invalid_input",
404
+ severity=IssueSeverity.ERROR,
405
+ stage=PipelineStage.INPUT,
406
+ message="Input path refers to a directory rather than a regular file.",
407
+ )
408
+ ],
409
+ )
410
+
411
+ if not doc_path.is_file():
412
+ return DocumentLoadResult(
413
+ source=base_source,
414
+ errors=[
415
+ DiagnosticIssue(
416
+ code="invalid_input",
417
+ severity=IssueSeverity.ERROR,
418
+ stage=PipelineStage.INPUT,
419
+ message="Input path is not a regular readable file.",
420
+ )
421
+ ],
422
+ )
423
+
424
+ if not os.access(doc_path, os.R_OK):
425
+ return DocumentLoadResult(
426
+ source=base_source,
427
+ errors=[
428
+ DiagnosticIssue(
429
+ code="permission_denied",
430
+ severity=IssueSeverity.ERROR,
431
+ stage=PipelineStage.INPUT,
432
+ message="Input document cannot be read due to file permissions.",
433
+ )
434
+ ],
435
+ )
436
+
437
+ try:
438
+ file_size = doc_path.stat().st_size
439
+ except OSError:
440
+ return DocumentLoadResult(
441
+ source=base_source,
442
+ errors=[
443
+ DiagnosticIssue(
444
+ code="invalid_input",
445
+ severity=IssueSeverity.ERROR,
446
+ stage=PipelineStage.INPUT,
447
+ message="Unable to inspect input document file metadata.",
448
+ )
449
+ ],
450
+ )
451
+
452
+ if file_size == 0:
453
+ return DocumentLoadResult(
454
+ source=base_source,
455
+ errors=[
456
+ DiagnosticIssue(
457
+ code="empty_document",
458
+ severity=IssueSeverity.ERROR,
459
+ stage=PipelineStage.INPUT,
460
+ message="Input document is empty (zero bytes).",
461
+ )
462
+ ],
463
+ )
464
+
465
+ if file_size > active_limits.max_file_bytes:
466
+ return DocumentLoadResult(
467
+ source=base_source,
468
+ errors=[
469
+ DiagnosticIssue(
470
+ code="resource_limit_exceeded",
471
+ severity=IssueSeverity.ERROR,
472
+ stage=PipelineStage.INPUT,
473
+ message=(
474
+ f"Input document size ({file_size} bytes) exceeds configured "
475
+ f"max_file_bytes limit ({active_limits.max_file_bytes} bytes)."
476
+ ),
477
+ )
478
+ ],
479
+ )
480
+
481
+ try:
482
+ raw = doc_path.read_bytes()
483
+ except PermissionError:
484
+ return DocumentLoadResult(
485
+ source=base_source,
486
+ errors=[
487
+ DiagnosticIssue(
488
+ code="permission_denied",
489
+ severity=IssueSeverity.ERROR,
490
+ stage=PipelineStage.INPUT,
491
+ message="Permission denied while reading input document.",
492
+ )
493
+ ],
494
+ )
495
+ except OSError:
496
+ return DocumentLoadResult(
497
+ source=base_source,
498
+ errors=[
499
+ DiagnosticIssue(
500
+ code="invalid_input",
501
+ severity=IssueSeverity.ERROR,
502
+ stage=PipelineStage.INPUT,
503
+ message="Failed to read input document bytes.",
504
+ )
505
+ ],
506
+ )
507
+
508
+ if len(raw) > active_limits.max_file_bytes:
509
+ return DocumentLoadResult(
510
+ source=base_source,
511
+ errors=[
512
+ DiagnosticIssue(
513
+ code="resource_limit_exceeded",
514
+ severity=IssueSeverity.ERROR,
515
+ stage=PipelineStage.INPUT,
516
+ message="Input document grew beyond configured max_file_bytes while reading.",
517
+ )
518
+ ],
519
+ )
520
+
521
+ return _load_prepared_from_bytes(
522
+ raw,
523
+ doc_id=doc_id,
524
+ safe_filename=safe_filename,
525
+ limits=active_limits,
526
+ media_type_hint=media_type_hint,
527
+ )
528
+
529
+
530
+ def load_document_input(
531
+ doc_input: DocumentInput,
532
+ *,
533
+ limits: DocumentLimits | None = None,
534
+ document_id: str | None = None,
535
+ ) -> DocumentLoadResult:
536
+ """Load and prepare any DocumentInput (path, bytes, plain text, or binary stream) safely."""
537
+ if not isinstance(doc_input, DocumentInput):
538
+ raise ConfigurationError("doc_input must be a DocumentInput instance.")
539
+
540
+ active_limits = limits or DocumentLimits()
541
+ if document_id is not None:
542
+ if not isinstance(document_id, str) or not document_id.strip():
543
+ raise ConfigurationError("document_id must be a non-empty string or None.")
544
+ resolved_doc_id = document_id.strip()
545
+ elif doc_input.document_id is not None:
546
+ resolved_doc_id = doc_input.document_id
547
+ else:
548
+ resolved_doc_id = str(uuid4())
549
+
550
+ safe_filename = sanitize_filename(doc_input.filename)
551
+
552
+ if doc_input.kind == DocumentInputKind.PATH:
553
+ if doc_input.path is None:
554
+ raise ConfigurationError("PATH DocumentInput is missing a path.")
555
+ return load_document(
556
+ doc_input.path,
557
+ limits=active_limits,
558
+ document_id=resolved_doc_id,
559
+ filename_override=safe_filename,
560
+ media_type_hint=doc_input.media_type,
561
+ )
562
+
563
+ if doc_input.kind == DocumentInputKind.BYTES:
564
+ raw_bytes = doc_input.content if doc_input.content is not None else b""
565
+ return _load_prepared_from_bytes(
566
+ raw_bytes,
567
+ doc_id=resolved_doc_id,
568
+ safe_filename=safe_filename,
569
+ limits=active_limits,
570
+ media_type_hint=doc_input.media_type,
571
+ )
572
+
573
+ if doc_input.kind == DocumentInputKind.TEXT:
574
+ raw_text_bytes = (doc_input.text or "").encode("utf-8")
575
+ empty_source = SourceMetadata(
576
+ document_id=resolved_doc_id,
577
+ filename=safe_filename,
578
+ media_type=None,
579
+ )
580
+ if len(raw_text_bytes) == 0:
581
+ return DocumentLoadResult(
582
+ source=empty_source,
583
+ errors=[
584
+ DiagnosticIssue(
585
+ code="empty_document",
586
+ severity=IssueSeverity.ERROR,
587
+ stage=PipelineStage.INPUT,
588
+ message="Input plain-text document is empty.",
589
+ )
590
+ ],
591
+ )
592
+ if len(raw_text_bytes) > active_limits.max_file_bytes:
593
+ return DocumentLoadResult(
594
+ source=empty_source,
595
+ errors=[
596
+ DiagnosticIssue(
597
+ code="resource_limit_exceeded",
598
+ severity=IssueSeverity.ERROR,
599
+ stage=PipelineStage.INPUT,
600
+ message=(
601
+ f"Input plain-text size ({len(raw_text_bytes)} bytes) exceeds "
602
+ f"configured max_file_bytes limit ({active_limits.max_file_bytes} "
603
+ "bytes)."
604
+ ),
605
+ )
606
+ ],
607
+ )
608
+
609
+ target_format = DocumentFormat.TXT
610
+ if doc_input.media_type is not None:
611
+ hinted_fmt = SUPPORTED_MEDIA_TYPES.get(doc_input.media_type)
612
+ if hinted_fmt not in _TEXT_FORMATS:
613
+ return DocumentLoadResult(
614
+ source=empty_source,
615
+ errors=[
616
+ DiagnosticIssue(
617
+ code="unsupported_format",
618
+ severity=IssueSeverity.ERROR,
619
+ stage=PipelineStage.INPUT,
620
+ message=(
621
+ f"Binary media_type {doc_input.media_type!r} is not supported "
622
+ "for DocumentInput.from_text(); use DocumentInput.from_bytes()."
623
+ ),
624
+ )
625
+ ],
626
+ )
627
+ target_format = hinted_fmt
628
+ elif safe_filename is not None:
629
+ ext_fmt = _EXTENSION_TO_FORMAT.get(Path(safe_filename).suffix.lower())
630
+ if ext_fmt in _TEXT_FORMATS:
631
+ target_format = ext_fmt
632
+
633
+ base_source = SourceMetadata(
634
+ document_id=resolved_doc_id,
635
+ filename=safe_filename,
636
+ media_type=_MEDIA_TYPES[target_format],
637
+ )
638
+ parsed = _dispatch_parser(target_format, raw_text_bytes, base_source, active_limits)
639
+ return DocumentLoadResult(
640
+ source=base_source,
641
+ document=parsed.document,
642
+ errors=list(parsed.errors),
643
+ warnings=list(parsed.warnings),
644
+ )
645
+
646
+ # DocumentInputKind.STREAM
647
+ if doc_input.stream is None:
648
+ raise ConfigurationError("STREAM DocumentInput is missing a binary stream.")
649
+ raw_stream_bytes, read_err = read_stream_bounded(
650
+ doc_input.stream,
651
+ max_bytes=active_limits.max_file_bytes,
652
+ )
653
+ if read_err is not None or raw_stream_bytes is None:
654
+ err_issue = read_err or DiagnosticIssue(
655
+ code="invalid_input",
656
+ severity=IssueSeverity.ERROR,
657
+ stage=PipelineStage.INPUT,
658
+ message="Failed to read input binary stream.",
659
+ )
660
+ return DocumentLoadResult(
661
+ source=SourceMetadata(
662
+ document_id=resolved_doc_id,
663
+ filename=safe_filename,
664
+ media_type=None,
665
+ ),
666
+ errors=[err_issue],
667
+ )
668
+
669
+ return _load_prepared_from_bytes(
670
+ raw_stream_bytes,
671
+ doc_id=resolved_doc_id,
672
+ safe_filename=safe_filename,
673
+ limits=active_limits,
674
+ media_type_hint=doc_input.media_type,
675
+ )