File size: 2,598 Bytes
62787e2 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 | import re
from typing import List, Sequence
_STACKED_HEADER_COLLAPSES = [
{
"name": "net_unrealized_appreciation_depreciation",
"rows": [
["", "Net Unrealized", ""],
["", "Appreciation", ""],
["", "(Depreciation)", "Net Unrealized"],
["", "as a % of", "Appreciation"],
["", "Trust Capital", "(Depreciation)"],
],
"replacement": [
"",
"**Net Unrealized<br>Appreciation<br>(Depreciation)<br>as a % of<br>Trust Capital**",
"**Net Unrealized<br>Appreciation<br>(Depreciation)**",
],
},
]
def _split_markdown_row(line: str) -> List[str] | None:
stripped = line.strip()
if not stripped.startswith("|") or not stripped.endswith("|"):
return None
return [cell.strip() for cell in stripped[1:-1].split("|")]
def _normalize_match_cell(cell: str) -> str:
cell = re.sub(r"</?u>", "", cell, flags=re.IGNORECASE)
cell = re.sub(r"(?i)<br\s*/?>", " ", cell)
cell = cell.replace("**", "")
cell = cell.replace(" ", " ")
cell = re.sub(r"\s+", " ", cell)
if cell.strip().lower() == "nan":
return ""
return cell.strip()
def _row_matches(line: str, expected_cells: Sequence[str]) -> bool:
cells = _split_markdown_row(line)
if cells is None or len(cells) != len(expected_cells):
return False
return all(
_normalize_match_cell(actual) == expected
for actual, expected in zip(cells, expected_cells)
)
def _format_markdown_row(cells: Sequence[str]) -> str:
return "| " + " | ".join(cells) + " |"
def apply_markdown_hardcodes(markdown_text: str) -> str:
"""
Apply narrow markdown-level hardcoded fixes for recurring parser edge cases.
These are intentionally exact-pattern transforms so they do not affect
unrelated tables.
"""
lines = markdown_text.splitlines()
rewritten: List[str] = []
i = 0
while i < len(lines):
matched = False
for hardcode in _STACKED_HEADER_COLLAPSES:
expected_rows = hardcode["rows"]
span = len(expected_rows)
if i + span > len(lines):
continue
if all(_row_matches(lines[i + offset], expected_rows[offset]) for offset in range(span)):
rewritten.append(_format_markdown_row(hardcode["replacement"]))
i += span
matched = True
break
if matched:
continue
rewritten.append(lines[i])
i += 1
return "\n".join(rewritten)
|