tracecite-docs 0.0.1__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.
- tracecite_docs/__init__.py +35 -0
- tracecite_docs/__main__.py +3 -0
- tracecite_docs/cli.py +580 -0
- tracecite_docs/docs/__init__.py +56 -0
- tracecite_docs/docs/build.py +382 -0
- tracecite_docs/docs/config.py +114 -0
- tracecite_docs/docs/contract.py +17 -0
- tracecite_docs/docs/modes.py +240 -0
- tracecite_docs/docs/stage.py +408 -0
- tracecite_docs/docs/vectorize.py +458 -0
- tracecite_docs/tables/__init__.py +41 -0
- tracecite_docs/tables/_text.py +142 -0
- tracecite_docs/tables/document.py +582 -0
- tracecite_docs/tables/html.py +232 -0
- tracecite_docs/tables/models.py +211 -0
- tracecite_docs/tables/normalise.py +787 -0
- tracecite_docs/tables/pandoc.py +427 -0
- tracecite_docs/tables/publish.py +248 -0
- tracecite_docs/tables/render.py +128 -0
- tracecite_docs/tables/site.py +457 -0
- tracecite_docs-0.0.1.dist-info/METADATA +94 -0
- tracecite_docs-0.0.1.dist-info/RECORD +26 -0
- tracecite_docs-0.0.1.dist-info/WHEEL +5 -0
- tracecite_docs-0.0.1.dist-info/entry_points.txt +2 -0
- tracecite_docs-0.0.1.dist-info/licenses/LICENSE +21 -0
- tracecite_docs-0.0.1.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,232 @@
|
|
|
1
|
+
"""HTML-table adapter for Literate.jl, Documenter.jl, and HTML MIME output."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import replace
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
from bs4 import BeautifulSoup, Tag
|
|
9
|
+
from bs4.element import PageElement
|
|
10
|
+
|
|
11
|
+
from ._text import collapse_space, escape_pipe_cell
|
|
12
|
+
from .models import (
|
|
13
|
+
NormalisedTable,
|
|
14
|
+
TableContext,
|
|
15
|
+
TableDiagnostic,
|
|
16
|
+
TableNormalisationError,
|
|
17
|
+
expand_spans,
|
|
18
|
+
source_hash,
|
|
19
|
+
)
|
|
20
|
+
from .normalise import normalise_pandoc_table
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def html_table_to_markdown(
|
|
24
|
+
source: str,
|
|
25
|
+
*,
|
|
26
|
+
context: TableContext | None = None,
|
|
27
|
+
) -> tuple[str, tuple[TableDiagnostic, ...]]:
|
|
28
|
+
"""Convert exactly one top-level HTML table to canonical pipe Markdown."""
|
|
29
|
+
|
|
30
|
+
context = context or TableContext()
|
|
31
|
+
soup = BeautifulSoup(source, "html.parser")
|
|
32
|
+
tables = [
|
|
33
|
+
table for table in soup.find_all("table") if table.find_parent("table") is None
|
|
34
|
+
]
|
|
35
|
+
if len(tables) != 1:
|
|
36
|
+
raise TableNormalisationError(
|
|
37
|
+
f"html_table_to_markdown expects exactly one top-level table; found {len(tables)}"
|
|
38
|
+
)
|
|
39
|
+
|
|
40
|
+
table = tables[0]
|
|
41
|
+
diagnostics: list[TableDiagnostic] = []
|
|
42
|
+
if table.find("table") is not None:
|
|
43
|
+
diagnostics.append(
|
|
44
|
+
TableDiagnostic(
|
|
45
|
+
"table.unsupported-nested-table",
|
|
46
|
+
"error",
|
|
47
|
+
"Nested HTML tables are preserved as raw evidence but are not flattened silently.",
|
|
48
|
+
)
|
|
49
|
+
)
|
|
50
|
+
|
|
51
|
+
logical_rows = [
|
|
52
|
+
row for row in table.find_all("tr") if row.find_parent("table") is table
|
|
53
|
+
]
|
|
54
|
+
if not logical_rows:
|
|
55
|
+
raise TableNormalisationError("The HTML table contains no rows")
|
|
56
|
+
|
|
57
|
+
width = max(
|
|
58
|
+
(
|
|
59
|
+
sum(_span(cell, "colspan") for cell in _direct_cells(row))
|
|
60
|
+
for row in logical_rows
|
|
61
|
+
),
|
|
62
|
+
default=0,
|
|
63
|
+
)
|
|
64
|
+
expanded = expand_spans(
|
|
65
|
+
(
|
|
66
|
+
[
|
|
67
|
+
(_span(cell, "rowspan"), _span(cell, "colspan"), _render_html(cell))
|
|
68
|
+
for cell in _direct_cells(row)
|
|
69
|
+
]
|
|
70
|
+
for row in logical_rows
|
|
71
|
+
),
|
|
72
|
+
width,
|
|
73
|
+
diagnostics,
|
|
74
|
+
"HTML",
|
|
75
|
+
)
|
|
76
|
+
|
|
77
|
+
thead_rows = {
|
|
78
|
+
index
|
|
79
|
+
for index, row in enumerate(logical_rows)
|
|
80
|
+
if row.find_parent("thead") is not None
|
|
81
|
+
}
|
|
82
|
+
if thead_rows:
|
|
83
|
+
header_indices = sorted(thead_rows)
|
|
84
|
+
else:
|
|
85
|
+
header_indices = []
|
|
86
|
+
for index, row in enumerate(logical_rows):
|
|
87
|
+
cells = _direct_cells(row)
|
|
88
|
+
if cells and all(cell.name == "th" for cell in cells):
|
|
89
|
+
header_indices.append(index)
|
|
90
|
+
else:
|
|
91
|
+
break
|
|
92
|
+
|
|
93
|
+
if header_indices:
|
|
94
|
+
header_rows = [expanded[index] for index in header_indices]
|
|
95
|
+
headers = _combine_header_rows(header_rows, width)
|
|
96
|
+
body_rows = [
|
|
97
|
+
row for index, row in enumerate(expanded) if index not in header_indices
|
|
98
|
+
]
|
|
99
|
+
else:
|
|
100
|
+
headers = [f"Column {index}" for index in range(1, width + 1)]
|
|
101
|
+
body_rows = expanded
|
|
102
|
+
diagnostics.append(
|
|
103
|
+
TableDiagnostic(
|
|
104
|
+
"table.generated-headers",
|
|
105
|
+
"warning",
|
|
106
|
+
"The HTML table had no complete header row; deterministic headers were generated.",
|
|
107
|
+
)
|
|
108
|
+
)
|
|
109
|
+
|
|
110
|
+
caption_tag = table.find("caption", recursive=False)
|
|
111
|
+
caption = context.caption or (_render_html(caption_tag) if caption_tag else None)
|
|
112
|
+
table_id = context.table_id or str(table.get("id") or "").strip() or None
|
|
113
|
+
|
|
114
|
+
lines = [
|
|
115
|
+
"| " + " | ".join(escape_pipe_cell(value) for value in headers) + " |",
|
|
116
|
+
"| " + " | ".join("---" for _ in headers) + " |",
|
|
117
|
+
]
|
|
118
|
+
lines.extend(
|
|
119
|
+
"| " + " | ".join(escape_pipe_cell(value) for value in row) + " |"
|
|
120
|
+
for row in body_rows
|
|
121
|
+
)
|
|
122
|
+
if caption:
|
|
123
|
+
suffix = f" {{#{table_id}}}" if table_id else ""
|
|
124
|
+
lines.extend(["", f": {caption}{suffix}"])
|
|
125
|
+
return "\n".join(lines), tuple(diagnostics)
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def normalise_html_table(
|
|
129
|
+
source: str,
|
|
130
|
+
*,
|
|
131
|
+
context: TableContext | None = None,
|
|
132
|
+
strict: bool = False,
|
|
133
|
+
pandoc: str | Path | None = None,
|
|
134
|
+
) -> NormalisedTable:
|
|
135
|
+
"""Normalise one HTML table through the shared Pandoc-table contract."""
|
|
136
|
+
|
|
137
|
+
context = context or TableContext()
|
|
138
|
+
soup = BeautifulSoup(source, "html.parser")
|
|
139
|
+
tables = [
|
|
140
|
+
table for table in soup.find_all("table") if table.find_parent("table") is None
|
|
141
|
+
]
|
|
142
|
+
if len(tables) != 1:
|
|
143
|
+
raise TableNormalisationError(
|
|
144
|
+
f"normalise_html_table expects exactly one top-level table; found {len(tables)}"
|
|
145
|
+
)
|
|
146
|
+
html_table = tables[0]
|
|
147
|
+
caption_tag = html_table.find("caption", recursive=False)
|
|
148
|
+
context = context.merged(
|
|
149
|
+
table_id=context.table_id or str(html_table.get("id") or "").strip() or None,
|
|
150
|
+
caption=context.caption or (_render_html(caption_tag) if caption_tag else None),
|
|
151
|
+
)
|
|
152
|
+
markdown, adapter_diagnostics = html_table_to_markdown(source, context=context)
|
|
153
|
+
result = normalise_pandoc_table(
|
|
154
|
+
markdown,
|
|
155
|
+
context=context,
|
|
156
|
+
strict=False,
|
|
157
|
+
pandoc=pandoc,
|
|
158
|
+
allow_pipe_fallback=True,
|
|
159
|
+
)
|
|
160
|
+
diagnostics = (*adapter_diagnostics, *result.diagnostics)
|
|
161
|
+
supported = result.supported and not any(
|
|
162
|
+
item.code == "table.unsupported-nested-table" for item in diagnostics
|
|
163
|
+
)
|
|
164
|
+
result = replace(
|
|
165
|
+
result,
|
|
166
|
+
raw_source=source,
|
|
167
|
+
source_format="html",
|
|
168
|
+
canonical_markdown=markdown,
|
|
169
|
+
diagnostics=diagnostics,
|
|
170
|
+
source_hash=source_hash(source, context),
|
|
171
|
+
supported=supported,
|
|
172
|
+
)
|
|
173
|
+
if strict and (result.has_errors or not result.supported):
|
|
174
|
+
errors = "; ".join(
|
|
175
|
+
item.message for item in result.diagnostics if item.severity == "error"
|
|
176
|
+
)
|
|
177
|
+
raise TableNormalisationError(
|
|
178
|
+
f"Table {result.table_id} failed strict HTML normalisation: {errors}"
|
|
179
|
+
)
|
|
180
|
+
return result
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def _direct_cells(row: Tag) -> list[Tag]:
|
|
184
|
+
return [
|
|
185
|
+
cell
|
|
186
|
+
for cell in row.find_all(["th", "td"], recursive=False)
|
|
187
|
+
if isinstance(cell, Tag)
|
|
188
|
+
]
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def _span(cell: Tag, attribute: str) -> int:
|
|
192
|
+
try:
|
|
193
|
+
return max(1, int(str(cell.get(attribute) or 1)))
|
|
194
|
+
except ValueError:
|
|
195
|
+
return 1
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def _combine_header_rows(rows: list[list[str]], width: int) -> list[str]:
|
|
199
|
+
headers = []
|
|
200
|
+
for column in range(width):
|
|
201
|
+
values: list[str] = []
|
|
202
|
+
for row in rows:
|
|
203
|
+
value = collapse_space(row[column] if column < len(row) else "")
|
|
204
|
+
if value and value not in values:
|
|
205
|
+
values.append(value)
|
|
206
|
+
headers.append(" / ".join(values) or f"Column {column + 1}")
|
|
207
|
+
return headers
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def _render_html(node: PageElement | None) -> str:
|
|
211
|
+
if node is None:
|
|
212
|
+
return ""
|
|
213
|
+
if not isinstance(node, Tag):
|
|
214
|
+
return collapse_space(str(node))
|
|
215
|
+
if node.name == "table":
|
|
216
|
+
return "[nested table omitted]"
|
|
217
|
+
if node.name == "br":
|
|
218
|
+
return " "
|
|
219
|
+
if node.name == "a":
|
|
220
|
+
label = collapse_space(" ".join(_render_html(child) for child in node.children))
|
|
221
|
+
href = str(node.get("href") or "").strip()
|
|
222
|
+
return f"{label} ({href})" if href else label
|
|
223
|
+
if node.name == "code":
|
|
224
|
+
return f"`{node.get_text(' ', strip=True)}`"
|
|
225
|
+
if node.name == "img":
|
|
226
|
+
alt = str(node.get("alt") or "image").strip()
|
|
227
|
+
src = str(node.get("src") or "").strip()
|
|
228
|
+
return f"{alt} ({src})" if src else alt
|
|
229
|
+
|
|
230
|
+
pieces = [_render_html(child) for child in node.children]
|
|
231
|
+
separator = "; " if node.name in {"ul", "ol", "li"} else " "
|
|
232
|
+
return collapse_space(separator.join(item for item in pieces if item))
|
|
@@ -0,0 +1,211 @@
|
|
|
1
|
+
"""Data contracts for deterministic table normalisation."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
from collections.abc import Iterable, Mapping
|
|
7
|
+
from dataclasses import asdict, dataclass, field
|
|
8
|
+
from hashlib import sha256
|
|
9
|
+
from typing import Any, Literal
|
|
10
|
+
|
|
11
|
+
Severity = Literal["info", "warning", "error"]
|
|
12
|
+
SourceFormat = Literal["pandoc-markdown", "html"]
|
|
13
|
+
NORMALISER_VERSION = "pandoc-table-v1"
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@dataclass(frozen=True, slots=True)
|
|
17
|
+
class TableContext:
|
|
18
|
+
"""Document context supplied by the caller or document extractor."""
|
|
19
|
+
|
|
20
|
+
document_path: str = "<memory>"
|
|
21
|
+
section_path: tuple[str, ...] = ()
|
|
22
|
+
source_code_path: str | None = None
|
|
23
|
+
table_id: str | None = None
|
|
24
|
+
caption: str | None = None
|
|
25
|
+
ordering: str | None = None
|
|
26
|
+
metadata: Mapping[str, Any] = field(default_factory=dict)
|
|
27
|
+
|
|
28
|
+
def merged(self, **updates: Any) -> TableContext:
|
|
29
|
+
values = {
|
|
30
|
+
"document_path": self.document_path,
|
|
31
|
+
"section_path": self.section_path,
|
|
32
|
+
"source_code_path": self.source_code_path,
|
|
33
|
+
"table_id": self.table_id,
|
|
34
|
+
"caption": self.caption,
|
|
35
|
+
"ordering": self.ordering,
|
|
36
|
+
"metadata": dict(self.metadata),
|
|
37
|
+
}
|
|
38
|
+
values.update(
|
|
39
|
+
{key: value for key, value in updates.items() if value is not None}
|
|
40
|
+
)
|
|
41
|
+
return TableContext(**values)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
@dataclass(frozen=True, slots=True)
|
|
45
|
+
class TableDiagnostic:
|
|
46
|
+
code: str
|
|
47
|
+
severity: Severity
|
|
48
|
+
message: str
|
|
49
|
+
row: int | None = None
|
|
50
|
+
column: int | None = None
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
@dataclass(frozen=True, slots=True)
|
|
54
|
+
class NormalisedTable:
|
|
55
|
+
"""Raw evidence, canonical table structure, and retrieval text."""
|
|
56
|
+
|
|
57
|
+
table_id: str
|
|
58
|
+
caption: str | None
|
|
59
|
+
section_path: tuple[str, ...]
|
|
60
|
+
headers: tuple[str, ...]
|
|
61
|
+
rows: tuple[tuple[str, ...], ...]
|
|
62
|
+
raw_source: str
|
|
63
|
+
source_format: SourceFormat
|
|
64
|
+
canonical_markdown: str
|
|
65
|
+
normalised_text: str
|
|
66
|
+
row_ids: tuple[str, ...]
|
|
67
|
+
row_records: tuple[str, ...]
|
|
68
|
+
diagnostics: tuple[TableDiagnostic, ...]
|
|
69
|
+
document_path: str
|
|
70
|
+
source_code_path: str | None
|
|
71
|
+
source_hash: str
|
|
72
|
+
normaliser_version: str = NORMALISER_VERSION
|
|
73
|
+
supported: bool = True
|
|
74
|
+
source_start_line: int | None = None
|
|
75
|
+
source_end_line: int | None = None
|
|
76
|
+
metadata: Mapping[str, Any] = field(default_factory=dict)
|
|
77
|
+
|
|
78
|
+
@property
|
|
79
|
+
def has_errors(self) -> bool:
|
|
80
|
+
return any(item.severity == "error" for item in self.diagnostics)
|
|
81
|
+
|
|
82
|
+
def to_dict(self) -> dict[str, Any]:
|
|
83
|
+
payload = asdict(self)
|
|
84
|
+
payload["section_path"] = list(self.section_path)
|
|
85
|
+
payload["headers"] = list(self.headers)
|
|
86
|
+
payload["rows"] = [list(row) for row in self.rows]
|
|
87
|
+
payload["row_ids"] = list(self.row_ids)
|
|
88
|
+
payload["row_records"] = list(self.row_records)
|
|
89
|
+
payload["diagnostics"] = [asdict(item) for item in self.diagnostics]
|
|
90
|
+
payload["metadata"] = dict(self.metadata)
|
|
91
|
+
return payload
|
|
92
|
+
|
|
93
|
+
def to_json(self, *, indent: int | None = 2) -> str:
|
|
94
|
+
return json.dumps(
|
|
95
|
+
self.to_dict(), ensure_ascii=False, indent=indent, sort_keys=True
|
|
96
|
+
)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
class TableNormalisationError(ValueError):
|
|
100
|
+
"""Raised when strict normalisation cannot produce a trustworthy table."""
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def source_hash(raw_source: str, context: TableContext) -> str:
|
|
104
|
+
payload = {
|
|
105
|
+
"raw_source": raw_source,
|
|
106
|
+
"document_path": context.document_path,
|
|
107
|
+
"section_path": list(context.section_path),
|
|
108
|
+
"source_code_path": context.source_code_path,
|
|
109
|
+
"table_id": context.table_id,
|
|
110
|
+
"caption": context.caption,
|
|
111
|
+
"ordering": context.ordering,
|
|
112
|
+
"metadata": dict(context.metadata),
|
|
113
|
+
"normaliser_version": NORMALISER_VERSION,
|
|
114
|
+
}
|
|
115
|
+
return sha256(
|
|
116
|
+
json.dumps(payload, ensure_ascii=False, sort_keys=True, default=str).encode(
|
|
117
|
+
"utf-8"
|
|
118
|
+
)
|
|
119
|
+
).hexdigest()
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def expand_spans(
|
|
123
|
+
rows: Iterable[Iterable[tuple[int, int, str] | None]],
|
|
124
|
+
width: int,
|
|
125
|
+
diagnostics: list[TableDiagnostic],
|
|
126
|
+
row_label: str,
|
|
127
|
+
) -> list[list[str]]:
|
|
128
|
+
"""Expand row and column spans by repeating each spanning cell's text.
|
|
129
|
+
|
|
130
|
+
Each cell is ``(rowspan, colspan, text)``, or None when its source shape
|
|
131
|
+
is unsupported. ``row_label`` names the rows in diagnostics, such as
|
|
132
|
+
``HTML`` or ``body``.
|
|
133
|
+
"""
|
|
134
|
+
pending: dict[int, tuple[int, str]] = {}
|
|
135
|
+
expanded: list[list[str]] = []
|
|
136
|
+
for row_number, cells in enumerate(rows, start=1):
|
|
137
|
+
values: list[str | None] = [None] * width
|
|
138
|
+
for column, (remaining, text) in list(pending.items()):
|
|
139
|
+
if column < width:
|
|
140
|
+
values[column] = text
|
|
141
|
+
if remaining <= 1:
|
|
142
|
+
del pending[column]
|
|
143
|
+
else:
|
|
144
|
+
pending[column] = (remaining - 1, text)
|
|
145
|
+
|
|
146
|
+
cursor = 0
|
|
147
|
+
for cell in cells:
|
|
148
|
+
while cursor < width and values[cursor] is not None:
|
|
149
|
+
cursor += 1
|
|
150
|
+
if cursor >= width:
|
|
151
|
+
diagnostics.append(
|
|
152
|
+
TableDiagnostic(
|
|
153
|
+
"table.extra-cell",
|
|
154
|
+
"error",
|
|
155
|
+
f"The {row_label} row contains more logical cells than the table width.",
|
|
156
|
+
row=row_number,
|
|
157
|
+
)
|
|
158
|
+
)
|
|
159
|
+
break
|
|
160
|
+
if cell is None:
|
|
161
|
+
diagnostics.append(
|
|
162
|
+
TableDiagnostic(
|
|
163
|
+
"table.unsupported-cell",
|
|
164
|
+
"error",
|
|
165
|
+
"A Pandoc table cell has an unsupported AST shape.",
|
|
166
|
+
row=row_number,
|
|
167
|
+
column=cursor + 1,
|
|
168
|
+
)
|
|
169
|
+
)
|
|
170
|
+
continue
|
|
171
|
+
|
|
172
|
+
rowspan, colspan, text = cell
|
|
173
|
+
if rowspan > 1 or colspan > 1:
|
|
174
|
+
diagnostics.append(
|
|
175
|
+
TableDiagnostic(
|
|
176
|
+
"table.span-expanded",
|
|
177
|
+
"warning",
|
|
178
|
+
f"A {rowspan}x{colspan} cell span was expanded by repeating its visible value.",
|
|
179
|
+
row=row_number,
|
|
180
|
+
column=cursor + 1,
|
|
181
|
+
)
|
|
182
|
+
)
|
|
183
|
+
for offset in range(colspan):
|
|
184
|
+
column = cursor + offset
|
|
185
|
+
if column >= width:
|
|
186
|
+
diagnostics.append(
|
|
187
|
+
TableDiagnostic(
|
|
188
|
+
"table.span-overflow",
|
|
189
|
+
"error",
|
|
190
|
+
"A cell span exceeds the table width.",
|
|
191
|
+
row=row_number,
|
|
192
|
+
column=cursor + 1,
|
|
193
|
+
)
|
|
194
|
+
)
|
|
195
|
+
break
|
|
196
|
+
values[column] = text
|
|
197
|
+
if rowspan > 1:
|
|
198
|
+
pending[column] = (rowspan - 1, text)
|
|
199
|
+
cursor += colspan
|
|
200
|
+
|
|
201
|
+
expanded.append([value or "" for value in values])
|
|
202
|
+
|
|
203
|
+
if pending:
|
|
204
|
+
diagnostics.append(
|
|
205
|
+
TableDiagnostic(
|
|
206
|
+
"table.rowspan-overflow",
|
|
207
|
+
"error",
|
|
208
|
+
f"A row span extends beyond the final {row_label} row.",
|
|
209
|
+
)
|
|
210
|
+
)
|
|
211
|
+
return expanded
|