forked from mofosyne/mediawiki-to-markdown-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhtml_convert.py
More file actions
2676 lines (2386 loc) · 99.8 KB
/
Copy pathhtml_convert.py
File metadata and controls
2676 lines (2386 loc) · 99.8 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
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import requests
from lxml import html
import argparse
import re
import urllib.parse
import json
from dataclasses import dataclass, field
from typing import Optional, Any, Tuple
from dataclasses_json import DataClassJsonMixin
import uuid
import unicodedata
from datetime import datetime
import zipfile
import mimetypes
import webcolors
import minify_html
import re
import colorsys
from colormath.color_objects import sRGBColor, LabColor
from colormath.color_conversions import convert_color
import colormath.color_diff
from progressbar import progressbar
pages = open("all_pages.txt", "r").read().strip().split("\n")
BASE = "https://wiki.makerspace.se"
BASE_HOSTNAME = urllib.parse.urlparse(BASE).hostname
CACHE_DIR = "cache_html"
OUTPUT_DIR = "output"
os.makedirs(CACHE_DIR, exist_ok=True)
VALID_COLORS = [
"#FDEA9B",
"#FED46A",
"#FA551E",
"#B4DC19",
"#C8AFF0",
"#3CBEFC",
]
BLOCK_ELEMENTS = [
"div",
"p",
"h1",
"h2",
"h3",
"h4",
"h5",
"h6",
"blockquote",
"ul",
"ol",
"li",
"table",
"tr",
"td",
"th",
]
MIRRORED_EXTENSIONS = [
".svg",
".png",
".jpg",
".jpeg",
".gif",
".pdf",
".webp",
".txt",
".md",
".zip",
".stl",
".gcode",
".mp4",
".webm",
".ogv",
".mov",
]
# Replace <sup>...</sup> with unicode superscript equivalents
def sup_to_unicode(match):
sup_map = {
"0": "⁰",
"1": "¹",
"2": "²",
"3": "³",
"4": "⁴",
"5": "⁵",
"6": "⁶",
"7": "⁷",
"8": "⁸",
"9": "⁹",
"+": "⁺",
"-": "⁻",
"=": "⁼",
"(": "⁽",
")": "⁾",
"n": "ⁿ",
"i": "ⁱ",
"a": "ᵃ",
"b": "ᵇ",
"c": "ᶜ",
"d": "ᵈ",
"e": "ᵉ",
"f": "ᶠ",
"g": "ᵍ",
"h": "ʰ",
"j": "ʲ",
"k": "ᵏ",
"l": "ˡ",
"m": "ᵐ",
"o": "ᵒ",
"p": "ᵖ",
"r": "ʳ",
"s": "ˢ",
"t": "ᵗ",
"u": "ᵘ",
"v": "ᵛ",
"w": "ʷ",
"x": "ˣ",
"y": "ʸ",
"z": "ᶻ",
"A": "ᴬ",
"B": "ᴮ",
"D": "ᴰ",
"E": "ᴱ",
"G": "ᴳ",
"H": "ᴴ",
"I": "ᴵ",
"J": "ᴶ",
"K": "ᴷ",
"L": "ᴸ",
"M": "ᴹ",
"N": "ᴺ",
"O": "ᴼ",
"P": "ᴾ",
"R": "ᴿ",
"T": "ᵀ",
"U": "ᵁ",
"V": "ⱽ",
"W": "ᵂ",
}
text = match.group(1)
return "".join(list(sup_map.get(c, c) for c in text))
def heading_to_slug(heading: str) -> str:
replacement = "-"
heading = re.sub(
r"[\s!\"#$%&'\.()*+,\/:;<=>?@\[\]\\^_`{|}~]+",
replacement,
heading,
flags=re.UNICODE,
)
heading = heading.lower()
heading = heading.strip(replacement)
return heading
def delta_e_cie2000(color1, color2, Kl=1, Kc=1, Kh=1):
"""
Calculates the Delta E (CIE2000) of two colors.
"""
color1_vector = colormath.color_diff._get_lab_color1_vector(color1)
color2_matrix = colormath.color_diff._get_lab_color2_matrix(color2)
delta_e = colormath.color_diff.color_diff_matrix.delta_e_cie2000(
color1_vector, color2_matrix, Kl=Kl, Kc=Kc, Kh=Kh
)[0]
return float(delta_e)
def nearest_valid_color(hex_color):
def hex_to_rgb(hexstr):
hexstr = hexstr.lstrip("#")
if len(hexstr) == 3:
hexstr = "".join([c * 2 for c in hexstr])
return tuple(int(hexstr[i : i + 2], 16) for i in (0, 2, 4))
try:
rgb = hex_to_rgb(hex_color)
color1_rgb = sRGBColor(rgb[0], rgb[1], rgb[2], is_upscaled=True)
color1_lab = convert_color(color1_rgb, LabColor)
except Exception:
return VALID_COLORS[0] # fallback
min_dist = float("inf")
nearest = VALID_COLORS[0]
for valid in VALID_COLORS:
v_rgb = hex_to_rgb(valid)
color2_rgb = sRGBColor(v_rgb[0], v_rgb[1], v_rgb[2], is_upscaled=True)
color2_lab = convert_color(color2_rgb, LabColor)
dist = delta_e_cie2000(color1_lab, color2_lab)
if dist < min_dist:
min_dist = dist
nearest = valid
return nearest
@dataclass
class DocumentStructureItem(DataClassJsonMixin):
id: str # UUID of the document
url: str
title: str
children: list["DocumentStructureItem"]
@dataclass
class Sort(DataClassJsonMixin):
field: str
direction: str
@dataclass
class OutlineCollection(DataClassJsonMixin):
id: str # UUID of the collection
urlId: str # Example: um8KoiqAPm
name: str
data: dict[Any, Any]
icon: Optional[str]
permission: Optional[Any]
commenting: bool
sharing: bool
documentStructure: list[DocumentStructureItem]
index: str = ","
color: Optional[str] = None
sort: Sort = field(default_factory=lambda: Sort(field="index", direction="asc"))
createdAt: Optional[str] = None # ISO 8601 format
updatedAt: Optional[str] = None # ISO 8601 format
deletedAt: Optional[str] = None # ISO 8601 format
archivedAt: Optional[str] = None # ISO 8601 format
@dataclass
class OutlinePage(DataClassJsonMixin):
createdById: str # UUID of the user who created the page
createdByName: str
createdByEmail: str
createdAt: Optional[str] # ISO 8601 format
updatedAt: Optional[str] # ISO 8601 format
publishedAt: Optional[str] # ISO 8601 format
fullWidth: bool
template: bool
parentDocumentId: Optional[str]
id: str #
urlId: str
title: str
icon: Optional[str]
color: Optional[str]
data: dict[Any, Any]
@dataclass
class OutlineExport(DataClassJsonMixin):
collection: OutlineCollection
documents: dict[str, OutlinePage]
attachments: dict[Any, Any]
# {
# "exportVersion": 1,
# "version": "0.84.0",
# "createdAt": "2025-07-06T19:19:21.827Z",
# "createdById": "f74221f0-4749-41f7-b327-5ed81752ef12",
# "createdByEmail": "aron.granberg@gmail.com"
# }
@dataclass
class OutlineExportMetadata(DataClassJsonMixin):
exportVersion: int = 1
version: str = "0.84.0"
createdAt: Optional[str] = None # ISO 8601 format
createdById: Optional[str] = None # UUID of the user who created the export
createdByEmail: Optional[str] = None # Email of the user who created the export
def mediawiki_slugify(value):
value = re.sub(r"[\s]+", "_", value)
return value
def outline_doc_url(doc: OutlinePage) -> str:
return f"/doc/{outline_slugify(doc.title)}-{doc.urlId}"
# Make a safe urlId from page name
def outline_slugify(value):
value = unicodedata.normalize("NFKD", value)
value = value.encode("ascii", "ignore").decode("ascii")
value = re.sub(r"[\s_]+", "-", value)
value = re.sub(r"[^\w\d-]", "", value)
return value.lower()
# Write an old-wiki-path -> Outline-URL map consumed by nginx as
# `map $uri $wiki_redirect { include wiki-redirects.map; }`.
#
# Key coverage: the wiki serves pages as "/Title" ($wgArticlePath = "/$1") and
# "/index.php/Title" ($wgUsePathInfo). The "/index.php?title=Title" query form
# is invisible in $uri; the vhost config must normalize it to "/Title" itself.
# Each title is emitted with underscores (MediaWiki canonical) and with
# spaces, because nginx percent-decodes $uri so "%20" links arrive as literal
# spaces. Case differences cost nothing: nginx map string matching is
# case-insensitive, which also mirrors MediaWiki's case-insensitive first
# letter.
#
# Contract: the map is only valid for an Outline instance imported from the
# export.zip of the same run, because urlIds are regenerated every run.
def write_nginx_redirect_map(
export: OutlineExport, redirects: dict[str, str], real_page_ids: set[str]
):
def nginx_quote(value: str) -> str:
return '"' + value.replace("\\", "\\\\").replace('"', '\\"') + '"'
# Lowercased key -> (key as emitted, target URL). nginx rejects duplicate
# map keys, and matching is case-insensitive, so dedup must be too.
entries: dict[str, tuple[str, str]] = {}
def add(title_variant: str, target_url: str):
for key in ("/" + title_variant, "/index.php/" + title_variant):
existing = entries.get(key.lower())
if existing is not None:
if existing[1] != target_url:
print(
f"Warning: conflicting redirect map entries for {key!r}: "
f"{existing[1]} vs {target_url}"
)
continue
entries[key.lower()] = (key, target_url)
def add_title_variants(title: str, target_url: str):
canonical = mediawiki_slugify(title)
add(canonical, target_url)
spaced = canonical.replace("_", " ")
if spaced != canonical:
add(spaced, target_url)
slug_to_doc: dict[str, OutlinePage] = {}
for doc in export.documents.values():
slug_to_doc.setdefault(mediawiki_slugify(doc.title), doc)
for doc in export.documents.values():
if doc.id in real_page_ids:
add_title_variants(doc.title, outline_doc_url(doc))
else:
# Synthetic category folder: point the old category page URLs at it.
add_title_variants("Kategori:" + doc.title, outline_doc_url(doc))
add_title_variants("Category:" + doc.title, outline_doc_url(doc))
# Redirect pages never become documents; send them to their (already
# chain-resolved) target's URL.
for src_slug, target_slug in redirects.items():
target_doc = slug_to_doc.get(target_slug)
if target_doc is None:
print(
f"Warning: redirect target {target_slug!r} has no document; "
f"skipping map entry for {src_slug!r}"
)
continue
add_title_variants(src_slug, outline_doc_url(target_doc))
map_path = os.path.join(OUTPUT_DIR, "wiki-redirects.map")
with open(map_path, "w", encoding="utf-8") as f:
for key, target_url in sorted(entries.values()):
f.write(f"{nginx_quote(key)} {nginx_quote(target_url)};\n")
print(f"Created {map_path} ({len(entries)} entries)")
def get_inner_html(page):
cache_path = os.path.join(CACHE_DIR, f"{page.replace('/', '_')}.html")
if os.path.exists(cache_path):
# print(f"Using cached: {cache_path}")
with open(cache_path, "r", encoding="utf-8") as f:
return f.read()
url = BASE + "/" + page
response = requests.get(url + "?redirect=no")
if response.status_code == 200:
tree = html.fromstring(response.text)
content_div = tree.xpath('//div[@id="mw-content-text"]')
if content_div:
html_content = html.tostring(
content_div[0], pretty_print=True, encoding="unicode"
)
with open(cache_path, "w", encoding="utf-8") as f:
f.write(html_content)
print(f"Saved content for {page} to {cache_path}")
return html_content
else:
print(f"Content not found for {page}")
return None
else:
print(f"Failed to fetch {url} (status {response.status_code})")
return None
def process_images(tree):
# Find all image, video, and link elements
element = tree.xpath(".//img[@src]|.//video[@src]|.//video/source[@src]|.//a[@href]")
for element in element:
src = element.get("href") if element.tag == "a" else element.get("src")
if not src:
continue
if src.startswith("/"):
src = BASE + src
if src.startswith(f"{BASE}/images/"):
# Extract filename from src
if "/images/thumb/" in src:
filename = src.split("/")[-2]
else:
filename = os.path.basename(src)
# Download from Special:Filepath for full resolution
img_url = f"{BASE}/Special:Filepath/{filename}"
elif src.startswith(f"{BASE}/File:") or src.startswith(f"{BASE}/Image:"):
img_url = src
img_url = img_url.replace(f"{BASE}/File:", f"{BASE}/Special:Filepath/")
img_url = img_url.replace(f"{BASE}/Image:", f"{BASE}/Special:Filepath/")
filename = os.path.basename(img_url)
elif src.startswith(f"{BASE}/Special:Filepath/"):
img_url = src
filename = os.path.basename(img_url)
elif os.path.splitext(src)[1].lower() in MIRRORED_EXTENSIONS:
filename = "mirror_" + os.path.basename(src)
img_url = src
else:
# Leave other links as is
continue
filename = urllib.parse.unquote(filename)
local_dir = os.path.join(OUTPUT_DIR, "uploads")
os.makedirs(local_dir, exist_ok=True)
local_path = os.path.join(local_dir, filename)
if os.path.exists(local_path + ".failed"):
print(f"Skipping previously failed file: {img_url}")
continue
# Download if not already present
if not os.path.exists(local_path):
try:
print(f"Downloading {img_url}...")
# Use a browser-like User-Agent to avoid some pages (like banggood) blocking the request
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/137.0.0.0 Safari/537.36"
}
resp = requests.get(img_url, stream=True, headers=headers)
if resp.status_code == 200:
with open(local_path, "wb") as f:
for chunk in resp.iter_content(1024):
f.write(chunk)
print(f"\tDownloaded {img_url} -> {local_path}")
else:
raise Exception(
f"Failed to download {img_url} (status {resp.status_code})"
)
except Exception as e:
print(f"Error downloading {img_url}: {e}")
with open(local_path + ".failed", "w", encoding="utf-8") as f:
f.write(f"Error downloading image: {img_url}. {e}")
continue
# Replace src with local url
element.set(
"href" if element.tag == "a" else "src", f"/uploads/{filename}"
)
if element.tag == "img":
# Remove all other attributes except 'src', 'width', 'height', 'alt', and 'title'
for attr in list(element.attrib.keys()):
if attr not in ("src", "width", "height", "alt", "title"):
del element.attrib[attr]
def convert_galleries_to_imgs(tree):
GALLERY_MODE = "table" # Or "flat"
# Convert gallery nodes to flat img tags
galleries = tree.xpath('.//ul[contains(@class, "gallery")]')
for gallery in galleries:
img_tags = []
for li in gallery.xpath('.//li[contains(@class, "gallerybox")]'):
img = li.xpath(".//img")
if img:
img_tags.append(img[0])
if GALLERY_MODE == "table":
# Replace gallery with a table of images (up to 3 per row)
parent = gallery.getparent()
if parent is not None:
table = html.Element("table")
row = None
for i, img in enumerate(img_tags):
if i % 3 == 0:
row = html.Element("tr")
table.append(row)
# Set height to 200, preserve aspect ratio, assuming width and height are already set
orig_width = int(img.attrib.get("width", "0"))
orig_height = int(img.attrib.get("height", "0"))
DESIRED_CELL_HEIGHT = 150
if orig_width > 0 and orig_height > 0:
new_height = DESIRED_CELL_HEIGHT
new_width = int(round(orig_width * (new_height / orig_height)))
img.set("width", str(new_width))
img.set("height", str(new_height))
else:
img.set("height", str(DESIRED_CELL_HEIGHT))
img.set("width", str(DESIRED_CELL_HEIGHT))
td = html.Element("td")
td.append(img)
row.append(td)
parent.insert(parent.index(gallery), table)
parent.remove(gallery)
else:
# Replace gallery with flat img tags
parent = gallery.getparent()
if parent is not None:
for img in img_tags:
img.tail = "\n"
parent.insert(parent.index(gallery), img)
parent.remove(gallery)
def unwrap_span(span):
parent = span.getparent()
assert parent is not None, "Span must have a parent to unwrap"
# Replace the <span> with all its children and text
idx = parent.index(span)
# Insert span's text if present
if span.text:
if idx == 0:
if parent.text:
parent.text += span.text
else:
parent.text = span.text
else:
prev = parent[idx - 1]
if prev.tail:
prev.tail += span.text
else:
prev.tail = span.text
# Insert all children of span
for child in list(span):
parent.insert(idx, child)
idx += 1
# Insert span.tail if present
if span.tail:
if idx == 0:
if parent.text:
parent.text += span.tail
else:
parent.text = span.tail
else:
node = parent[idx - 1]
if node.tail:
node.tail += span.tail
else:
node.tail = span.tail
parent.remove(span)
def convert_figures_to_imgs(tree) -> None:
# Convert <figure> elements to <img> with caption as alt text
for figure in tree.xpath(".//figure"):
img = figure.find(".//img")
caption_elem = figure.find(".//figcaption")
if img is not None:
# Set alt text from caption if present (text_content flattens any
# inline markup like <b>/<i> inside the caption)
if caption_elem is not None and caption_elem.text_content().strip():
img.set("alt", caption_elem.text_content().strip())
# Replace <figure> with <img>
parent = figure.getparent()
if parent is not None:
parent.insert(parent.index(figure), img)
parent.remove(figure)
def normalize_heading_levels(tree):
# Find all headings (h1-h6)
headings = tree.xpath(".//h1 | .//h2 | .//h3 | .//h4 | .//h5 | .//h6")
if not headings:
return
# Find the lowest heading level
min_level = min(int(h.tag[1]) for h in headings)
# Raise all headings so that the lowest is 1
for h in headings:
old_level = int(h.tag[1])
new_level = old_level - min_level + 1
new_level = min(max(new_level, 1), 6) # Clamp between 1 and 6
h.tag = f"h{new_level}"
# Convert CSS color names to hex values if present
def css_color_to_hex(color):
color = color.strip().lower()
if color == "yellow" or color.lower() == "#ffff00":
# Of the valid colors, the greenish color is actually perceptually closer than the yellowish color.
# Which is annoying. So convert yellow to a yellowish color even though it's perceptually not as close.
return "#FDEA9B"
try:
# Try named color
return webcolors.name_to_hex(color)
except ValueError:
pass
try:
# Try rgb/rgba/hsl/hex
return webcolors.normalize_hex(color)
except ValueError:
pass
return color # fallback
def unwrap_single_cell_notice_tables(nodes):
"""Replace tables that contain only a single cell, and that cell is a container_notice. Replace the table with just the container_notice node."""
result = []
for node in nodes:
if (
node.get("type") == "table"
and len(node.get("content", [])) == 1
and node["content"][0].get("type") == "tr"
and len(node["content"][0].get("content", [])) == 1
and node["content"][0]["content"][0].get("type") in ("td", "th")
):
cell = node["content"][0]["content"][0]
cell_content = cell.get("content", [])
if (
len(cell_content) == 1
and isinstance(cell_content[0], dict)
and cell_content[0].get("type") == "container_notice"
):
# Replace table with the container_notice node
result.append(cell_content[0])
continue
# Recursively process children if present
if "content" in node and isinstance(node["content"], list):
node = dict(node)
node["content"] = unwrap_single_cell_notice_tables(node["content"])
result.append(node)
return result
def color_marks(node):
if isinstance(node, str):
return []
if node.tag in ["table"]:
return []
# Check for marks in style attribute
marks = []
style = node.attrib.get("style", "")
if "text-decoration: underline" in style:
marks.append({"type": "underline"}) # Correct?
if "text-decoration: line-through" in style:
marks.append({"type": "strikethrough"}) # Correct?
# Check for color or background-color in style
bgcolor_match = re.search(
r"(?:background-color|color|background):\s*([^;]+)", style
)
if bgcolor_match:
orig = css_color_to_hex(bgcolor_match.group(1).strip())
rgb = _hex_to_rgb01(orig)
if rgb is not None:
r, g, b = rgb
# Skip near-neutral light backgrounds (e.g. #f5faff infobox
# framing): they are layout decoration, not semantic color.
if max(r, g, b) - min(r, g, b) >= 0.08 or max(r, g, b) < 0.85:
color = nearest_valid_color(orig)
# "original" is consumed by wrap_highlight_paragraphs to pick a
# notice style and stripped before export.
marks.append(
{"type": "highlight", "attrs": {"color": color}, "original": orig}
)
return marks
def _hex_to_rgb01(hex_color) -> Optional[Tuple[float, float, float]]:
if not isinstance(hex_color, str):
return None
m = re.fullmatch(r"#?([0-9a-fA-F]{6})", hex_color.strip())
if not m:
return None
v = m.group(1)
return tuple(int(v[i : i + 2], 16) / 255 for i in (0, 2, 4))
def notice_style_for_color(hex_color) -> str:
"""Pick a container_notice style from a CSS color: green means ok/success,
yellow/orange means caution/tip, red means forbidden/warning."""
rgb = _hex_to_rgb01(hex_color)
if rgb is None:
return "warning"
h, _l, _s = colorsys.rgb_to_hls(*rgb)
deg = h * 360
if 70 <= deg <= 170:
return "success"
if 20 <= deg < 70:
return "tip"
if 170 < deg <= 260:
return "info"
return "warning"
# Remove all None children from nodes recursively
def remove_none_children(nodes):
if not isinstance(nodes, list):
return nodes
cleaned = []
for node in nodes:
if node is None:
continue
if (
isinstance(node, dict)
and "content" in node
and isinstance(node["content"], list)
):
node = dict(node)
node["content"] = remove_none_children(node["content"])
cleaned.append(node)
return cleaned
def fill_empty_block_elements(nodes):
"""Ensure all block elements have at least one paragraph with an empty text node if their content is empty"""
for node in nodes:
if node.get("type") in ("td", "li", "header") and (
not node.get("content") or len(node["content"]) == 0
):
node["content"] = [{"type": "paragraph"}]
elif "content" in node:
fill_empty_block_elements(node["content"])
def replace_nostalgia_template(content):
"""Find all headings with the content "Nostalgi" and replace both the heading and the following paragraph"""
idx = 0
found = False
while idx < len(content):
node = content[idx]
if (
isinstance(node, dict)
and node.get("type") == "heading"
and node.get("content")
and len(node["content"]) == 1
and node["content"][0].get("type") == "text"
and node["content"][0].get("text", "").strip() == "Nostalgi"
):
# Assert that the next element is a paragraph
if idx + 1 >= len(content):
raise AssertionError(
"Heading 'Nostalgi' is not followed by a paragraph"
)
next_elem = content[idx + 1]
if not (
isinstance(next_elem, dict) and next_elem.get("type") == "paragraph"
):
raise AssertionError(
f"Heading 'Nostalgi' is not followed by a paragraph, found {next_elem.get('type') if isinstance(next_elem, dict) else type(next_elem)}"
)
assert content[idx - 1]["type"] == "hr"
assert content[idx + 2]["type"] == "hr"
# Replace both with a single container_notice
notice = {
"type": "container_notice",
"attrs": {"style": "warning"},
"content": [
{
"type": "text",
"text": "This page is no longer relevant, it is only kept for nostalgic reasons",
}
],
}
found = True
# Remove the heading and paragraph, insert notice
content[idx - 1 : idx + 3] = [notice]
# Do not increment idx, in case there are multiple in a row
else:
idx += 1
return found
def wrap_text_and_image_nodes(nodes, parent_type=None):
wrapped = []
buffer = []
def flush_buffer():
if buffer:
wrapped.append({"type": "paragraph", "content": buffer[:]})
buffer.clear()
for node in nodes:
if (
isinstance(node, dict)
and node.get("type") in ("text", "image")
and parent_type not in ("heading", "paragraph", "code_fence")
):
buffer.append(node)
elif (
isinstance(node, dict)
and "content" in node
and isinstance(node["content"], list)
):
# Flush buffer before handling non-text/image node
flush_buffer()
node_copy = dict(node)
node_copy["content"] = wrap_text_and_image_nodes(
node["content"], parent_type=node.get("type")
)
wrapped.append(node_copy)
else:
flush_buffer()
wrapped.append(node)
flush_buffer()
return wrapped
def unwrap_embed_paragraphs(nodes):
"""Replace paragraphs that only contain a single embed node with the embed node itself"""
result = []
for node in nodes:
if (
isinstance(node, dict)
and node.get("type") == "paragraph"
and isinstance(node.get("content"), list)
and len(node["content"]) == 1
and isinstance(node["content"][0], dict)
and node["content"][0].get("type") == "embed"
):
result.append(node["content"][0])
else:
# Recursively process children if present
if (
isinstance(node, dict)
and "content" in node
and isinstance(node["content"], list)
):
node = dict(node)
node["content"] = unwrap_embed_paragraphs(node["content"])
result.append(node)
return result
def collapse_adjacent_text_nodes(nodes):
"""Collapse adjacent text nodes with no marks into the same text node"""
if not nodes or not isinstance(nodes, list):
return nodes
collapsed = []
prev = None
for node in nodes:
if (
isinstance(node, dict)
and node.get("type") == "text"
and not node.get("marks")
and prev
and isinstance(prev, dict)
and prev.get("type") == "text"
and not prev.get("marks")
):
prev["text"] += node["text"]
else:
collapsed.append(node)
prev = node
# Recursively apply to children
for node in collapsed:
if (
isinstance(node, dict)
and "content" in node
and isinstance(node["content"], list)
):
node["content"] = collapse_adjacent_text_nodes(node["content"])
return collapsed
def wrap_highlight_paragraphs(nodes):
"""Wrap paragraphs - where all child text nodes are highlighted the same - in a container_notice node"""
result = []
for node in nodes:
# Check for paragraph where all text nodes have the same highlight mark
if (
node.get("type") == "paragraph"
and "content" in node
and all(
c.get("type") == "text"
and "marks" in c
and any(m.get("type") == "highlight" for m in c["marks"])
for c in node["content"]
if c.get("type") == "text"
)
and any(c.get("type") == "text" for c in node["content"])
):
# Get the highlight color from the first text node
first_marks = next(
c["marks"] for c in node["content"] if c.get("type") == "text"
)
highlight_mark = next(
(m for m in first_marks if m.get("type") == "highlight"), None
)
if highlight_mark is not None:
# Ensure all text nodes have the same highlight color
same_highlight = all(
any(
m.get("type") == "highlight"
and m.get("attrs", {}).get("color")
== highlight_mark.get("attrs", {}).get("color")
for m in c["marks"]
)
for c in node["content"]
if c.get("type") == "text"
)
if same_highlight:
# Prefer the original CSS color (pre-preset-snapping) for
# classifying the notice style, so pale reds/yellows keep
# their meaning.
color = highlight_mark.get("original") or highlight_mark.get(
"attrs", {}
).get("color")
notice_type = notice_style_for_color(color)
# Remove the highlight mark from all text nodes
new_content = []
for c in node["content"]:
if c.get("type") == "text" and "marks" in c:
new_marks = [
m for m in c["marks"] if m.get("type") != "highlight"
]
text_node = dict(c)
if new_marks:
text_node["marks"] = new_marks
else:
text_node.pop("marks", None)
new_content.append(text_node)
else:
new_content.append(c)
# Wrap in container_notice with style "warning"
result.append(
{
"type": "container_notice",
"attrs": {"style": notice_type},
"content": [{"type": "paragraph", "content": new_content}],
}
)
continue
# Recursively process children
if "content" in node and node["content"] is not None:
node = dict(node)
node["content"] = wrap_highlight_paragraphs(node["content"])
result.append(node)
return result
def remove_empty_text_nodes(nodes):
"""Drop text nodes with empty strings; ProseMirror rejects them. (The
per-node guard misses empties that acquire marks during processing.)"""
if not isinstance(nodes, list):
return nodes
result = []
for node in nodes:
if isinstance(node, dict):
if node.get("type") == "text" and node.get("text", "") == "":
continue
if isinstance(node.get("content"), list):
node["content"] = remove_empty_text_nodes(node["content"])
result.append(node)
return result
def strip_highlight_original(nodes):
"""Remove the internal "original" key from highlight marks before export."""
if not isinstance(nodes, list):
return nodes
for node in nodes:
if not isinstance(node, dict):
continue
for mark in node.get("marks", []) or []:
mark.pop("original", None)
if isinstance(node.get("content"), list):
strip_highlight_original(node["content"])
return nodes
# Block-level node types that must not appear inside a paragraph. Notably
# patch_attachments turns file-link text nodes into attachment blocks in place.
BLOCK_TYPES_IN_PARAGRAPH = {
"attachment",