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,360 @@
1
+ """Hardened stdlib-only RFC 5322 (.eml) parser with MIME-bomb limits & safe attachment skipping."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from email import policy as email_policy
6
+ from email.message import EmailMessage, Message
7
+ from email.parser import BytesParser
8
+
9
+ from structa_maestro.config import DocumentLimits
10
+ from structa_maestro.contracts.enums import DocumentFormat, IssueSeverity, PipelineStage
11
+ from structa_maestro.contracts.models import DiagnosticIssue, SourceMetadata
12
+ from structa_maestro.documents.html_parser import parse_html_bytes
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, _decode_text_bytes, _looks_binary
16
+
17
+ MAX_EML_PARTS = 128
18
+ MAX_EML_NESTING_DEPTH = 16
19
+
20
+ _EXTRACTED_HEADERS: tuple[str, ...] = ("From", "To", "Cc", "Date", "Subject")
21
+
22
+
23
+ class _EmlLimitExceeded(Exception):
24
+ """Sentinel aborting EML traversal immediately when MIME or text limits are exceeded."""
25
+
26
+ def __init__(self, detail: str) -> None:
27
+ super().__init__(detail)
28
+ self.detail = detail
29
+
30
+
31
+ def _clean_header_value(raw_val: object) -> str:
32
+ text = str(raw_val).replace("\r", " ").replace("\n", " ").strip()
33
+ return " ".join(text.split())
34
+
35
+
36
+ def _is_attachment_part(part: Message) -> bool:
37
+ disposition = (part.get_content_disposition() or "").lower()
38
+ if disposition == "attachment":
39
+ return True
40
+ if part.get_filename() is not None and disposition != "inline":
41
+ return True
42
+ ctype = part.get_content_type().lower()
43
+ return not ctype.startswith("text/") and not part.is_multipart()
44
+
45
+
46
+ def _extract_part_bytes(part: Message) -> bytes:
47
+ payload = part.get_payload(decode=True)
48
+ if isinstance(payload, bytes):
49
+ return payload
50
+ if isinstance(payload, str):
51
+ return payload.encode("utf-8", errors="replace")
52
+ return b""
53
+
54
+
55
+ def _decode_plain_part(part: Message, limits: DocumentLimits) -> str:
56
+ raw_bytes = _extract_part_bytes(part)
57
+ if not raw_bytes:
58
+ return ""
59
+ if len(raw_bytes) > limits.max_decompressed_bytes:
60
+ raise _EmlLimitExceeded(
61
+ "Decoded EML body part exceeds configured max_decompressed_bytes limit."
62
+ )
63
+ charset = part.get_content_charset()
64
+ decoded: str | None = None
65
+ if charset:
66
+ try:
67
+ decoded = raw_bytes.decode(charset, errors="replace")
68
+ except LookupError:
69
+ decoded = None
70
+ if decoded is None:
71
+ decoded = _decode_text_bytes(raw_bytes)
72
+ if decoded is None:
73
+ decoded = raw_bytes.decode("utf-8", errors="replace")
74
+ normalized = normalize_document_text(decoded)
75
+ if len(normalized.encode("utf-8")) > limits.max_decompressed_bytes:
76
+ raise _EmlLimitExceeded(
77
+ "Prepared EML body text exceeds configured max_decompressed_bytes limit."
78
+ )
79
+ return normalized
80
+
81
+
82
+ def _decode_html_part(
83
+ part: Message,
84
+ source: SourceMetadata,
85
+ limits: DocumentLimits,
86
+ ) -> list[tuple[str, str]]:
87
+ raw_bytes = _extract_part_bytes(part)
88
+ if not raw_bytes:
89
+ return []
90
+ if len(raw_bytes) > limits.max_decompressed_bytes:
91
+ raise _EmlLimitExceeded(
92
+ "Decoded EML HTML part exceeds configured max_decompressed_bytes limit."
93
+ )
94
+ parsed = parse_html_bytes(raw_bytes, source, limits)
95
+ if parsed.document is None:
96
+ for err in parsed.errors:
97
+ if err.code == "resource_limit_exceeded":
98
+ raise _EmlLimitExceeded(err.message)
99
+ return []
100
+ return [(seg.text, seg.heading or "Body") for seg in parsed.document.segments]
101
+
102
+
103
+ def parse_eml_bytes(
104
+ raw: bytes,
105
+ source: SourceMetadata,
106
+ limits: DocumentLimits,
107
+ ) -> ParseResult:
108
+ """Parse RFC 5322 .eml bytes safely into Headers + Body DocumentSegments."""
109
+ if len(raw) == 0:
110
+ return ParseResult(
111
+ document=None,
112
+ errors=(
113
+ DiagnosticIssue(
114
+ code="empty_document",
115
+ severity=IssueSeverity.ERROR,
116
+ stage=PipelineStage.DOCUMENT_PROCESSING,
117
+ message="Input EML document is empty (zero bytes).",
118
+ ),
119
+ ),
120
+ )
121
+
122
+ if _looks_binary(raw):
123
+ return ParseResult(
124
+ document=None,
125
+ errors=(
126
+ DiagnosticIssue(
127
+ code="unsupported_format",
128
+ severity=IssueSeverity.ERROR,
129
+ stage=PipelineStage.DOCUMENT_PROCESSING,
130
+ message="Input file appears to contain binary data rather than an EML email.",
131
+ ),
132
+ ),
133
+ )
134
+
135
+ try:
136
+ msg: EmailMessage = BytesParser(policy=email_policy.default).parsebytes(raw)
137
+ except Exception:
138
+ return ParseResult(
139
+ document=None,
140
+ errors=(
141
+ DiagnosticIssue(
142
+ code="unsupported_format",
143
+ severity=IssueSeverity.ERROR,
144
+ stage=PipelineStage.DOCUMENT_PROCESSING,
145
+ message="Unable to parse input bytes as an RFC 5322 EML message.",
146
+ ),
147
+ ),
148
+ )
149
+
150
+ part_count = 0
151
+ skipped_attachments = 0
152
+ accumulated_bytes = 0
153
+ raw_blocks: list[tuple[str, str]] = []
154
+
155
+ def _charge(text: str) -> None:
156
+ nonlocal accumulated_bytes
157
+ accumulated_bytes += len(text.encode("utf-8"))
158
+ if accumulated_bytes > limits.max_decompressed_bytes:
159
+ raise _EmlLimitExceeded(
160
+ "Prepared EML text exceeds configured max_decompressed_bytes limit."
161
+ )
162
+
163
+ # 1. Extract normalized key headers into the "Headers" section
164
+ header_lines: list[str] = []
165
+ for hdr_name in _EXTRACTED_HEADERS:
166
+ hdr_val = msg.get(hdr_name)
167
+ if hdr_val is not None:
168
+ cleaned = _clean_header_value(hdr_val)
169
+ if cleaned:
170
+ header_lines.append(f"{hdr_name}: {cleaned}")
171
+ if header_lines:
172
+ header_block = "\n".join(header_lines)
173
+ _charge(header_block)
174
+ raw_blocks.append((header_block, "Headers"))
175
+
176
+ def _collect_part(part: Message, depth: int) -> list[tuple[str, str]]:
177
+ nonlocal part_count, skipped_attachments
178
+ part_count += 1
179
+ if part_count > MAX_EML_PARTS:
180
+ raise _EmlLimitExceeded(
181
+ f"EML MIME part count exceeds maximum safety limit ({MAX_EML_PARTS} parts)."
182
+ )
183
+ if depth > MAX_EML_NESTING_DEPTH:
184
+ raise _EmlLimitExceeded(
185
+ f"EML MIME nesting depth exceeds maximum safety limit "
186
+ f"({MAX_EML_NESTING_DEPTH} levels)."
187
+ )
188
+
189
+ if part.is_multipart():
190
+ children = part.get_payload()
191
+ if not isinstance(children, list):
192
+ return []
193
+ subtype = part.get_content_subtype().lower()
194
+ if subtype == "alternative":
195
+ plain_blocks: list[tuple[str, str]] = []
196
+ html_blocks: list[tuple[str, str]] = []
197
+ for child in children:
198
+ if not isinstance(child, Message):
199
+ continue
200
+ if _is_attachment_part(child):
201
+ skipped_attachments += 1
202
+ continue
203
+ ctype = child.get_content_type().lower()
204
+ if child.is_multipart():
205
+ plain_blocks.extend(_collect_part(child, depth + 1))
206
+ elif ctype == "text/plain":
207
+ part_count += 1
208
+ if part_count > MAX_EML_PARTS:
209
+ raise _EmlLimitExceeded(
210
+ f"EML MIME part count exceeds maximum safety limit "
211
+ f"({MAX_EML_PARTS} parts)."
212
+ )
213
+ text = _decode_plain_part(child, limits)
214
+ for para in [p.strip() for p in text.split("\n\n") if p.strip()]:
215
+ plain_blocks.append((para, "Body"))
216
+ elif ctype == "text/html":
217
+ part_count += 1
218
+ if part_count > MAX_EML_PARTS:
219
+ raise _EmlLimitExceeded(
220
+ f"EML MIME part count exceeds maximum safety limit "
221
+ f"({MAX_EML_PARTS} parts)."
222
+ )
223
+ html_blocks.extend(_decode_html_part(child, source, limits))
224
+ else:
225
+ skipped_attachments += 1
226
+ return plain_blocks if plain_blocks else html_blocks
227
+
228
+ collected: list[tuple[str, str]] = []
229
+ for child in children:
230
+ if not isinstance(child, Message):
231
+ continue
232
+ if _is_attachment_part(child):
233
+ skipped_attachments += 1
234
+ continue
235
+ collected.extend(_collect_part(child, depth + 1))
236
+ return collected
237
+
238
+ if _is_attachment_part(part):
239
+ skipped_attachments += 1
240
+ return []
241
+
242
+ ctype = part.get_content_type().lower()
243
+ if ctype == "text/plain":
244
+ text = _decode_plain_part(part, limits)
245
+ return [(para, "Body") for para in (p.strip() for p in text.split("\n\n")) if para]
246
+ if ctype == "text/html":
247
+ return _decode_html_part(part, source, limits)
248
+ skipped_attachments += 1
249
+ return []
250
+
251
+ try:
252
+ body_blocks = _collect_part(msg, depth=0)
253
+ for text, section in body_blocks:
254
+ _charge(text)
255
+ raw_blocks.append((text, section))
256
+ except _EmlLimitExceeded as exc:
257
+ return ParseResult(
258
+ document=None,
259
+ errors=(
260
+ DiagnosticIssue(
261
+ code="resource_limit_exceeded",
262
+ severity=IssueSeverity.ERROR,
263
+ stage=PipelineStage.DOCUMENT_PROCESSING,
264
+ message=exc.detail,
265
+ ),
266
+ ),
267
+ )
268
+
269
+ warnings: list[DiagnosticIssue] = []
270
+ if skipped_attachments > 0:
271
+ warnings.append(
272
+ DiagnosticIssue(
273
+ code="attachments_skipped",
274
+ severity=IssueSeverity.WARNING,
275
+ stage=PipelineStage.DOCUMENT_PROCESSING,
276
+ message=(
277
+ f"Skipped {skipped_attachments} non-text or file attachment(s) "
278
+ "while parsing EML message."
279
+ ),
280
+ )
281
+ )
282
+
283
+ if not raw_blocks:
284
+ return ParseResult(
285
+ document=None,
286
+ errors=(
287
+ DiagnosticIssue(
288
+ code="no_extractable_text",
289
+ severity=IssueSeverity.ERROR,
290
+ stage=PipelineStage.DOCUMENT_PROCESSING,
291
+ message="EML message contains no extractable headers or text body.",
292
+ ),
293
+ ),
294
+ warnings=tuple(warnings),
295
+ )
296
+
297
+ segments: list[DocumentSegment] = []
298
+ full_parts: list[str] = []
299
+ offset = 0
300
+ para_idx = 0
301
+ for text, heading in raw_blocks:
302
+ normalized_block = normalize_document_text(text).strip()
303
+ if not normalized_block:
304
+ continue
305
+ para_idx += 1
306
+ if full_parts:
307
+ offset += 2 # "\n\n" separator
308
+ char_start = offset
309
+ char_end = char_start + len(normalized_block)
310
+ full_parts.append(normalized_block)
311
+ segments.append(
312
+ DocumentSegment(
313
+ text=normalized_block,
314
+ char_start=char_start,
315
+ char_end=char_end,
316
+ paragraph=para_idx,
317
+ heading=heading,
318
+ )
319
+ )
320
+ offset = char_end
321
+
322
+ if not full_parts:
323
+ return ParseResult(
324
+ document=None,
325
+ errors=(
326
+ DiagnosticIssue(
327
+ code="no_extractable_text",
328
+ severity=IssueSeverity.ERROR,
329
+ stage=PipelineStage.DOCUMENT_PROCESSING,
330
+ message="EML message contains no extractable headers or text body.",
331
+ ),
332
+ ),
333
+ warnings=tuple(warnings),
334
+ )
335
+
336
+ full_text = "\n\n".join(full_parts)
337
+ if len(full_text.encode("utf-8")) > limits.max_decompressed_bytes:
338
+ return ParseResult(
339
+ document=None,
340
+ errors=(
341
+ DiagnosticIssue(
342
+ code="resource_limit_exceeded",
343
+ severity=IssueSeverity.ERROR,
344
+ stage=PipelineStage.DOCUMENT_PROCESSING,
345
+ message="Prepared EML text exceeds configured max_decompressed_bytes limit.",
346
+ ),
347
+ ),
348
+ warnings=tuple(warnings),
349
+ )
350
+
351
+ return ParseResult(
352
+ document=PreparedDocument(
353
+ source=source,
354
+ format=DocumentFormat.EML,
355
+ full_text=full_text,
356
+ segments=tuple(segments),
357
+ page_count=None,
358
+ ),
359
+ warnings=tuple(warnings),
360
+ )
@@ -0,0 +1,337 @@
1
+ """Hardened stdlib-only HTML parser stripping scripts/styles and preserving heading/table blocks."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import codecs
6
+ import re
7
+ from html.parser import HTMLParser
8
+
9
+ from structa_maestro.config import DocumentLimits
10
+ from structa_maestro.contracts.enums import DocumentFormat, IssueSeverity, PipelineStage
11
+ from structa_maestro.contracts.models import DiagnosticIssue, SourceMetadata
12
+ from structa_maestro.documents.models import DocumentSegment, PreparedDocument
13
+ from structa_maestro.documents.normalization import normalize_document_text
14
+ from structa_maestro.documents.txt_parser import ParseResult, _decode_text_bytes, _looks_binary
15
+
16
+ _SKIP_TAGS: frozenset[str] = frozenset({"script", "style", "noscript", "template"})
17
+ _HEADING_TAGS: frozenset[str] = frozenset({"h1", "h2", "h3", "h4", "h5", "h6"})
18
+ _BLOCK_TAGS: frozenset[str] = frozenset(
19
+ {
20
+ "p",
21
+ "div",
22
+ "section",
23
+ "article",
24
+ "header",
25
+ "footer",
26
+ "main",
27
+ "aside",
28
+ "nav",
29
+ "li",
30
+ "ul",
31
+ "ol",
32
+ "blockquote",
33
+ "pre",
34
+ "dt",
35
+ "dd",
36
+ "hr",
37
+ "figure",
38
+ "figcaption",
39
+ "address",
40
+ "title",
41
+ }
42
+ )
43
+ _CELL_TAGS: frozenset[str] = frozenset({"td", "th"})
44
+ _META_CHARSET_RE = re.compile(
45
+ rb"<meta[^>]+charset\s*=\s*['\"]?\s*([A-Za-z0-9._\-]+)",
46
+ re.IGNORECASE,
47
+ )
48
+ _WS_COLLAPSE_RE = re.compile(r"[ \t\r\n\f\v]+")
49
+
50
+
51
+ class _DecompressedLimitExceeded(Exception):
52
+ """Internal sentinel aborting HTML parsing immediately when decoded bytes exceed limit."""
53
+
54
+
55
+ def _decode_html_bytes(raw: bytes) -> str | None:
56
+ """Decode HTML bytes honoring BOMs, UTF-8, safe <meta charset> hints, and Latin-1 fallback."""
57
+ if raw.startswith((b"\xff\xfe", b"\xfe\xff", b"\xef\xbb\xbf")):
58
+ return _decode_text_bytes(raw)
59
+ try:
60
+ return raw.decode("utf-8")
61
+ except UnicodeDecodeError:
62
+ pass
63
+
64
+ match = _META_CHARSET_RE.search(raw[:4096])
65
+ if match is not None:
66
+ raw_enc = match.group(1).decode("ascii", errors="ignore").strip()
67
+ try:
68
+ codec_info = codecs.lookup(raw_enc)
69
+ return raw.decode(codec_info.name)
70
+ except (LookupError, UnicodeDecodeError):
71
+ pass
72
+
73
+ return _decode_text_bytes(raw)
74
+
75
+
76
+ class _SafeHTMLTextExtractor(HTMLParser):
77
+ """Stdlib HTMLParser discarding executable/non-visible tags and bounding decoded output."""
78
+
79
+ def __init__(self, *, max_decompressed_bytes: int) -> None:
80
+ super().__init__(convert_charrefs=True)
81
+ self._max_bytes = max_decompressed_bytes
82
+ self._byte_count = 0
83
+ self._skip_depth = 0
84
+ self._in_heading = False
85
+ self._heading_buf: list[str] = []
86
+ self._current_heading: str | None = None
87
+ self._in_row = False
88
+ self._in_cell = False
89
+ self._row_cells: list[str] = []
90
+ self._cell_buf: list[str] = []
91
+ self._block_buf: list[str] = []
92
+ self.blocks: list[tuple[str, str | None]] = []
93
+
94
+ def _charge_bytes(self, text: str) -> None:
95
+ self._byte_count += len(text.encode("utf-8"))
96
+ if self._byte_count > self._max_bytes:
97
+ raise _DecompressedLimitExceeded
98
+
99
+ def _flush_block(self) -> None:
100
+ if not self._block_buf:
101
+ return
102
+ raw_text = "".join(self._block_buf)
103
+ self._block_buf.clear()
104
+ cleaned = _WS_COLLAPSE_RE.sub(" ", raw_text).strip()
105
+ if cleaned:
106
+ self.blocks.append((cleaned, self._current_heading))
107
+
108
+ def _flush_cell(self) -> None:
109
+ if not self._cell_buf:
110
+ return
111
+ cleaned = _WS_COLLAPSE_RE.sub(" ", "".join(self._cell_buf)).strip()
112
+ self._cell_buf.clear()
113
+ if cleaned:
114
+ self._row_cells.append(cleaned)
115
+
116
+ def _flush_row(self) -> None:
117
+ self._flush_cell()
118
+ if self._row_cells:
119
+ row_text = " | ".join(self._row_cells)
120
+ self._row_cells.clear()
121
+ self.blocks.append((row_text, self._current_heading))
122
+
123
+ def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
124
+ _ = attrs
125
+ tag_l = tag.lower()
126
+ if tag_l in _SKIP_TAGS:
127
+ self._skip_depth += 1
128
+ return
129
+ if self._skip_depth > 0:
130
+ return
131
+ if tag_l in _HEADING_TAGS:
132
+ self._flush_block()
133
+ self._in_heading = True
134
+ self._heading_buf.clear()
135
+ elif tag_l == "tr":
136
+ self._flush_block()
137
+ self._flush_row()
138
+ self._in_row = True
139
+ elif tag_l in _CELL_TAGS:
140
+ if not self._in_row:
141
+ self._flush_block()
142
+ self._in_row = True
143
+ self._flush_cell()
144
+ self._in_cell = True
145
+ elif tag_l == "br":
146
+ if self._in_cell:
147
+ self._cell_buf.append(" ")
148
+ elif self._in_heading:
149
+ self._heading_buf.append(" ")
150
+ else:
151
+ self._flush_block()
152
+ elif tag_l in _BLOCK_TAGS:
153
+ self._flush_block()
154
+
155
+ def handle_endtag(self, tag: str) -> None:
156
+ tag_l = tag.lower()
157
+ if tag_l in _SKIP_TAGS:
158
+ if self._skip_depth > 0:
159
+ self._skip_depth -= 1
160
+ return
161
+ if self._skip_depth > 0:
162
+ return
163
+ if tag_l in _HEADING_TAGS:
164
+ if self._in_heading:
165
+ heading_text = _WS_COLLAPSE_RE.sub(" ", "".join(self._heading_buf)).strip()
166
+ self._heading_buf.clear()
167
+ self._in_heading = False
168
+ if heading_text:
169
+ self._current_heading = heading_text
170
+ self.blocks.append((heading_text, heading_text))
171
+ elif tag_l in _CELL_TAGS:
172
+ self._flush_cell()
173
+ self._in_cell = False
174
+ elif tag_l == "tr":
175
+ self._flush_row()
176
+ self._in_row = False
177
+ self._in_cell = False
178
+ elif tag_l in _BLOCK_TAGS:
179
+ self._flush_block()
180
+
181
+ def handle_data(self, data: str) -> None:
182
+ if self._skip_depth > 0 or not data:
183
+ return
184
+ self._charge_bytes(data)
185
+ if self._in_heading:
186
+ self._heading_buf.append(data)
187
+ elif self._in_cell:
188
+ self._cell_buf.append(data)
189
+ else:
190
+ self._block_buf.append(data)
191
+
192
+ def handle_comment(self, data: str) -> None:
193
+ # Discard all HTML comments completely
194
+ _ = data
195
+
196
+ def finalize(self) -> list[tuple[str, str | None]]:
197
+ if self._in_heading and self._heading_buf:
198
+ heading_text = _WS_COLLAPSE_RE.sub(" ", "".join(self._heading_buf)).strip()
199
+ self._heading_buf.clear()
200
+ self._in_heading = False
201
+ if heading_text:
202
+ self._current_heading = heading_text
203
+ self.blocks.append((heading_text, heading_text))
204
+ self._flush_row()
205
+ self._flush_block()
206
+ return self.blocks
207
+
208
+
209
+ def parse_html_bytes(
210
+ raw: bytes,
211
+ source: SourceMetadata,
212
+ limits: DocumentLimits,
213
+ ) -> ParseResult:
214
+ """Parse raw HTML bytes into a PreparedDocument with heading & paragraph DocumentSegments."""
215
+ if len(raw) == 0:
216
+ return ParseResult(
217
+ document=None,
218
+ errors=(
219
+ DiagnosticIssue(
220
+ code="empty_document",
221
+ severity=IssueSeverity.ERROR,
222
+ stage=PipelineStage.DOCUMENT_PROCESSING,
223
+ message="Input HTML document is empty (zero bytes).",
224
+ ),
225
+ ),
226
+ )
227
+
228
+ if _looks_binary(raw):
229
+ return ParseResult(
230
+ document=None,
231
+ errors=(
232
+ DiagnosticIssue(
233
+ code="unsupported_format",
234
+ severity=IssueSeverity.ERROR,
235
+ stage=PipelineStage.DOCUMENT_PROCESSING,
236
+ message="Input file appears to contain binary data rather than HTML.",
237
+ ),
238
+ ),
239
+ )
240
+
241
+ decoded = _decode_html_bytes(raw)
242
+ if decoded is None:
243
+ return ParseResult(
244
+ document=None,
245
+ errors=(
246
+ DiagnosticIssue(
247
+ code="decoding_error",
248
+ severity=IssueSeverity.ERROR,
249
+ stage=PipelineStage.DOCUMENT_PROCESSING,
250
+ message="Unable to decode HTML document with supported text encodings.",
251
+ ),
252
+ ),
253
+ )
254
+
255
+ extractor = _SafeHTMLTextExtractor(max_decompressed_bytes=limits.max_decompressed_bytes)
256
+ try:
257
+ extractor.feed(decoded)
258
+ extractor.close()
259
+ raw_blocks = extractor.finalize()
260
+ except _DecompressedLimitExceeded:
261
+ return ParseResult(
262
+ document=None,
263
+ errors=(
264
+ DiagnosticIssue(
265
+ code="resource_limit_exceeded",
266
+ severity=IssueSeverity.ERROR,
267
+ stage=PipelineStage.DOCUMENT_PROCESSING,
268
+ message="Decoded HTML text exceeds configured max_decompressed_bytes limit.",
269
+ ),
270
+ ),
271
+ )
272
+
273
+ segments: list[DocumentSegment] = []
274
+ full_parts: list[str] = []
275
+ offset = 0
276
+ para_idx = 0
277
+
278
+ for text, heading in raw_blocks:
279
+ normalized_block = normalize_document_text(text).strip()
280
+ if not normalized_block:
281
+ continue
282
+ para_idx += 1
283
+ if full_parts:
284
+ offset += 1 # '\n' separator
285
+ char_start = offset
286
+ char_end = char_start + len(normalized_block)
287
+ full_parts.append(normalized_block)
288
+ segments.append(
289
+ DocumentSegment(
290
+ text=normalized_block,
291
+ char_start=char_start,
292
+ char_end=char_end,
293
+ paragraph=para_idx,
294
+ heading=heading,
295
+ )
296
+ )
297
+ offset = char_end
298
+
299
+ if not full_parts:
300
+ return ParseResult(
301
+ document=None,
302
+ errors=(
303
+ DiagnosticIssue(
304
+ code="no_extractable_text",
305
+ severity=IssueSeverity.ERROR,
306
+ stage=PipelineStage.DOCUMENT_PROCESSING,
307
+ message=(
308
+ "HTML document contains no extractable visible text "
309
+ "(markup, scripts, styles, comments, or whitespace only)."
310
+ ),
311
+ ),
312
+ ),
313
+ )
314
+
315
+ full_text = "\n".join(full_parts)
316
+ if len(full_text.encode("utf-8")) > limits.max_decompressed_bytes:
317
+ return ParseResult(
318
+ document=None,
319
+ errors=(
320
+ DiagnosticIssue(
321
+ code="resource_limit_exceeded",
322
+ severity=IssueSeverity.ERROR,
323
+ stage=PipelineStage.DOCUMENT_PROCESSING,
324
+ message="Prepared HTML text exceeds configured max_decompressed_bytes limit.",
325
+ ),
326
+ ),
327
+ )
328
+
329
+ return ParseResult(
330
+ document=PreparedDocument(
331
+ source=source,
332
+ format=DocumentFormat.HTML,
333
+ full_text=full_text,
334
+ segments=tuple(segments),
335
+ page_count=None,
336
+ )
337
+ )