Repository navigation
Expand file tree
/
Copy pathhtml2md.py
More file actions
555 lines (445 loc) · 17.7 KB
/
Copy pathhtml2md.py
File metadata and controls
555 lines (445 loc) · 17.7 KB
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
"""Convert PCG source HTML files to Markdown.
Parses the positioned-layout HTML files generated by pdf2html.py and
converts them to clean Markdown, preserving bold/italic styling,
headings (detected from font size), internal links (matched from
overlay <a> elements), and the Plan de comptes layout.
Usage:
uv run html2md.py [--year YEAR] [--all] [--output-dir DIR]
Examples:
uv run html2md.py --year 2026 # Convert HTMLs for a specific year
uv run html2md.py --all # Convert all HTMLs across all years
uv run html2md.py --all --output-dir out # Specify a custom output directory
"""
from __future__ import annotations
import argparse
import re
import sys
from html.parser import HTMLParser
from pathlib import Path
SOURCES_DIR = Path(__file__).resolve().parent.parent / "PCG" / "sources"
# ---------------------------------------------------------------------------
# Font-size → heading level thresholds (same as pdf2html output)
# ---------------------------------------------------------------------------
_HEADING_THRESHOLDS: list[tuple[float, int]] = [
(20.0, 1), # Livre
(14.0, 2), # Title page items
(12.0, 3), # Chapitre
(10.6, 4), # Section / Sous-section (bold 10.6)
]
# ---------------------------------------------------------------------------
# Patterns
# ---------------------------------------------------------------------------
_ARTICLE_RE = re.compile(r"^Art\.\s+\d")
_DOT_LEADER_RE = re.compile(r"\s*\.{2,}\s*\d*\s*(\*{0,3})$")
# Header / footer patterns.
_HEADER_RE = re.compile(
r"^Version (?:du )?1er? janvier \d{4}\s*(?:Page \d+ sur \d+\s*)?$",
)
_PAGE_NUMBER_RE = re.compile(r"^Page \d+ sur \d+\s*$")
_RECUEIL_HEADER_RE = re.compile(
r"^RECUEIL DES NORMES COMPTABLES FRANÇAISES\s*$",
)
_RECUEIL_VERSION_RE = re.compile(
r"^Version du 1er? janvier \d{4}\s*\d*\s*$",
)
# Extract numeric value from a CSS property like "top:123.4pt".
_CSS_PT_RE = re.compile(r"([\d.]+)pt")
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
def _parse_pt(value: str) -> float:
"""Parse a CSS pt value like '123.4pt' and return the float."""
m = _CSS_PT_RE.search(value)
return float(m.group(1)) if m else 0.0
def _parse_style(style: str) -> dict[str, str]:
"""Parse an inline CSS style string into a dict."""
result: dict[str, str] = {}
for part in style.split(";"):
part = part.strip()
if ":" in part:
key, _, val = part.partition(":")
result[key.strip()] = val.strip()
return result
def _heading_level(size: float) -> int | None:
"""Return the Markdown heading level for a given font *size*, or None."""
for min_size, level in _HEADING_THRESHOLDS:
if size >= min_size:
return level
return None
def _is_header_or_footer(text: str) -> bool:
"""Return True if *text* matches a known repetitive header/footer."""
return bool(
_HEADER_RE.match(text)
or _PAGE_NUMBER_RE.match(text)
or _RECUEIL_HEADER_RE.match(text)
or _RECUEIL_VERSION_RE.match(text)
)
def _wrap_style(text: str, *, bold: bool, italic: bool) -> str:
"""Wrap *text* with Markdown bold/italic markers.
Leading and trailing whitespace is moved outside the markers so that
``*`` / ``**`` are always adjacent to non-space characters (required
by CommonMark for emphasis to be recognised).
"""
if not bold and not italic:
return text
lstripped = text.lstrip()
leading = text[: len(text) - len(lstripped)]
stripped = lstripped.rstrip()
trailing = lstripped[len(stripped):]
if not stripped:
return text
if bold and italic:
return f"{leading}***{stripped}***{trailing}"
if bold:
return f"{leading}**{stripped}**{trailing}"
return f"{leading}*{stripped}*{trailing}"
def _merge_styled_runs(
runs: list[tuple[str, bool, bool]],
) -> str:
"""Merge consecutive runs sharing the same (bold, italic) style."""
if not runs:
return ""
groups: list[tuple[str, bool, bool]] = []
cur_text, cur_b, cur_i = runs[0]
for text, b, i in runs[1:]:
if b == cur_b and i == cur_i:
cur_text += text
else:
groups.append((cur_text, cur_b, cur_i))
cur_text, cur_b, cur_i = text, b, i
groups.append((cur_text, cur_b, cur_i))
parts: list[str] = []
for text, bold, italic in groups:
parts.append(_wrap_style(text, bold=bold, italic=italic))
return "".join(parts)
def _strip_dot_leaders(text: str) -> str:
"""Remove dot leaders and trailing page numbers from *text*."""
return re.sub(r"\s*\.{2,}\s*\d*\s*(\*{0,3})$", r"\1", text)
# ---------------------------------------------------------------------------
# Structured data from a single <p> element
# ---------------------------------------------------------------------------
class _PLine:
"""A single <p> element from the positioned HTML."""
__slots__ = ("top", "left", "is_italic", "runs", "max_font_size")
def __init__(
self,
top: float,
left: float,
is_italic: bool,
) -> None:
self.top = top
self.left = left
self.is_italic = is_italic
self.runs: list[tuple[str, bool, bool]] = [] # (text, bold, italic)
self.max_font_size: float = 0.0
def add_text(self, text: str, bold: bool, font_size: float) -> None:
italic = self.is_italic
self.runs.append((text, bold, italic))
if font_size > self.max_font_size:
self.max_font_size = font_size
class _Link:
"""A positioned <a> overlay."""
__slots__ = ("href", "left", "top", "right", "bottom")
def __init__(
self, href: str, left: float, top: float, width: float, height: float
) -> None:
self.href = href
self.left = left
self.top = top
self.right = left + width
self.bottom = top + height
# ---------------------------------------------------------------------------
# HTML parser
# ---------------------------------------------------------------------------
class _PCGHTMLParser(HTMLParser):
"""Parse the positioned-layout HTML produced by pdf2html.py."""
def __init__(self) -> None:
super().__init__()
# Results per page: list of (page_id, lines, links).
self.pages: list[tuple[str, list[_PLine], list[_Link]]] = []
# Parser state.
self._current_page_id: str | None = None
self._current_lines: list[_PLine] = []
self._current_links: list[_Link] = []
self._in_p = False
self._current_pline: _PLine | None = None
self._in_bold = False
self._current_font_size: float = 10.0
# Stack depth for elements we skip (img, sup, etc.)
self._skip_depth = 0
def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
attr = dict(attrs)
if tag == "div":
cls = attr.get("class") or ""
div_id = attr.get("id") or ""
if "page" in cls and div_id.startswith("page-"):
self._current_page_id = div_id
self._current_lines = []
self._current_links = []
return
if tag == "a":
href = attr.get("href") or ""
style_str = attr.get("style") or ""
if href and "position:absolute" in style_str:
style = _parse_style(style_str)
left = _parse_pt(style.get("left", "0"))
top = _parse_pt(style.get("top", "0"))
width = _parse_pt(style.get("width", "0"))
height = _parse_pt(style.get("height", "0"))
self._current_links.append(
_Link(href, left, top, width, height)
)
return
if tag == "p":
style_str = attr.get("style") or ""
style = _parse_style(style_str)
top = _parse_pt(style.get("top", "0"))
left = _parse_pt(style.get("left", "0"))
is_italic = "italic" in style.get("font-style", "")
self._current_pline = _PLine(top, left, is_italic)
self._in_p = True
return
if tag == "b" and self._in_p:
self._in_bold = True
return
if tag == "span" and self._in_p:
style_str = attr.get("style") or ""
# Extract font-size from span style.
m = re.search(r"font-size:([\d.]+)pt", style_str)
if m:
self._current_font_size = float(m.group(1))
return
if tag == "sup" and self._in_p:
# Superscript text — include it inline.
return
# Void elements — just ignore, no skip depth (they never close).
if tag in ("img", "meta", "br", "hr", "link"):
return
# Elements with content to skip.
if tag in ("style", "title", "head", "script"):
self._skip_depth += 1
return
def handle_endtag(self, tag: str) -> None:
if tag in ("style", "title", "head", "script"):
if self._skip_depth > 0:
self._skip_depth -= 1
return
if tag == "div" and self._current_page_id is not None:
self.pages.append((
self._current_page_id,
self._current_lines,
self._current_links,
))
self._current_page_id = None
return
if tag == "p" and self._in_p:
if self._current_pline is not None:
self._current_lines.append(self._current_pline)
self._in_p = False
self._current_pline = None
self._in_bold = False
self._current_font_size = 10.0
return
if tag == "b" and self._in_p:
self._in_bold = False
return
def handle_data(self, data: str) -> None:
if self._skip_depth > 0:
return
if self._in_p and self._current_pline is not None:
self._current_pline.add_text(
data, self._in_bold, self._current_font_size
)
def handle_entityref(self, name: str) -> None:
from html import unescape
self.handle_data(unescape(f"&{name};"))
def handle_charref(self, name: str) -> None:
from html import unescape
self.handle_data(unescape(f"&#{name};"))
# ---------------------------------------------------------------------------
# Merge same-y lines & produce Markdown
# ---------------------------------------------------------------------------
def _find_link(
top: float,
left: float,
right: float,
links: list[_Link],
) -> str | None:
"""Find a link overlay that covers the given line position."""
for link in links:
# Check vertical overlap.
if top < link.bottom and top >= link.top - 2.0:
# Check horizontal overlap.
if left < link.right and right > link.left:
return link.href
return None
def _merge_same_y(
plines: list[_PLine],
*,
y_tolerance: float = 2.0,
) -> list[_PLine]:
"""Group <p> elements at the same y-coordinate into single logical rows."""
if not plines:
return []
# Sort by top, then left.
sorted_lines = sorted(plines, key=lambda p: (p.top, p.left))
rows: list[list[_PLine]] = []
current_y = sorted_lines[0].top
current_group: list[_PLine] = [sorted_lines[0]]
for pline in sorted_lines[1:]:
if abs(pline.top - current_y) <= y_tolerance:
current_group.append(pline)
else:
rows.append(current_group)
current_y = pline.top
current_group = [pline]
rows.append(current_group)
result: list[_PLine] = []
for row in rows:
row.sort(key=lambda p: p.left)
merged = _PLine(row[0].top, row[0].left, row[0].is_italic)
merged.max_font_size = row[0].max_font_size
for idx, pline in enumerate(row):
if idx > 0:
# Space separator between fragments on the same row.
if merged.runs and not merged.runs[-1][0].endswith(" "):
last_text, last_b, last_i = merged.runs[-1]
merged.runs[-1] = (last_text + " ", last_b, last_i)
merged.runs.extend(pline.runs)
if pline.max_font_size > merged.max_font_size:
merged.max_font_size = pline.max_font_size
if pline.is_italic:
merged.is_italic = True
else:
merged.runs = list(pline.runs)
result.append(merged)
return result
def _estimate_right(pline: _PLine) -> float:
"""Estimate the right edge of a line from its left + rough text width."""
# Rough: ~6pt per char at 10pt font. Good enough for link matching.
total_chars = sum(len(t) for t, _, _ in pline.runs)
return pline.left + total_chars * 6.0
def _process_page(
page_id: str,
plines: list[_PLine],
links: list[_Link],
) -> list[str]:
"""Convert parsed <p> elements from one page into Markdown lines."""
merged = _merge_same_y(plines)
lines: list[str] = []
lines.append(f'<a id="{page_id}"></a>')
lines.append("")
for pline in merged:
joined = _merge_styled_runs(pline.runs).strip()
if not joined:
continue
# Skip headers/footers.
plain = re.sub(r"[*]+", "", joined).strip()
if _is_header_or_footer(plain):
continue
# Detect and remove dot leaders (TOC lines).
had_dot_leaders = bool(_DOT_LEADER_RE.search(
re.sub(r"[*]+", "", joined),
))
joined = _strip_dot_leaders(joined)
joined = joined.rstrip()
if not joined or not re.sub(r"[*]+", "", joined).strip():
continue
# Check if this line should be a heading.
# TOC entries use the same font sizes as real headings but are
# identified by the dot leaders we just stripped.
heading = (
_heading_level(pline.max_font_size) if not had_dot_leaders else None
)
if heading is not None:
heading_text = re.sub(r"\*+", "", joined).strip()
joined = f"{'#' * heading} {heading_text}"
if lines and lines[-1] != "":
lines.append("")
# Wrap in a link if one overlaps this line.
if heading is None:
right = _estimate_right(pline)
href = _find_link(pline.top, pline.left, right, links)
if href:
joined = f"[{joined}]({href})"
# Insert blank line before article references.
plain_check = re.sub(r"[*\\[\\]()#]+", "", joined).strip()
if _ARTICLE_RE.match(plain_check):
if lines and lines[-1] != "":
lines.append("")
# Trailing double-space for hard line breaks on non-heading lines.
if heading is None:
joined += " "
lines.append(joined)
return lines
def _collapse_blank_lines(text: str) -> str:
"""Collapse runs of 3+ blank lines down to 2."""
return re.sub(r"\n{3,}", "\n\n", text)
# ---------------------------------------------------------------------------
# Public API
# ---------------------------------------------------------------------------
def convert_html_to_md(html_path: Path, md_path: Path) -> None:
"""Convert a single HTML file to Markdown."""
html = html_path.read_text(encoding="utf-8")
parser = _PCGHTMLParser()
parser.feed(html)
all_lines: list[str] = []
for page_id, plines, links in parser.pages:
page_lines = _process_page(page_id, plines, links)
all_lines.extend(page_lines)
all_lines.append("")
output = "\n".join(all_lines)
output = _collapse_blank_lines(output)
output = output.strip() + "\n"
md_path.write_text(output, encoding="utf-8")
def discover_htmls(year: str | None) -> list[Path]:
"""Find HTML files in the sources directory, optionally filtered by year."""
if year:
year_dir = SOURCES_DIR / year
if not year_dir.is_dir():
print(
f"Error: no source directory found for year {year} at {year_dir}",
file=sys.stderr,
)
sys.exit(1)
return sorted(year_dir.glob("*.html"))
# All years
return sorted(SOURCES_DIR.rglob("*.html"))
def main() -> None:
parser = argparse.ArgumentParser(
description="Convert PCG source HTML files to Markdown.",
)
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument("--year", help="Year to process (e.g. 2026)")
group.add_argument("--all", action="store_true", help="Process all years")
parser.add_argument(
"--output-dir",
default=None,
help=(
"Output directory for Markdown files "
"(default: same directory as source HTML)"
),
)
args = parser.parse_args()
htmls = discover_htmls(args.year if not args.all else None)
if not htmls:
print("No HTML files found.", file=sys.stderr)
sys.exit(1)
print(f"Found {len(htmls)} HTML(s) to convert.\n")
for html_path in htmls:
if args.output_dir:
out_dir = Path(args.output_dir)
relative = html_path.relative_to(SOURCES_DIR)
md_path = out_dir / relative.with_suffix(".md")
else:
md_path = html_path.with_suffix(".md")
md_path.parent.mkdir(parents=True, exist_ok=True)
print(f" {html_path.relative_to(SOURCES_DIR)} -> {md_path}")
try:
convert_html_to_md(html_path, md_path)
except Exception as exc:
print(f" ERROR: {exc}", file=sys.stderr)
continue
print("\nDone.")
if __name__ == "__main__":
main()