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.
@@ -0,0 +1,458 @@
1
+ """Adapter that feeds retained documentation into the existing evidence stack."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import re
7
+ import shutil
8
+ import tempfile
9
+ from dataclasses import dataclass
10
+ from pathlib import Path
11
+ from typing import TYPE_CHECKING
12
+
13
+ from tracecite.evidence.paths import file_sha256
14
+
15
+ from ..tables import augment_document_with_embedding_text
16
+ from .contract import DocsEvidenceContract
17
+ from .stage import is_publication_excluded, validate_retained_source_links
18
+
19
+ if TYPE_CHECKING:
20
+ from tracecite.evidence.sync import SyncOptions, SyncReport
21
+
22
+ INDEX_INPUT_NAME = "index-input"
23
+ MANIFEST_NAME = "index-input.manifest.toml"
24
+
25
+ _EXCLUDED_DIR_NAMES = {
26
+ ".git",
27
+ ".quarto",
28
+ "_quarto",
29
+ "_site",
30
+ "site_libs",
31
+ "_tracecite",
32
+ ".tracecite",
33
+ "build",
34
+ ".pytest_cache",
35
+ ".venv",
36
+ "dist",
37
+ "__pycache__",
38
+ "model-cache",
39
+ }
40
+ _EXCLUDED_SUFFIXES = {".html"}
41
+ _RESOURCE_REFERENCE_RE = re.compile(
42
+ r"(?:!\[[^\]]*\]|\[[^\]]*\])\(([^)]+)\)|^\s*\[[^\]]+\]:\s*(\S+)",
43
+ re.MULTILINE,
44
+ )
45
+
46
+
47
+ @dataclass(frozen=True, slots=True)
48
+ class DocsIndexProfile:
49
+ input_root: Path
50
+ manifest_path: Path
51
+ database_path: Path
52
+ model_cache_dir: Path
53
+
54
+
55
+ @dataclass(frozen=True, slots=True)
56
+ class DocsIndexResult:
57
+ profile: DocsIndexProfile
58
+ tables_normalized: int
59
+ sync_report: SyncReport
60
+
61
+
62
+ def resolve_docs_index_profile(contract: DocsEvidenceContract) -> DocsIndexProfile:
63
+ database_path = contract.index_output.resolve()
64
+ return DocsIndexProfile(
65
+ input_root=(contract.staged_root / INDEX_INPUT_NAME).resolve(),
66
+ manifest_path=(contract.staged_root / MANIFEST_NAME).resolve(),
67
+ database_path=database_path,
68
+ model_cache_dir=(database_path.parent / "model-cache").resolve(),
69
+ )
70
+
71
+
72
+ def _inside(path: Path, root: Path) -> bool:
73
+ return path.resolve().is_relative_to(root.resolve())
74
+
75
+
76
+ def _should_skip_retained_path(path: Path, retained_root: Path) -> bool:
77
+ relative = path.relative_to(retained_root)
78
+ return (
79
+ not path.is_file()
80
+ or any(
81
+ part in _EXCLUDED_DIR_NAMES or part.startswith(".tracecite")
82
+ for part in relative.parts
83
+ )
84
+ or path.suffix.lower() in _EXCLUDED_SUFFIXES
85
+ or path.name.endswith("_files")
86
+ )
87
+
88
+
89
+ def _mirror_exclude_globs(contract: DocsEvidenceContract) -> tuple[str, ...]:
90
+ retained = contract.retained_root.resolve()
91
+ globs: set[str] = set()
92
+ for exclude in contract.publication_exclude:
93
+ target = exclude.resolve()
94
+ if not _inside(target, retained):
95
+ continue
96
+ relative = target.relative_to(retained).as_posix()
97
+ if not relative or relative == ".":
98
+ raise ValueError(
99
+ f"publication_exclude cannot exclude the entire retained root: {exclude}"
100
+ )
101
+ if ".." in relative.split("/"):
102
+ raise ValueError(
103
+ f"publication_exclude cannot be represented safely in the mirror: {exclude}"
104
+ )
105
+ globs.add(f"{relative}/**" if target.is_dir() else relative)
106
+ for name in sorted(_EXCLUDED_DIR_NAMES):
107
+ globs.add(f"**/{name}/**")
108
+ for suffix in sorted(_EXCLUDED_SUFFIXES):
109
+ globs.add(f"**/*{suffix}")
110
+ globs.add("**/*_files/**")
111
+ return tuple(sorted(globs))
112
+
113
+
114
+ def _retained_markdown_paths(contract: DocsEvidenceContract) -> list[Path]:
115
+ retained = contract.retained_root.resolve()
116
+ return [
117
+ path
118
+ for path in sorted(retained.rglob("*.md"))
119
+ if not _should_skip_retained_path(path, retained)
120
+ and not is_publication_excluded(path, contract)
121
+ ]
122
+
123
+
124
+ def _local_resource_destinations(markdown: str) -> set[str]:
125
+ destinations: set[str] = set()
126
+ for match in _RESOURCE_REFERENCE_RE.finditer(markdown):
127
+ destination = (match.group(1) or match.group(2) or "").strip()
128
+ if not destination or destination.startswith("<"):
129
+ continue
130
+ lowered = destination.lower()
131
+ if lowered.startswith(("http://", "https://", "mailto:")):
132
+ continue
133
+ if "#page=" in lowered or lowered.endswith(".pdf"):
134
+ continue
135
+ destination = destination.split("#", 1)[0].strip()
136
+ if destination:
137
+ destinations.add(destination)
138
+ return destinations
139
+
140
+
141
+ def _copy_resource_files(
142
+ *,
143
+ source_markdown: Path,
144
+ retained_root: Path,
145
+ mirror_root: Path,
146
+ original_markdown: str,
147
+ ) -> None:
148
+ for destination in sorted(_local_resource_destinations(original_markdown)):
149
+ source = (source_markdown.parent / destination).resolve()
150
+ if not source.is_file() or not _inside(source, retained_root):
151
+ continue
152
+ target = mirror_root / source.relative_to(retained_root)
153
+ target.parent.mkdir(parents=True, exist_ok=True)
154
+ shutil.copy2(source, target)
155
+
156
+
157
+ def _render_manifest(exclude_globs: tuple[str, ...]) -> str:
158
+ lines = ["schema_version = 1", "", "[[include]]", 'glob = "**/*.md"']
159
+ for pattern in exclude_globs:
160
+ lines.extend(["", "[[exclude]]", f'glob = "{pattern}"'])
161
+ return "\n".join(lines) + "\n"
162
+
163
+
164
+ def _snapshot_retained(retained_root: Path) -> dict[Path, bytes]:
165
+ return {
166
+ path.relative_to(retained_root): path.read_bytes()
167
+ for path in sorted(retained_root.rglob("*"))
168
+ if path.is_file()
169
+ }
170
+
171
+
172
+ def _assert_retained_unchanged(retained_root: Path, before: dict[Path, bytes]) -> None:
173
+ after = _snapshot_retained(retained_root)
174
+ if before != after:
175
+ changed = sorted(
176
+ set(before) ^ set(after)
177
+ | {path for path in before if before.get(path) != after.get(path)}
178
+ )
179
+ raise RuntimeError(
180
+ f"retained Markdown was mutated during index-input preparation: {changed[0]}"
181
+ )
182
+
183
+
184
+ def _atomic_promote_pair(replacements: tuple[tuple[Path, Path], ...]) -> None:
185
+ """Replace every destination with its staged temp path, or roll all of them back.
186
+
187
+ ``replacements`` is a sequence of ``(temp_path, destination)`` pairs. If any
188
+ individual replace fails partway through, every destination already moved is
189
+ restored to its prior content and no stray ``.previous`` backup is left behind.
190
+ """
191
+ backups: list[tuple[Path, Path]] = []
192
+ try:
193
+ for _temp, destination in replacements:
194
+ if destination.exists():
195
+ backup = destination.with_name(f".{destination.name}.previous")
196
+ if backup.exists():
197
+ shutil.rmtree(backup) if backup.is_dir() else backup.unlink()
198
+ os.replace(destination, backup)
199
+ backups.append((destination, backup))
200
+ for temp, destination in replacements:
201
+ os.replace(temp, destination)
202
+ except Exception:
203
+ for _temp, destination in replacements:
204
+ if destination.exists():
205
+ shutil.rmtree(
206
+ destination
207
+ ) if destination.is_dir() else destination.unlink()
208
+ for destination, backup in backups:
209
+ os.replace(backup, destination)
210
+ raise
211
+ else:
212
+ for _destination, backup in backups:
213
+ if backup.exists():
214
+ shutil.rmtree(backup) if backup.is_dir() else backup.unlink()
215
+
216
+
217
+ def prepare_docs_index_input(
218
+ contract: DocsEvidenceContract,
219
+ *,
220
+ repo_root: str | Path,
221
+ strict_tables: bool = False,
222
+ pandoc: str | Path | None = None,
223
+ allow_pipe_fallback: bool = False,
224
+ ) -> tuple[DocsIndexProfile, int]:
225
+ """Write the index-input mirror and manifest; return the profile and the number of normalised tables."""
226
+ root = Path(repo_root).resolve()
227
+ profile = resolve_docs_index_profile(contract)
228
+ retained = contract.retained_root.resolve()
229
+ before = _snapshot_retained(retained)
230
+
231
+ link_issues = validate_retained_source_links(contract, repo_root=root)
232
+ if link_issues:
233
+ raise ValueError("; ".join(link_issues))
234
+
235
+ manifest_text = _render_manifest(_mirror_exclude_globs(contract))
236
+ markdown_paths = _retained_markdown_paths(contract)
237
+
238
+ contract.staged_root.parent.mkdir(parents=True, exist_ok=True)
239
+ contract.staged_root.mkdir(parents=True, exist_ok=True)
240
+ temporary = Path(
241
+ tempfile.mkdtemp(prefix=".index-input-", dir=contract.staged_root.parent)
242
+ )
243
+ temp_input = temporary / INDEX_INPUT_NAME
244
+ temp_manifest = temporary / MANIFEST_NAME
245
+ tables_normalized = 0
246
+
247
+ try:
248
+ temp_input.mkdir(parents=True, exist_ok=True)
249
+ for source_path in markdown_paths:
250
+ relative = source_path.relative_to(retained)
251
+ original = source_path.read_text(encoding="utf-8")
252
+ transformed = augment_document_with_embedding_text(
253
+ original,
254
+ document_path=relative.as_posix(),
255
+ strict=strict_tables,
256
+ pandoc=pandoc,
257
+ allow_pipe_fallback=allow_pipe_fallback,
258
+ )
259
+ tables_normalized += len(transformed.tables)
260
+ destination = temp_input / relative
261
+ destination.parent.mkdir(parents=True, exist_ok=True)
262
+ destination.write_text(transformed.markdown, encoding="utf-8")
263
+ _copy_resource_files(
264
+ source_markdown=source_path,
265
+ retained_root=retained,
266
+ mirror_root=temp_input,
267
+ original_markdown=original,
268
+ )
269
+
270
+ temp_manifest.write_text(manifest_text, encoding="utf-8")
271
+
272
+ _atomic_promote_pair(
273
+ (
274
+ (temp_input, profile.input_root),
275
+ (temp_manifest, profile.manifest_path),
276
+ )
277
+ )
278
+ finally:
279
+ if temporary.exists():
280
+ shutil.rmtree(temporary)
281
+ _assert_retained_unchanged(retained, before)
282
+
283
+ return profile, tables_normalized
284
+
285
+
286
+ def sync_docs_index(
287
+ contract: DocsEvidenceContract,
288
+ *,
289
+ repo_root: str | Path,
290
+ options: SyncOptions | None = None,
291
+ embedder=None,
292
+ strict_tables: bool = False,
293
+ pandoc: str | Path | None = None,
294
+ allow_pipe_fallback: bool = False,
295
+ ) -> DocsIndexResult:
296
+ profile, tables_normalized = prepare_docs_index_input(
297
+ contract,
298
+ repo_root=repo_root,
299
+ strict_tables=strict_tables,
300
+ pandoc=pandoc,
301
+ allow_pipe_fallback=allow_pipe_fallback,
302
+ )
303
+ from tracecite.evidence import sync as sync_module
304
+
305
+ report = sync_module.sync(
306
+ profile.input_root,
307
+ profile.manifest_path,
308
+ profile.database_path,
309
+ options=options,
310
+ embedder=embedder,
311
+ model_cache_dir=profile.model_cache_dir,
312
+ )
313
+ return DocsIndexResult(profile, tables_normalized, report)
314
+
315
+
316
+ def search_docs_index(
317
+ contract: DocsEvidenceContract,
318
+ query: str,
319
+ *,
320
+ limit: int = 10,
321
+ fts_limit: int = 50,
322
+ vector_limit: int = 50,
323
+ embedder=None,
324
+ ) -> list[dict]:
325
+ from tracecite.evidence import schema
326
+ from tracecite.evidence.commands import active_embedding_model, hybrid_search
327
+
328
+ profile = resolve_docs_index_profile(contract)
329
+ if not profile.database_path.is_file():
330
+ return []
331
+ conn = schema.connect_existing(profile.database_path, read_only=True)
332
+ try:
333
+ schema.ensure_schema(conn)
334
+ embedder = embedder or active_embedding_model(conn, profile.model_cache_dir)
335
+ return hybrid_search(conn, query, limit, fts_limit, vector_limit, embedder)
336
+ finally:
337
+ conn.close()
338
+
339
+
340
+ def _index_input_freshness(
341
+ contract: DocsEvidenceContract, profile: DocsIndexProfile
342
+ ) -> tuple[str, ...]:
343
+ diagnostics: list[str] = []
344
+ if not profile.input_root.is_dir():
345
+ diagnostics.append("index-input mirror is missing")
346
+ return tuple(diagnostics)
347
+ if not profile.manifest_path.is_file():
348
+ diagnostics.append("index-input manifest is missing")
349
+ expected_paths = {
350
+ path.relative_to(contract.retained_root).as_posix()
351
+ for path in _retained_markdown_paths(contract)
352
+ }
353
+ actual_paths = {
354
+ path.relative_to(profile.input_root).as_posix()
355
+ for path in sorted(profile.input_root.rglob("*.md"))
356
+ if path.is_file()
357
+ }
358
+ for path in sorted(expected_paths - actual_paths):
359
+ diagnostics.append(f"index-input missing: {path}")
360
+ for path in sorted(actual_paths - expected_paths):
361
+ diagnostics.append(f"index-input extra: {path}")
362
+ for relative in sorted(expected_paths & actual_paths):
363
+ source = contract.retained_root / relative
364
+ mirror = profile.input_root / relative
365
+ expected = augment_document_with_embedding_text(
366
+ source.read_text(encoding="utf-8"),
367
+ document_path=relative,
368
+ ).markdown
369
+ if mirror.read_text(encoding="utf-8") != expected:
370
+ diagnostics.append(f"index-input stale (retained changed): {relative}")
371
+ for path in sorted(profile.input_root.rglob("*")):
372
+ if not path.is_file():
373
+ continue
374
+ relative = path.relative_to(profile.input_root)
375
+ if any(part in _EXCLUDED_DIR_NAMES for part in relative.parts):
376
+ diagnostics.append(f"index-input leaked artifact: {relative.as_posix()}")
377
+ if path.suffix.lower() in _EXCLUDED_SUFFIXES:
378
+ diagnostics.append(f"index-input leaked artifact: {relative.as_posix()}")
379
+ return tuple(diagnostics)
380
+
381
+
382
+ def _manifest_freshness(
383
+ contract: DocsEvidenceContract, profile: DocsIndexProfile
384
+ ) -> tuple[str, ...]:
385
+ if not profile.manifest_path.is_file():
386
+ return ()
387
+ expected = _render_manifest(_mirror_exclude_globs(contract))
388
+ try:
389
+ actual = profile.manifest_path.read_text(encoding="utf-8")
390
+ except OSError as exc:
391
+ return (f"index-input manifest is unreadable: {exc}",)
392
+ if actual != expected:
393
+ return (
394
+ "index-input manifest is stale or does not match the current docs contract",
395
+ )
396
+ return ()
397
+
398
+
399
+ def _database_freshness(profile: DocsIndexProfile) -> tuple[str, ...]:
400
+ if not profile.manifest_path.is_file():
401
+ return ()
402
+ from tracecite.evidence import manifest, schema
403
+
404
+ try:
405
+ rules = manifest.load_manifest(profile.manifest_path)
406
+ except Exception: # noqa: BLE001
407
+ # An unparsable manifest is already reported by _manifest_freshness;
408
+ # there is no usable source selection to compare the database against.
409
+ return ()
410
+ discovered = manifest.resolve_sources(profile.input_root, rules).selected
411
+ conn = schema.connect_existing(profile.database_path, read_only=True)
412
+ try:
413
+ schema.ensure_schema(conn)
414
+ rows = {
415
+ row["path"]: row["sha256"]
416
+ for row in conn.execute("SELECT path, sha256 FROM sources")
417
+ }
418
+ finally:
419
+ conn.close()
420
+ diagnostics: list[str] = []
421
+ for path in sorted(set(discovered) - set(rows)):
422
+ diagnostics.append(f"documentation index database missing source: {path}")
423
+ for path in sorted(set(rows) - set(discovered)):
424
+ diagnostics.append(f"documentation index database has stale source: {path}")
425
+ for path in sorted(set(discovered) & set(rows)):
426
+ if file_sha256(discovered[path]) != rows[path]:
427
+ diagnostics.append(
428
+ f"documentation index database is stale relative to mirror: {path}"
429
+ )
430
+ return tuple(diagnostics)
431
+
432
+
433
+ def docs_index_freshness_diagnostics(contract: DocsEvidenceContract) -> tuple[str, ...]:
434
+ profile = resolve_docs_index_profile(contract)
435
+ diagnostics = list(_index_input_freshness(contract, profile))
436
+ diagnostics.extend(_manifest_freshness(contract, profile))
437
+ if not profile.database_path.is_file():
438
+ diagnostics.append("documentation index database is missing")
439
+ else:
440
+ diagnostics.extend(_database_freshness(profile))
441
+ return tuple(diagnostics)
442
+
443
+
444
+ def doctor_docs_index(contract: DocsEvidenceContract) -> tuple[str, ...]:
445
+ profile = resolve_docs_index_profile(contract)
446
+ issues = list(docs_index_freshness_diagnostics(contract))
447
+ if not profile.database_path.is_file():
448
+ return tuple(issues)
449
+ from tracecite.evidence import schema
450
+ from tracecite.evidence import sync as sync_module
451
+
452
+ conn = schema.connect_existing(profile.database_path, read_only=True)
453
+ try:
454
+ schema.ensure_schema(conn)
455
+ issues.extend(sync_module.integrity_check(conn))
456
+ finally:
457
+ conn.close()
458
+ return tuple(issues)
@@ -0,0 +1,41 @@
1
+ """Public table-normalisation API."""
2
+
3
+ from .document import (
4
+ DocumentTransform,
5
+ augment_document_with_embedding_text,
6
+ normalise_document_tables,
7
+ )
8
+ from .html import html_table_to_markdown, normalise_html_table
9
+ from .models import (
10
+ NORMALISER_VERSION,
11
+ NormalisedTable,
12
+ TableContext,
13
+ TableDiagnostic,
14
+ TableNormalisationError,
15
+ )
16
+ from .normalise import normalise_pandoc_table
17
+ from .publish import computed_first_row_summary, knowledge_table, table_metadata_comment
18
+ from .render import render_debug_markdown, render_embedding_block
19
+ from .site import SiteExportResult, export_embedding_site, render_embedding_site
20
+
21
+ __all__ = [
22
+ "NORMALISER_VERSION",
23
+ "DocumentTransform",
24
+ "NormalisedTable",
25
+ "SiteExportResult",
26
+ "TableContext",
27
+ "TableDiagnostic",
28
+ "TableNormalisationError",
29
+ "augment_document_with_embedding_text",
30
+ "computed_first_row_summary",
31
+ "export_embedding_site",
32
+ "html_table_to_markdown",
33
+ "knowledge_table",
34
+ "normalise_document_tables",
35
+ "normalise_html_table",
36
+ "normalise_pandoc_table",
37
+ "render_debug_markdown",
38
+ "render_embedding_block",
39
+ "render_embedding_site",
40
+ "table_metadata_comment",
41
+ ]
@@ -0,0 +1,142 @@
1
+ """Small text helpers shared by Markdown and HTML table adapters."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+
7
+ from bs4 import BeautifulSoup
8
+
9
+ _ID_RE = re.compile(r"[^a-z0-9]+")
10
+ _TRAILING_ID_RE = re.compile(r"\s*\{#([A-Za-z][A-Za-z0-9_.:-]*)\}\s*$")
11
+ _NUMBER_WITH_UNIT_RE = re.compile(
12
+ r"^\s*[-+]?\d[\d,]*(?:\.\d+)?(?:[eE][-+]?\d+)?\s*"
13
+ r"([A-Za-zµμΩ°%$€£¥][A-Za-z0-9µμΩ°/%$€£¥·^*._-]*)\s*$"
14
+ )
15
+ _HEADER_UNIT_RE = re.compile(r"(?:\(([^()]*)\)|\[([^\[\]]*)\])\s*$")
16
+ _PIPE_SEPARATOR_RE = re.compile(r":?-{3,}:?")
17
+ _COMMON_LOWER_UNITS = {
18
+ "bar",
19
+ "degc",
20
+ "degf",
21
+ "g",
22
+ "h",
23
+ "hz",
24
+ "kg",
25
+ "km",
26
+ "m",
27
+ "min",
28
+ "mm",
29
+ "ms",
30
+ "pa",
31
+ "pu",
32
+ "p.u.",
33
+ "s",
34
+ }
35
+
36
+
37
+ def slug(value: str, fallback: str = "table") -> str:
38
+ return _ID_RE.sub("-", value.lower()).strip("-") or fallback
39
+
40
+
41
+ def strip_caption_id(caption: str) -> tuple[str, str | None]:
42
+ match = _TRAILING_ID_RE.search(caption)
43
+ if not match:
44
+ return caption.strip(), None
45
+ return caption[: match.start()].strip(), match.group(1)
46
+
47
+
48
+ def collapse_space(value: str) -> str:
49
+ return re.sub(r"\s+", " ", value).strip()
50
+
51
+
52
+ def split_pipe_row(line: str, clean=str.strip) -> list[str]:
53
+ """Split one Markdown pipe-table row, honouring backslash escapes."""
54
+ stripped = line.strip().removeprefix("|")
55
+ if stripped.endswith("|") and not stripped.endswith("\\|"):
56
+ stripped = stripped[:-1]
57
+ cells: list[str] = []
58
+ current: list[str] = []
59
+ escaped = False
60
+ for character in stripped:
61
+ if escaped:
62
+ current.append(character)
63
+ escaped = False
64
+ elif character == "\\":
65
+ escaped = True
66
+ elif character == "|":
67
+ cells.append(clean("".join(current)))
68
+ current = []
69
+ else:
70
+ current.append(character)
71
+ if escaped:
72
+ current.append("\\")
73
+ cells.append(clean("".join(current)))
74
+ return cells
75
+
76
+
77
+ def is_pipe_table_start(lines: list[str], index: int) -> bool:
78
+ """Whether ``lines[index]`` is a pipe-table header followed by its separator row."""
79
+ if (
80
+ index + 1 >= len(lines)
81
+ or "|" not in lines[index]
82
+ or "|" not in lines[index + 1]
83
+ ):
84
+ return False
85
+ separator = split_pipe_row(lines[index + 1])
86
+ return len(split_pipe_row(lines[index])) == len(separator) and all(
87
+ _PIPE_SEPARATOR_RE.fullmatch(value) for value in separator
88
+ )
89
+
90
+
91
+ def strip_html(value: str) -> str:
92
+ return collapse_space(BeautifulSoup(value, "html.parser").get_text(" ", strip=True))
93
+
94
+
95
+ def escape_pipe_cell(value: str) -> str:
96
+ text = str(value).replace("\\", "\\\\").replace("|", "\\|")
97
+ return text.replace("\n", "<br>")
98
+
99
+
100
+ def escape_markdown_inline(value: str) -> str:
101
+ text = str(value)
102
+ for character in ("\\", "|", "$", "*", "_", "~", "`", "[", "]", "<", ">"):
103
+ text = text.replace(character, f"\\{character}")
104
+ return text
105
+
106
+
107
+ def normalise_label(value: str) -> str:
108
+ if header_unit(value):
109
+ value = _HEADER_UNIT_RE.sub("", value)
110
+ return _ID_RE.sub(" ", value.lower()).strip()
111
+
112
+
113
+ def header_unit(value: str) -> str | None:
114
+ match = _HEADER_UNIT_RE.search(value)
115
+ if not match:
116
+ return None
117
+ unit = collapse_space(match.group(1) or match.group(2) or "")
118
+ return unit if _looks_like_unit(unit) else None
119
+
120
+
121
+ def cell_unit(value: str) -> str | None:
122
+ match = _NUMBER_WITH_UNIT_RE.match(value)
123
+ return collapse_space(match.group(1)) if match else None
124
+
125
+
126
+ def is_missing(value: str) -> bool:
127
+ return value.strip().lower() in {"", "na", "n/a", "nan", "null", "not available"}
128
+
129
+
130
+ def _looks_like_unit(value: str) -> bool:
131
+ compact = collapse_space(value)
132
+ if not compact or len(compact) > 32:
133
+ return False
134
+ if any(
135
+ marker in compact for marker in ("°", "%", "/", "$", "€", "£", "¥", "·", "^")
136
+ ):
137
+ return True
138
+ if " " in compact:
139
+ return False
140
+ if compact.casefold() in _COMMON_LOWER_UNITS:
141
+ return True
142
+ return any(character.isupper() or character.isdigit() for character in compact)