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,225 @@
1
+ """Hardened stdlib-only Markdown parser with ATX/Setext heading and line/paragraph provenance."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+
7
+ from structa_maestro.config import DocumentLimits
8
+ from structa_maestro.contracts.enums import DocumentFormat, IssueSeverity, PipelineStage
9
+ from structa_maestro.contracts.models import DiagnosticIssue, SourceMetadata
10
+ from structa_maestro.documents.models import DocumentSegment, PreparedDocument
11
+ from structa_maestro.documents.normalization import normalize_document_text
12
+ from structa_maestro.documents.txt_parser import ParseResult, _decode_text_bytes, _looks_binary
13
+
14
+ _ATX_HEADING_RE = re.compile(r"^\s{0,3}(#{1,6})\s+(.+?)\s*#*\s*$")
15
+ _SETEXT_UNDERLINE_RE = re.compile(r"^\s{0,3}(=+|-+)\s*$")
16
+ _FENCE_RE = re.compile(r"^\s{0,3}(`{3,}|~{3,})")
17
+
18
+
19
+ def parse_markdown_bytes(
20
+ raw: bytes,
21
+ source: SourceMetadata,
22
+ limits: DocumentLimits,
23
+ ) -> ParseResult:
24
+ """Parse raw Markdown bytes into a PreparedDocument with section, paragraph & line locations."""
25
+ if len(raw) == 0:
26
+ return ParseResult(
27
+ document=None,
28
+ errors=(
29
+ DiagnosticIssue(
30
+ code="empty_document",
31
+ severity=IssueSeverity.ERROR,
32
+ stage=PipelineStage.DOCUMENT_PROCESSING,
33
+ message="Input Markdown document is empty (zero bytes).",
34
+ ),
35
+ ),
36
+ )
37
+
38
+ if _looks_binary(raw):
39
+ return ParseResult(
40
+ document=None,
41
+ errors=(
42
+ DiagnosticIssue(
43
+ code="unsupported_format",
44
+ severity=IssueSeverity.ERROR,
45
+ stage=PipelineStage.DOCUMENT_PROCESSING,
46
+ message="Input file appears to contain binary data rather than Markdown.",
47
+ ),
48
+ ),
49
+ )
50
+
51
+ decoded = _decode_text_bytes(raw)
52
+ if decoded is None:
53
+ return ParseResult(
54
+ document=None,
55
+ errors=(
56
+ DiagnosticIssue(
57
+ code="decoding_error",
58
+ severity=IssueSeverity.ERROR,
59
+ stage=PipelineStage.DOCUMENT_PROCESSING,
60
+ message="Unable to decode Markdown document with supported text encodings.",
61
+ ),
62
+ ),
63
+ )
64
+
65
+ normalized = normalize_document_text(decoded)
66
+ if len(normalized.encode("utf-8")) > limits.max_decompressed_bytes:
67
+ return ParseResult(
68
+ document=None,
69
+ errors=(
70
+ DiagnosticIssue(
71
+ code="resource_limit_exceeded",
72
+ severity=IssueSeverity.ERROR,
73
+ stage=PipelineStage.DOCUMENT_PROCESSING,
74
+ message=(
75
+ "Prepared Markdown text exceeds configured max_decompressed_bytes limit."
76
+ ),
77
+ ),
78
+ ),
79
+ )
80
+
81
+ if not normalized.strip():
82
+ return ParseResult(
83
+ document=None,
84
+ errors=(
85
+ DiagnosticIssue(
86
+ code="no_extractable_text",
87
+ severity=IssueSeverity.ERROR,
88
+ stage=PipelineStage.DOCUMENT_PROCESSING,
89
+ message="Markdown document contains no extractable text (whitespace only).",
90
+ ),
91
+ ),
92
+ )
93
+
94
+ lines = normalized.split("\n")
95
+ line_offsets: list[tuple[int, int]] = []
96
+ pos = 0
97
+ for line in lines:
98
+ line_offsets.append((pos, pos + len(line)))
99
+ pos += len(line) + 1
100
+
101
+ segments: list[DocumentSegment] = []
102
+ current_heading: str | None = None
103
+ in_fence_char: str | None = None
104
+ in_fence_len = 0
105
+ para_idx = 0
106
+
107
+ block_start_idx: int | None = None
108
+
109
+ def _flush_block(end_idx: int) -> None:
110
+ nonlocal block_start_idx, para_idx
111
+ if block_start_idx is None:
112
+ return
113
+ start_char = line_offsets[block_start_idx][0]
114
+ end_char = line_offsets[end_idx][1]
115
+ text_slice = normalized[start_char:end_char]
116
+ if text_slice.strip():
117
+ para_idx += 1
118
+ segments.append(
119
+ DocumentSegment(
120
+ text=text_slice,
121
+ char_start=start_char,
122
+ char_end=end_char,
123
+ paragraph=para_idx,
124
+ line_start=block_start_idx + 1,
125
+ line_end=end_idx + 1,
126
+ heading=current_heading,
127
+ )
128
+ )
129
+ block_start_idx = None
130
+
131
+ idx = 0
132
+ total_lines = len(lines)
133
+ while idx < total_lines:
134
+ line = lines[idx]
135
+
136
+ # Track fenced code blocks (``` or ~~~) so '#' lines inside code are never headings
137
+ fence_match = _FENCE_RE.match(line)
138
+ if fence_match is not None:
139
+ marker = fence_match.group(1)
140
+ fchar, flen = marker[0], len(marker)
141
+ if in_fence_char is None:
142
+ in_fence_char = fchar
143
+ in_fence_len = flen
144
+ if block_start_idx is None:
145
+ block_start_idx = idx
146
+ elif fchar == in_fence_char and flen >= in_fence_len and not line.strip(fchar + " \t"):
147
+ in_fence_char = None
148
+ in_fence_len = 0
149
+ idx += 1
150
+ continue
151
+
152
+ if in_fence_char is not None:
153
+ idx += 1
154
+ continue
155
+
156
+ if not line.strip():
157
+ _flush_block(idx - 1)
158
+ idx += 1
159
+ continue
160
+
161
+ # ATX heading (# .. ######)
162
+ atx = _ATX_HEADING_RE.match(line)
163
+ if atx is not None:
164
+ _flush_block(idx - 1)
165
+ heading_text = atx.group(2).strip()
166
+ if heading_text:
167
+ current_heading = heading_text
168
+ para_idx += 1
169
+ start_char, end_char = line_offsets[idx]
170
+ segments.append(
171
+ DocumentSegment(
172
+ text=line,
173
+ char_start=start_char,
174
+ char_end=end_char,
175
+ paragraph=para_idx,
176
+ line_start=idx + 1,
177
+ line_end=idx + 1,
178
+ heading=current_heading,
179
+ )
180
+ )
181
+ idx += 1
182
+ continue
183
+
184
+ # Setext heading (current non-empty line followed by === or ---)
185
+ if (
186
+ idx + 1 < total_lines
187
+ and _SETEXT_UNDERLINE_RE.match(lines[idx + 1]) is not None
188
+ and not line.lstrip().startswith(("-", "*", "+", ">", "|"))
189
+ ):
190
+ _flush_block(idx - 1)
191
+ heading_text = line.strip()
192
+ if heading_text:
193
+ current_heading = heading_text
194
+ para_idx += 1
195
+ start_char = line_offsets[idx][0]
196
+ end_char = line_offsets[idx + 1][1]
197
+ segments.append(
198
+ DocumentSegment(
199
+ text=normalized[start_char:end_char],
200
+ char_start=start_char,
201
+ char_end=end_char,
202
+ paragraph=para_idx,
203
+ line_start=idx + 1,
204
+ line_end=idx + 2,
205
+ heading=current_heading,
206
+ )
207
+ )
208
+ idx += 2
209
+ continue
210
+
211
+ if block_start_idx is None:
212
+ block_start_idx = idx
213
+ idx += 1
214
+
215
+ _flush_block(total_lines - 1)
216
+
217
+ return ParseResult(
218
+ document=PreparedDocument(
219
+ source=source,
220
+ format=DocumentFormat.MARKDOWN,
221
+ full_text=normalized,
222
+ segments=tuple(segments),
223
+ page_count=None,
224
+ )
225
+ )
@@ -0,0 +1,33 @@
1
+ """Internal prepared document models (data-model.md Section 2.3)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+
7
+ from structa_maestro.contracts.enums import DocumentFormat
8
+ from structa_maestro.contracts.models import SourceMetadata
9
+
10
+
11
+ @dataclass(frozen=True, slots=True)
12
+ class DocumentSegment:
13
+ """Normalized text slice carrying source location metadata (data-model.md Section 2.3)."""
14
+
15
+ text: str
16
+ char_start: int
17
+ char_end: int
18
+ page: int | None = None
19
+ paragraph: int | None = None
20
+ line_start: int | None = None
21
+ line_end: int | None = None
22
+ heading: str | None = None
23
+
24
+
25
+ @dataclass(frozen=True, slots=True)
26
+ class PreparedDocument:
27
+ """Internal representation of parsed document text and structural location map."""
28
+
29
+ source: SourceMetadata
30
+ format: DocumentFormat
31
+ full_text: str
32
+ segments: tuple[DocumentSegment, ...] = field(default_factory=tuple)
33
+ page_count: int | None = None
@@ -0,0 +1,24 @@
1
+ """Lossless permitted text normalization preserving Unicode, whitespace, and leading zeros."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+
7
+ # Strip ASCII control characters other than tab (\t), newline (\n), and carriage return (\r)
8
+ _DANGEROUS_CONTROL_RE = re.compile(r"[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]")
9
+
10
+
11
+ def normalize_document_text(text: str) -> str:
12
+ """Normalize line endings and non-breaking spaces without corrupting meaningful content."""
13
+ normalized = text.replace("\r\n", "\n").replace("\r", "\n")
14
+ normalized = normalized.replace("\u00a0", " ")
15
+ normalized = _DANGEROUS_CONTROL_RE.sub("", normalized)
16
+ return normalized
17
+
18
+
19
+ def normalize_extracted_string(value: str) -> str:
20
+ """Trim surrounding whitespace while preserving internal whitespace and leading zeros."""
21
+ normalized = value.replace("\r\n", "\n").replace("\r", "\n")
22
+ normalized = normalized.replace("\u00a0", " ")
23
+ normalized = _DANGEROUS_CONTROL_RE.sub("", normalized)
24
+ return normalized.strip()
@@ -0,0 +1,186 @@
1
+ """Text-based PDF parser using pypdf with page limits, encryption, and image-only detection."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import io
6
+
7
+ from pypdf import PdfReader
8
+ from pypdf.errors import PdfReadError
9
+
10
+ from structa_maestro.config import DocumentLimits
11
+ from structa_maestro.contracts.enums import DocumentFormat, IssueSeverity, PipelineStage
12
+ from structa_maestro.contracts.models import DiagnosticIssue, SourceMetadata
13
+ from structa_maestro.documents.models import DocumentSegment, PreparedDocument
14
+ from structa_maestro.documents.normalization import normalize_document_text
15
+ from structa_maestro.documents.txt_parser import ParseResult
16
+
17
+
18
+ def parse_pdf_bytes(
19
+ raw: bytes,
20
+ source: SourceMetadata,
21
+ limits: DocumentLimits,
22
+ ) -> ParseResult:
23
+ """Parse text-based PDF bytes enforcing DocumentLimits.max_pages and max_decompressed_bytes."""
24
+ if len(raw) == 0:
25
+ return ParseResult(
26
+ document=None,
27
+ errors=(
28
+ DiagnosticIssue(
29
+ code="empty_document",
30
+ severity=IssueSeverity.ERROR,
31
+ stage=PipelineStage.DOCUMENT_PROCESSING,
32
+ message="Input PDF document is empty (zero bytes).",
33
+ ),
34
+ ),
35
+ )
36
+
37
+ try:
38
+ reader = PdfReader(io.BytesIO(raw), strict=False)
39
+ except (PdfReadError, Exception):
40
+ return ParseResult(
41
+ document=None,
42
+ errors=(
43
+ DiagnosticIssue(
44
+ code="corrupted_document",
45
+ severity=IssueSeverity.ERROR,
46
+ stage=PipelineStage.DOCUMENT_PROCESSING,
47
+ message="PDF document is corrupted or unreadable.",
48
+ ),
49
+ ),
50
+ )
51
+
52
+ if reader.is_encrypted:
53
+ return ParseResult(
54
+ document=None,
55
+ errors=(
56
+ DiagnosticIssue(
57
+ code="corrupted_document",
58
+ severity=IssueSeverity.ERROR,
59
+ stage=PipelineStage.DOCUMENT_PROCESSING,
60
+ message="Encrypted PDF documents are not supported without prior decryption.",
61
+ ),
62
+ ),
63
+ )
64
+
65
+ try:
66
+ page_count = len(reader.pages)
67
+ except Exception:
68
+ return ParseResult(
69
+ document=None,
70
+ errors=(
71
+ DiagnosticIssue(
72
+ code="corrupted_document",
73
+ severity=IssueSeverity.ERROR,
74
+ stage=PipelineStage.DOCUMENT_PROCESSING,
75
+ message="Unable to read PDF page structure.",
76
+ ),
77
+ ),
78
+ )
79
+
80
+ if page_count == 0:
81
+ return ParseResult(
82
+ document=None,
83
+ errors=(
84
+ DiagnosticIssue(
85
+ code="empty_document",
86
+ severity=IssueSeverity.ERROR,
87
+ stage=PipelineStage.DOCUMENT_PROCESSING,
88
+ message="PDF document contains zero pages.",
89
+ ),
90
+ ),
91
+ )
92
+
93
+ if page_count > limits.max_pages:
94
+ return ParseResult(
95
+ document=None,
96
+ errors=(
97
+ DiagnosticIssue(
98
+ code="resource_limit_exceeded",
99
+ severity=IssueSeverity.ERROR,
100
+ stage=PipelineStage.DOCUMENT_PROCESSING,
101
+ message=(
102
+ f"PDF page count ({page_count}) exceeds configured "
103
+ f"max_pages limit ({limits.max_pages})."
104
+ ),
105
+ ),
106
+ ),
107
+ )
108
+
109
+ segments: list[DocumentSegment] = []
110
+ full_parts: list[str] = []
111
+ warnings: list[DiagnosticIssue] = []
112
+ cumulative_bytes = 0
113
+ offset = 0
114
+
115
+ for page_num, page in enumerate(reader.pages, start=1):
116
+ try:
117
+ raw_page_text = page.extract_text() or ""
118
+ except Exception:
119
+ warnings.append(
120
+ DiagnosticIssue(
121
+ code="partial_page_parse_failure",
122
+ severity=IssueSeverity.WARNING,
123
+ stage=PipelineStage.DOCUMENT_PROCESSING,
124
+ message=f"Failed to extract text from PDF page {page_num}.",
125
+ )
126
+ )
127
+ raw_page_text = ""
128
+
129
+ normalized = normalize_document_text(raw_page_text).strip()
130
+ cumulative_bytes += len(normalized.encode("utf-8"))
131
+ if cumulative_bytes > limits.max_decompressed_bytes:
132
+ return ParseResult(
133
+ document=None,
134
+ errors=(
135
+ DiagnosticIssue(
136
+ code="resource_limit_exceeded",
137
+ severity=IssueSeverity.ERROR,
138
+ stage=PipelineStage.DOCUMENT_PROCESSING,
139
+ message="Extracted PDF text exceeds configured max_decompressed_bytes.",
140
+ ),
141
+ ),
142
+ )
143
+ if normalized:
144
+ if full_parts:
145
+ offset += 2 # "\n\n" separator
146
+ char_start = offset
147
+ char_end = offset + len(normalized)
148
+ segments.append(
149
+ DocumentSegment(
150
+ text=normalized,
151
+ char_start=char_start,
152
+ char_end=char_end,
153
+ page=page_num,
154
+ )
155
+ )
156
+ full_parts.append(normalized)
157
+ offset = char_end
158
+
159
+ full_text = "\n\n".join(full_parts)
160
+ if not full_text.strip():
161
+ return ParseResult(
162
+ document=None,
163
+ errors=(
164
+ DiagnosticIssue(
165
+ code="no_extractable_text",
166
+ severity=IssueSeverity.ERROR,
167
+ stage=PipelineStage.DOCUMENT_PROCESSING,
168
+ message=(
169
+ "PDF contains no extractable text layer "
170
+ "(image-only or scanned PDFs require OCR, which is outside MVP scope)."
171
+ ),
172
+ ),
173
+ ),
174
+ warnings=tuple(warnings),
175
+ )
176
+
177
+ return ParseResult(
178
+ document=PreparedDocument(
179
+ source=source,
180
+ format=DocumentFormat.PDF,
181
+ full_text=full_text,
182
+ segments=tuple(segments),
183
+ page_count=page_count,
184
+ ),
185
+ warnings=tuple(warnings),
186
+ )
@@ -0,0 +1,169 @@
1
+ """Multi-encoding TXT parser with line-number DocumentSegment tracking."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+
7
+ from structa_maestro.config import DocumentLimits
8
+ from structa_maestro.contracts.enums import DocumentFormat, IssueSeverity, PipelineStage
9
+ from structa_maestro.contracts.models import DiagnosticIssue, SourceMetadata
10
+ from structa_maestro.documents.models import DocumentSegment, PreparedDocument
11
+ from structa_maestro.documents.normalization import normalize_document_text
12
+
13
+ _KNOWN_BINARY_SIGNATURES: tuple[bytes, ...] = (
14
+ b"\x89PNG\r\n\x1a\n",
15
+ b"\xff\xd8\xff",
16
+ b"GIF87a",
17
+ b"GIF89a",
18
+ b"\x7fELF",
19
+ b"MZ",
20
+ b"\x1f\x8b\x08",
21
+ b"Rar!",
22
+ b"7z\xbc\xaf\x27\x1c",
23
+ b"\x00\x00\x01\x00",
24
+ )
25
+
26
+
27
+ @dataclass(frozen=True, slots=True)
28
+ class ParseResult:
29
+ """Outcome of a single document parser invocation."""
30
+
31
+ document: PreparedDocument | None
32
+ errors: tuple[DiagnosticIssue, ...] = ()
33
+ warnings: tuple[DiagnosticIssue, ...] = ()
34
+
35
+
36
+ def _looks_binary(raw: bytes) -> bool:
37
+ for sig in _KNOWN_BINARY_SIGNATURES:
38
+ if raw.startswith(sig):
39
+ return True
40
+ # UTF-16 BOM legitimately contains null bytes
41
+ if raw.startswith((b"\xff\xfe", b"\xfe\xff")):
42
+ return False
43
+ if b"\x00" in raw[:8192]:
44
+ return True
45
+ sample = raw[:4096]
46
+ if not sample:
47
+ return False
48
+ non_text = sum(1 for b in sample if b < 9 or (13 < b < 32) or b == 127)
49
+ return (non_text / len(sample)) > 0.25
50
+
51
+
52
+ def _decode_text_bytes(raw: bytes) -> str | None:
53
+ if raw.startswith((b"\xff\xfe", b"\xfe\xff")):
54
+ try:
55
+ return raw.decode("utf-16")
56
+ except UnicodeDecodeError:
57
+ return None
58
+ if raw.startswith(b"\xef\xbb\xbf"):
59
+ try:
60
+ return raw.decode("utf-8-sig")
61
+ except UnicodeDecodeError:
62
+ return None
63
+ for encoding in ("utf-8", "cp1252", "latin-1"):
64
+ try:
65
+ return raw.decode(encoding)
66
+ except UnicodeDecodeError:
67
+ continue
68
+ return None
69
+
70
+
71
+ def parse_txt_bytes(
72
+ raw: bytes,
73
+ source: SourceMetadata,
74
+ limits: DocumentLimits,
75
+ ) -> ParseResult:
76
+ """Parse raw TXT bytes into a PreparedDocument with 1-indexed line DocumentSegments."""
77
+ if len(raw) == 0:
78
+ return ParseResult(
79
+ document=None,
80
+ errors=(
81
+ DiagnosticIssue(
82
+ code="empty_document",
83
+ severity=IssueSeverity.ERROR,
84
+ stage=PipelineStage.DOCUMENT_PROCESSING,
85
+ message="Input TXT document is empty (zero bytes).",
86
+ ),
87
+ ),
88
+ )
89
+
90
+ if _looks_binary(raw):
91
+ return ParseResult(
92
+ document=None,
93
+ errors=(
94
+ DiagnosticIssue(
95
+ code="unsupported_format",
96
+ severity=IssueSeverity.ERROR,
97
+ stage=PipelineStage.DOCUMENT_PROCESSING,
98
+ message="Input file appears to contain binary data rather than plain text.",
99
+ ),
100
+ ),
101
+ )
102
+
103
+ decoded = _decode_text_bytes(raw)
104
+ if decoded is None:
105
+ return ParseResult(
106
+ document=None,
107
+ errors=(
108
+ DiagnosticIssue(
109
+ code="decoding_error",
110
+ severity=IssueSeverity.ERROR,
111
+ stage=PipelineStage.DOCUMENT_PROCESSING,
112
+ message="Unable to decode TXT document with supported text encodings.",
113
+ ),
114
+ ),
115
+ )
116
+
117
+ normalized = normalize_document_text(decoded)
118
+ if len(normalized.encode("utf-8")) > limits.max_decompressed_bytes:
119
+ return ParseResult(
120
+ document=None,
121
+ errors=(
122
+ DiagnosticIssue(
123
+ code="resource_limit_exceeded",
124
+ severity=IssueSeverity.ERROR,
125
+ stage=PipelineStage.DOCUMENT_PROCESSING,
126
+ message="Prepared TXT text exceeds configured max_decompressed_bytes limit.",
127
+ ),
128
+ ),
129
+ )
130
+
131
+ if not normalized.strip():
132
+ return ParseResult(
133
+ document=None,
134
+ errors=(
135
+ DiagnosticIssue(
136
+ code="empty_document",
137
+ severity=IssueSeverity.ERROR,
138
+ stage=PipelineStage.DOCUMENT_PROCESSING,
139
+ message="TXT document contains no extractable text (whitespace only).",
140
+ ),
141
+ ),
142
+ )
143
+
144
+ segments: list[DocumentSegment] = []
145
+ offset = 0
146
+ lines = normalized.split("\n")
147
+ for idx, line in enumerate(lines, start=1):
148
+ char_start = offset
149
+ char_end = offset + len(line)
150
+ segments.append(
151
+ DocumentSegment(
152
+ text=line,
153
+ char_start=char_start,
154
+ char_end=char_end,
155
+ line_start=idx,
156
+ line_end=idx,
157
+ )
158
+ )
159
+ offset = char_end + 1 # account for '\n'
160
+
161
+ return ParseResult(
162
+ document=PreparedDocument(
163
+ source=source,
164
+ format=DocumentFormat.TXT,
165
+ full_text=normalized,
166
+ segments=tuple(segments),
167
+ page_count=None,
168
+ )
169
+ )