#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
MediaWiki XML Export Unpacker (v1.0.3)
Author: Gemini 4 Carbon ("Carbie") — AI Village
License: CC0 1.0 Universal (Public Domain)
Drag and drop any MediaWiki XML export (.xml, .xml.gz, or .xml.bz2) onto this
script to unpack every page into:
1. Clean, standalone, cross-linked UTF-8 HTML files (html/
.html)
2. Clean, readable UTF-8 plain-text files (txt/.txt)
3. King Jim Pomera DM30 ready Shift_JIS text files (pomera/.txt)
with '.' Outline Mode headings (Ctrl+F1), DM30-safe filenames, & 50k split
4. An offline searchable Table of Contents (index.html + _manifest.txt)
100% Python 3 standard library — zero pip packages required.
Full Unicode (NFC) support for Japanese (日本語), Swedish (Svenska åäö), and all scripts.
"""
from __future__ import annotations
import argparse
import bz2
import codecs
import gzip
import html
import io
import os
import re
import sys
import time
import traceback
import unicodedata
import urllib.parse
import xml.etree.ElementTree as ET
from dataclasses import dataclass, field
from pathlib import Path
from typing import Dict, Iterator, List, Optional, Tuple
VERSION = "1.0.3"
# Ensure Windows consoles (cp1252 / cp932) never crash when printing Japanese + Swedish titles
for _stream_name in ("stdout", "stderr"):
_stream = getattr(sys, _stream_name, None)
if _stream is not None and hasattr(_stream, "reconfigure"):
try:
_stream.reconfigure(encoding="utf-8", errors="replace")
except Exception:
pass
# Windows reserved device names (case-insensitive)
WINDOWS_RESERVED = {
"CON", "PRN", "AUX", "NUL",
*{f"COM{i}" for i in range(1, 10)},
*{f"LPT{i}" for i in range(1, 10)},
}
# Localized File / Category / Redirect prefixes (English, Swedish, Japanese)
FILE_NS_PREFIXES = {
"file", "image",
"fil", "bild",
"ファイル", "画像",
}
CATEGORY_NS_PREFIXES = {
"category",
"kategori",
"カテゴリ", "カテゴリー", "分類",
}
REDIRECT_RE = re.compile(
r"^\s*#(?:REDIRECT|OMDIRIGERING|転送|リダイレクト)\s*:?\s*\[\[([^\|\]]+)(?:\|[^\]]*)?\]\]",
re.IGNORECASE,
)
def nfc(text: str) -> str:
"""Normalize text to canonical Unicode NFC (preserves åäö and Japanese dakuten cleanly)."""
if not text:
return ""
return unicodedata.normalize("NFC", text)
def canonical_wiki_key(title: str) -> str:
"""Normalize a MediaWiki page title for cross-link lookup."""
t = nfc(title).strip().replace("_", " ")
t = re.sub(r"\s+", " ", t)
if not t:
return ""
# MediaWiki titles are commonly case-insensitive on the first character
return t[0].upper() + t[1:] if len(t) > 1 else t.upper()
def make_safe_stem(title: str, used_casefold: set, max_len: int = 130) -> str:
"""
Build a cross-platform (Windows NTFS + macOS + Linux) safe filename stem
that preserves Japanese, Swedish, and other Unicode letters cleanly.
"""
s = nfc(title).strip()
# Make namespace/subpage separators readable on Windows
s = s.replace(":", " - ").replace("/", " - ").replace("\\", " - ")
# Replace remaining Windows-illegal filename characters and control chars
s = re.sub(r'[<>\"|?*\x00-\x1f\x7f]', "_", s)
s = re.sub(r"\s+", " ", s).strip(" .")
if not s:
s = "Untitled"
if len(s) > max_len:
s = s[:max_len].rstrip(" .-_") or "Article"
if s.upper() in WINDOWS_RESERVED or s.split(".")[0].upper() in WINDOWS_RESERVED:
s = f"_{s}"
candidate = s
counter = 2
while candidate.casefold() in used_casefold:
suffix = f" ({counter})"
base = s[: max(1, max_len - len(suffix))].rstrip(" .")
candidate = f"{base}{suffix}"
counter += 1
used_casefold.add(candidate.casefold())
return candidate
# King Jim Pomera DM30 typography & Latin fallback map for Shift_JIS (cp932)
POMERA_CHAR_MAP: Dict[str, str] = {
"\u00a0": " ",
"\u2009": " ",
"\u200b": "",
"\ufeff": "",
"\u2022": "・",
"\u2023": "・",
"\u25e6": "-",
"\u2043": "-",
"\u2013": "-",
"\u2014": "―",
"\u2212": "-",
"\u2018": "'",
"\u2019": "'",
"\u201c": '"',
"\u201d": '"',
"\u00ab": "<<",
"\u00bb": ">>",
"\u00df": "ss",
"\u1e9e": "SS",
"\u00e6": "ae",
"\u00c6": "AE",
"\u00f8": "o",
"\u00d8": "O",
"\u0153": "oe",
"\u0152": "OE",
"\u00f0": "d",
"\u00d0": "D",
"\u00fe": "th",
"\u00de": "TH",
"\u0142": "l",
"\u0141": "L",
"\u21b3": "->",
"\u2713": "[x]",
"\u2714": "[x]",
"\u2717": "[ ]",
"\u2718": "[ ]",
"\u2610": "( )",
"\u2611": "(x)",
"\u2612": "(x)",
}
# Characters in POMERA_CHAR_MAP that ARE valid cp932 (2-byte symbols) but mapped to crisp ASCII
_POMERA_PRE_TRANS = str.maketrans({
"\u2212": "-",
"\u2018": "'",
"\u2019": "'",
"\u201c": '"',
"\u201d": '"',
})
_POMERA_NORDIC_DIGRAPH_TRANS = str.maketrans({
"\u00e5": "aa",
"\u00e4": "ae",
"\u00f6": "oe",
"\u00c5": "Aa",
"\u00c4": "Ae",
"\u00d6": "Oe",
})
_POMERA_FALLBACK_CACHE: Dict[str, str] = dict(POMERA_CHAR_MAP)
def _pomera_fallback_char(ch: str) -> str:
cached = _POMERA_FALLBACK_CACHE.get(ch)
if cached is not None:
return cached
decomp = unicodedata.normalize("NFKD", ch)
cleaned = "".join(c for c in decomp if not unicodedata.combining(c))
if cleaned:
kept: List[str] = []
for c in cleaned:
if c in POMERA_CHAR_MAP:
kept.append(POMERA_CHAR_MAP[c])
else:
try:
c.encode("cp932")
kept.append(c)
except UnicodeEncodeError:
pass
res = "".join(kept) if kept else "?"
else:
res = "?"
_POMERA_FALLBACK_CACHE[ch] = res
return res
def _pomera_cp932_error_handler(exc: UnicodeError) -> Tuple[str, int]:
if not isinstance(exc, UnicodeEncodeError):
raise exc
bad = exc.object[exc.start : exc.end]
rep = "".join(_POMERA_FALLBACK_CACHE.get(ch) or _pomera_fallback_char(ch) for ch in bad)
return (rep, exc.end)
codecs.register_error("pomera_cp932", _pomera_cp932_error_handler)
def to_pomera_cp932_str(text: str, nordic_digraph: bool = False) -> str:
"""
Convert arbitrary Unicode text into a string cleanly encodable in Shift_JIS (cp932)
using Python's C-level cp932 encoder + memoized NFKD fallback handler.
"""
if not text:
return ""
if text.isascii():
return text
pre = text.translate(_POMERA_NORDIC_DIGRAPH_TRANS) if nordic_digraph else text
pre = pre.translate(_POMERA_PRE_TRANS)
return pre.encode("cp932", errors="pomera_cp932").decode("cp932")
def encode_pomera_bytes(text: str, encoding: str = "cp932", nordic_digraph: bool = False) -> bytes:
"""Encode Pomera text with CRLF line endings in Shift_JIS (cp932) or custom encoding."""
norm = text.replace("\r\n", "\n").replace("\r", "\n").replace("\n", "\r\n")
enc_low = encoding.lower().strip()
if enc_low in ("cp932", "shift_jis", "shift-jis", "sjis", "windows-31j"):
if norm.isascii():
return norm.encode("ascii")
pre = norm.translate(_POMERA_NORDIC_DIGRAPH_TRANS) if nordic_digraph else norm
return pre.translate(_POMERA_PRE_TRANS).encode("cp932", errors="pomera_cp932")
return norm.encode(encoding, errors="replace")
def _truncate_cp932_bytes(s: str, max_bytes: int) -> str:
"""Truncate `s` on whole-character boundaries so its cp932 byte length <= max_bytes."""
if len(s.encode("cp932", errors="replace")) <= max_bytes:
return s
acc: List[str] = []
used = 0
for ch in s:
b_len = len(ch.encode("cp932", errors="replace"))
if used + b_len > max_bytes:
break
acc.append(ch)
used += b_len
return "".join(acc)
def make_pomera_stem(title: str, used_casefold: set, max_bytes: int = 30) -> str:
"""
Build a King Jim Pomera DM30 safe filename stem (Manual pp. 53, 55, 78):
- Strips DM30-forbidden half-width chars: " * + , / : ; < = > ? [ \ ¥ ] |
- No leading half-width space; guards Windows reserved device names.
- Keeps cp932 byte length <= `max_bytes` (default 30 bytes + '.txt' 4 bytes = 34 <= 36 bytes
= 18 zenkaku chars, leaving headroom for `_1` / `_2` split or collision suffixes).
"""
s = to_pomera_cp932_str(nfc(title).strip())
for sep in (":", "/", "\\", "\u00a5"):
s = s.replace(sep, " - ")
# Forbidden half-width characters on Pomera DM30 + control chars
s = re.sub(r'[\"*+,/:;<=>?\[\\\]|\x00-\x1f\x7f]', "_", s)
s = re.sub(r"\s+", " ", s).strip(" .")
if not s:
s = "Untitled"
if s.upper() in WINDOWS_RESERVED or s.split(".")[0].upper() in WINDOWS_RESERVED:
s = f"_{s}"
s = _truncate_cp932_bytes(s, max_bytes).rstrip(" .-_") or "Article"
candidate = s
counter = 2
while candidate.casefold() in used_casefold:
suffix = f"_{counter}"
base = _truncate_cp932_bytes(s, max(4, max_bytes - len(suffix))).rstrip(" .")
candidate = f"{base}{suffix}"
counter += 1
used_casefold.add(candidate.casefold())
return candidate
def pomera_heading(level: int, title_text: str) -> str:
"""
Format a Pomera DM30 Outline Mode heading (Manual pp. 39, 84-86):
`.` at column 0 works on ALL DM30 firmware versions (v1.0 & v1.1; `#` requires v1.1+).
"""
lvl = max(1, min(10, level))
clean = re.sub(r"\s+", " ", title_text).strip() or "Section"
sep = " " if clean.startswith((".", "#")) else ""
return f"{'.' * lvl}{sep}{clean}"
def guard_pomera_body_lines(block_text: str) -> str:
"""Prefix any non-heading line starting with `.` or `#` at col 0 with a space."""
guarded: List[str] = []
for ln in block_text.split("\n"):
if ln.startswith((".", "#")):
guarded.append(" " + ln)
else:
guarded.append(ln)
return "\n".join(guarded)
def split_pomera_parts(
title: str,
pomera_txt: str,
max_chars: int = 45000,
max_bytes: int = 90000,
) -> List[str]:
"""
Ensure every file stays safely beneath Pomera DM30's 50,000-zenkaku per-file limit
(Manual pp. 31, 78). Almost all articles fit in 1 file; giant articles split cleanly
on section/line boundaries with `.Title (1/N)` Outline headers.
"""
norm = pomera_txt.replace("\r\n", "\n").replace("\r", "\n")
if len(norm) <= (max_chars // 3) and norm.isascii():
return [norm]
cp_bytes = norm.translate(_POMERA_PRE_TRANS).encode("cp932", errors="pomera_cp932")
if len(cp_bytes) <= max_bytes and len(cp_bytes.decode("cp932")) <= max_chars:
return [norm]
lines = norm.split("\n")
# Drop the initial `.Title` line while chunking so we can add `.Title (k/N)` to each part
body_lines = lines[1:] if (lines and lines[0].startswith(".")) else lines
while body_lines and not body_lines[0].strip():
body_lines.pop(0)
raw_chunks: List[List[str]] = []
cur: List[str] = []
cur_chars = 0
cur_bytes = 0
budget_chars = max_chars - 200
budget_bytes = max_bytes - 400
for ln in body_lines:
ln_cp = to_pomera_cp932_str(ln) + "\n"
c_len = len(ln_cp)
b_len = len(ln_cp.encode("cp932", errors="replace"))
# Prefer breaking cleanly before a level-2 `..` section if already >= 60% full
is_sec = ln.startswith("..") and not ln.startswith("...")
if cur and (
cur_chars + c_len > budget_chars
or cur_bytes + b_len > budget_bytes
or (is_sec and (cur_chars > budget_chars * 0.65 or cur_bytes > budget_bytes * 0.65))
):
raw_chunks.append(cur)
cur = []
cur_chars = 0
cur_bytes = 0
cur.append(ln)
cur_chars += c_len
cur_bytes += b_len
if cur:
raw_chunks.append(cur)
total = len(raw_chunks)
if total <= 1:
return [norm]
parts: List[str] = []
for idx, chunk in enumerate(raw_chunks, 1):
hdr = pomera_heading(1, f"{title} ({idx}/{total})")
body = "\n".join(chunk).strip("\n")
parts.append(f"{hdr}\n\n{body}\n")
return parts
def open_xml_stream(path: Path) -> io.BufferedReader | gzip.GzipFile | bz2.BZ2File:
"""Open .xml, .xml.gz, or .xml.bz2 transparently as a binary stream for ElementTree."""
lower = path.name.lower()
if lower.endswith(".gz"):
return gzip.open(path, "rb")
if lower.endswith(".bz2"):
return bz2.open(path, "rb")
return path.open("rb")
def local_tag(tag: str) -> str:
"""Strip XML namespace URI from an ElementTree tag."""
if "}" in tag:
return tag.rsplit("}", 1)[1]
return tag
@dataclass
class RawWikiPage:
title: str
ns: int
page_id: str
timestamp: str
contributor: str
redirect_to: Optional[str]
wikitext: str
@dataclass
class ExportedPageInfo:
title: str
ns: int
page_id: str
timestamp: str
contributor: str
redirect_to: Optional[str]
stem: str
char_count: int
categories: List[str] = field(default_factory=list)
pomera_relpaths: List[str] = field(default_factory=list)
def iter_mediawiki_pages(xml_path: Path) -> Tuple[Dict[str, str], Iterator[RawWikiPage]]:
"""
Stream records from a MediaWiki XML export without holding the whole DOM in memory.
If a has multiple elements, selects the latest revision by timestamp/order.
"""
site_meta: Dict[str, str] = {"sitename": "", "base": "", "generator": ""}
def _gen() -> Iterator[RawWikiPage]:
with open_xml_stream(xml_path) as stream:
context = ET.iterparse(stream, events=("start", "end"))
_, root = next(context)
in_siteinfo = False
for event, elem in context:
t = local_tag(elem.tag)
if event == "start" and t == "siteinfo":
in_siteinfo = True
elif event == "end" and t == "siteinfo":
for child in elem:
ct = local_tag(child.tag)
if ct in site_meta and child.text:
site_meta[ct] = nfc(child.text.strip())
in_siteinfo = False
elem.clear()
root.clear()
elif event == "end" and t == "page" and not in_siteinfo:
title = ""
ns = 0
page_id = ""
redirect_to: Optional[str] = None
best_ts = ""
best_text = ""
best_contrib = ""
found_rev = False
for child in elem:
ct = local_tag(child.tag)
if ct == "title" and child.text:
title = nfc(child.text.strip())
elif ct == "ns" and child.text:
try:
ns = int(child.text.strip())
except ValueError:
ns = 0
elif ct == "id" and not page_id and child.text:
page_id = child.text.strip()
elif ct == "redirect":
rt = child.attrib.get("title", "").strip()
if rt:
redirect_to = nfc(rt)
elif ct == "revision":
rev_ts = ""
rev_text = ""
rev_user = ""
for rchild in child:
rct = local_tag(rchild.tag)
if rct == "timestamp" and rchild.text:
rev_ts = rchild.text.strip()
elif rct == "text":
rev_text = nfc("".join(rchild.itertext()))
elif rct == "contributor":
for cchild in rchild:
cct = local_tag(cchild.tag)
if cct in ("username", "ip") and cchild.text:
rev_user = nfc(cchild.text.strip())
break
if (not found_rev) or (rev_ts and rev_ts >= best_ts) or (not best_ts):
found_rev = True
best_ts = rev_ts
best_text = rev_text
best_contrib = rev_user
if not redirect_to and best_text:
m = REDIRECT_RE.match(best_text)
if m:
redirect_to = nfc(m.group(1).strip())
if title:
yield RawWikiPage(
title=title,
ns=ns,
page_id=page_id,
timestamp=best_ts,
contributor=best_contrib,
redirect_to=redirect_to,
wikitext=best_text,
)
elem.clear()
root.clear()
return site_meta, _gen()
# ==============================================================================
# MediaWiki Wikitext -> HTML & Plain Text Converter
# ==============================================================================
class WikitextConverter:
"""
Clean, zero-dependency MediaWiki wikitext converter producing both:
- Semantic HTML body (with TOC, infoboxes, tables, lists, footnotes, cross-links)
- Readable UTF-8 plain text (with clean headings, tables, lists, footnotes)
"""
def __init__(
self,
title_to_stem: Dict[str, str],
redirects: Dict[str, str],
) -> None:
self.title_to_stem = title_to_stem
self.redirects = redirects
def resolve_stem(self, target: str) -> Tuple[Optional[str], Optional[str]]:
"""Resolve [[Target#Anchor]] to (stem, anchor) if present in this export."""
raw = nfc(target).strip()
anchor = None
if "#" in raw:
raw, anchor = raw.split("#", 1)
raw = raw.strip()
anchor = anchor.strip() or None
if not raw:
return (None, anchor)
key = canonical_wiki_key(raw)
seen = set()
while key in self.redirects and key not in seen:
seen.add(key)
key = canonical_wiki_key(self.redirects[key])
stem = self.title_to_stem.get(key)
if stem is None:
# Fallback case-insensitive lookup
cf = key.casefold()
for k, v in self.title_to_stem.items():
if k.casefold() == cf:
stem = v
break
return (stem, anchor)
def convert(self, page: RawWikiPage) -> Tuple[str, str, List[str]]:
"""Return (html_body, plain_text_body, categories)."""
h_body, t_body, _, cats = self.convert_all(page)
return h_body, t_body, cats
def convert_all(self, page: RawWikiPage) -> Tuple[str, str, str, List[str]]:
"""Return (html_body, plain_text_body, pomera_text_body, categories)."""
text = page.wikitext.replace("\r\n", "\n").replace("\r", "\n")
# 1. Strip HTML comments and behavior switches
notoc = "__NOTOC__" in text
text = re.sub(r"", "", text)
text = re.sub(r"__(?:NOTOC|FORCETOC|TOC|NOEDITSECTION|NEWSECTIONLINK|HIDDENCAT)__", "", text)
# 2. Protect ,
'
)
redir_line = f"-> Redirects to: {page.redirect_to}"
txt_blocks.append(redir_line)
pomera_blocks.append(guard_pomera_body_lines(redir_line))
if infobox_blocks_html:
html_blocks.extend(infobox_blocks_html)
if infobox_blocks_txt:
txt_blocks.extend(infobox_blocks_txt)
pomera_blocks.extend(guard_pomera_body_lines(b) for b in infobox_blocks_txt)
lines = text.split("\n")
para_buf: List[str] = []
list_buf: List[str] = []
def flush_para() -> None:
if not para_buf:
return
joined = " ".join(s.strip() for s in para_buf if s.strip())
para_buf.clear()
if not joined:
return
# Pure block token on its own?
if re.fullmatch(r"\x02MWBLK\d+\x03", joined):
html_blocks.append(stash_html[joined])
if stash_txt[joined].strip():
txt_blocks.append(stash_txt[joined])
pomera_blocks.append(guard_pomera_body_lines(stash_txt[joined]))
return
h_in = self._format_inline_html(joined, stash_html)
t_in = self._format_inline_txt(joined, stash_txt)
if h_in.strip():
html_blocks.append(f"
{h_in}
")
if t_in.strip():
txt_blocks.append(t_in)
pomera_blocks.append(guard_pomera_body_lines(t_in))
def flush_list() -> None:
if not list_buf:
return
h_list, t_list = self._render_list_block(list_buf, stash_html, stash_txt)
list_buf.clear()
if h_list:
html_blocks.append(h_list)
if t_list:
txt_blocks.append(t_list)
pomera_blocks.append(guard_pomera_body_lines(t_list))
i = 0
while i < len(lines):
raw_line = lines[i]
stripped = raw_line.strip()
if not stripped:
flush_para()
flush_list()
i += 1
continue
# Blockquote tags spanning lines
if stripped.lower().startswith("
]*>", "", stripped, flags=re.IGNORECASE)
while True:
end_m = re.search(r"
", cur, flags=re.IGNORECASE)
if end_m:
bq_lines.append(cur[: end_m.start()])
break
bq_lines.append(cur)
i += 1
if i >= len(lines):
break
cur = lines[i]
bq_raw = "\n".join(bq_lines).strip()
if bq_raw:
html_blocks.append(f"
{self._format_inline_html(bq_raw, stash_html)}
")
txt_bq = self._format_inline_txt(bq_raw, stash_txt)
bq_fmt = "\n".join(" > " + ln for ln in txt_bq.splitlines() if ln.strip())
txt_blocks.append(bq_fmt)
pomera_blocks.append(guard_pomera_body_lines(bq_fmt))
i += 1
continue
# Standalone block token line
if re.fullmatch(r"\x02MWBLK\d+\x03", stripped):
flush_para()
flush_list()
html_blocks.append(stash_html[stripped])
if stash_txt[stripped].strip():
txt_blocks.append(stash_txt[stripped])
pomera_blocks.append(guard_pomera_body_lines(stash_txt[stripped]))
i += 1
continue
# Horizontal rule
if re.match(r"^-{4,}\s*$", stripped):
flush_para()
flush_list()
html_blocks.append("")
txt_blocks.append("-" * 48)
pomera_blocks.append("-" * 40)
i += 1
continue
# MediaWiki Heading == Title ==
hm = re.match(r"^(=+)\s*(.*?)\s*\1\s*$", stripped)
if hm and 1 <= len(hm.group(1)) <= 6 and hm.group(2):
flush_para()
flush_list()
lvl = min(6, max(2, len(hm.group(1))))
raw_h = hm.group(2).strip()
h_html = self._format_inline_html(raw_h, stash_html)
h_txt = self._format_inline_txt(raw_h, stash_txt).strip()
anchor_id = self._make_anchor(h_txt, used_anchors)
headings.append((lvl, h_txt, anchor_id))
html_blocks.append(f'{h_html}')
underline_char = "=" if lvl <= 2 else ("-" if lvl == 3 else "~")
if lvl <= 3:
txt_blocks.append(f"{h_txt}\n{underline_char * max(3, len(h_txt))}")
else:
txt_blocks.append(f"{'#' * lvl} {h_txt}")
pomera_blocks.append(pomera_heading(lvl, h_txt))
i += 1
continue
# List / definition / indent line (*, #, ;, :)
if stripped[0] in "*#;:" and not stripped.startswith("://"):
flush_para()
list_buf.append(stripped)
i += 1
continue
# Space-indented preformatted MediaWiki lines
if raw_line.startswith(" ") and not list_buf and not para_buf and stripped and not stripped.startswith("\x02"):
pre_lines = []
while i < len(lines) and lines[i].startswith(" ") and lines[i].strip():
pre_lines.append(self._format_inline_txt(lines[i][1:], stash_txt))
i += 1
joined_pre = "\n".join(pre_lines)
html_blocks.append(f"
{html.escape(joined_pre)}
")
ind_pre = "\n".join(" " + ln for ln in pre_lines)
txt_blocks.append(ind_pre)
pomera_blocks.append(guard_pomera_body_lines(ind_pre))
continue
flush_list()
para_buf.append(stripped)
i += 1
flush_para()
flush_list()
# 8. Build Table of Contents if >= 3 headings and not __NOTOC__
toc_html = ""
if not notoc and len(headings) >= 3:
toc_items = []
min_lvl = min(h[0] for h in headings)
for lvl, h_txt, aid in headings:
indent_cls = f"toc-lvl-{min(4, lvl - min_lvl + 1)}"
toc_items.append(
f'
'
f'{"".join(fn_html_items)}'
)
txt_blocks.append("\n".join(fn_txt_items))
pomera_fn = [pomera_heading(2, "Notes & References")] + [
guard_pomera_body_lines(ln) for ln in fn_txt_items[1:]
]
pomera_blocks.append("\n".join(pomera_fn))
# 10. Render Categories footer if any
if categories:
cat_pills = []
for c in categories:
c_stem, _ = self.resolve_stem(f"Category:{c}")
if c_stem:
cat_pills.append(f'{html.escape(c)}')
else:
cat_pills.append(f'{html.escape(c)}')
html_blocks.append(
f''
)
cat_line = "Categories: " + ", ".join(categories)
txt_blocks.append(cat_line)
pomera_blocks.append(guard_pomera_body_lines(cat_line))
# Insert TOC before the first heading (so lead summary stays above TOC, just like MediaWiki!)
if toc_html:
inserted = False
for idx, blk in enumerate(html_blocks):
if blk.startswith(" str:
base = re.sub(r"\s+", "_", heading_txt.strip())
base = re.sub(r'[\"\'<>#%]', "", base) or "section"
cand = base
n = 2
while cand in used:
cand = f"{base}_{n}"
n += 1
used.add(cand)
return cand
def _process_templates(
self,
text: str,
infobox_html: List[str],
infobox_txt: List[str],
make_token,
) -> str:
"""Iteratively resolve innermost {{...}} templates so nested templates work cleanly."""
innermost_re = re.compile(r"\{\{([^{}]*)\}\}")
for _ in range(25):
if "{{" not in text:
break
def _repl(m: re.Match) -> str:
raw_inner = m.group(1).strip()
if not raw_inner:
return ""
parts = [p.strip() for p in self._split_top_pipes(raw_inner)]
tname = parts[0].strip()
tlow = tname.casefold()
args = parts[1:]
pos_args: List[str] = []
kv_args: List[Tuple[str, str]] = []
param_key_re = re.compile(r"^[\w\- ]+$", re.UNICODE)
for a in args:
if "=" in a:
k, v = a.split("=", 1)
k_s, v_s = k.strip(), v.strip()
if k_s and len(k_s) <= 48 and param_key_re.match(k_s):
if v_s:
kv_args.append((k_s, v_s))
continue
pos_args.append(a)
# {{nihongo|English|日本語|romaji|extra}}
if tlow in ("nihongo", "nihongo2", "nihongo-inline"):
eng = pos_args[0] if len(pos_args) > 0 else ""
jp = pos_args[1] if len(pos_args) > 1 else ""
rom = pos_args[2] if len(pos_args) > 2 else ""
extra = ", ".join(x for x in [jp, rom] if x)
if eng and extra:
return f"{eng} ({extra})"
return eng or extra
# {{lang|ja|日本語}} / {{transl|...}} / {{ipa|...}} / {{ruby|漢字|かんじ}}
if tlow in ("ruby", "ふりがな"):
if len(pos_args) >= 2:
h = f"{html.escape(pos_args[0])}"
t = f"{pos_args[0]}({pos_args[1]})"
return make_token(h, t, block=False)
return pos_args[0] if pos_args else ""
if tlow.startswith("lang-") and pos_args:
return pos_args[0]
if tlow in ("lang", "ipa", "transl", "nowrap", "small", "big", "sc", "smcaps"):
return pos_args[-1] if pos_args else ""
# {{quote|text|author}} / {{cquote|...}} / {{blockquote|...}}
if tlow in ("quote", "cquote", "blockquote", "citat", "引用"):
q_body = ""
q_attr = ""
if pos_args:
q_body = pos_args[0]
if len(pos_args) > 1:
q_attr = pos_args[1]
for k, v in kv_args:
if k.casefold() in ("text", "quote", "1") and not q_body:
q_body = v
elif k.casefold() in ("author", "by", "sign", "source", "2") and not q_attr:
q_attr = v
if q_body:
cite = f" — {q_attr}" if q_attr else ""
return f"\n
{q_body}{cite}
\n"
return ""
# {{main|...}} / {{see also|...}} / {{further|...}}
if tlow in ("main", "see also", "further", "se även", "huvudartikel", "main article"):
targets = ", ".join(f"[[{p}]]" for p in pos_args if p)
label = "Main article" if "main" in tlow or "huvud" in tlow else "See also"
return f"\n:''{label}: {targets}''\n" if targets else ""
# {{!}} MediaWiki magic word for a literal pipe inside tables/templates
if tlow == "!" and not pos_args and not kv_args:
return make_token("|", "|", block=False)
# {{reflist}} / {{notlista}} / {{脚注}} -> handled automatically at bottom
if tlow in ("reflist", "references", "notlista", "källor", "脚注", "clear", "-"):
return ""
# Infoboxes: {{Infobox ... | key = val }} / {{Faktamall ...}} / {{基礎情報 ...}}
if (
tlow.startswith("infobox")
or tlow.startswith("faktamall")
or tlow.startswith("基礎情報")
or (len(kv_args) >= 3 and "\n" in m.group(1))
):
box_title = tname
for prefix in ("Infobox", "infobox", "Faktamall", "faktamall", "基礎情報"):
if box_title.startswith(prefix):
rest = box_title[len(prefix):].strip(" :-_")
if rest:
box_title = rest
break
for k, v in kv_args:
if k.casefold() in ("name", "title", "namn", "名称", "タイトル"):
box_title = v
break
rows_h = []
rows_t = [f"[{self._strip_wiki_markup_simple(box_title)}]"]
for k, v in kv_args:
if k.casefold() in ("image_size", "imagesize", "alt"):
continue
k_clean = k.replace("_", " ").strip()
v_clean = self._strip_wiki_markup_simple(v)
if not v_clean:
continue
rows_h.append(
f"
{html.escape(k_clean)}
{html.escape(v_clean)}
"
)
rows_t.append(f" {k_clean}: {v_clean}")
if rows_h:
infobox_html.append(
f''
)
infobox_txt.append("\n".join(rows_t))
return ""
# Generic lightweight inline templates with 1 positional text arg
if len(pos_args) == 1 and not kv_args and len(pos_args[0]) < 160:
return pos_args[0]
return ""
new_text = innermost_re.sub(_repl, text)
if new_text == text:
break
text = new_text
return text
def _strip_wiki_markup_simple(self, s: str) -> str:
"""Quick plain cleanup for infobox cells before main pass."""
s = re.sub(r" ", ", ", s, flags=re.IGNORECASE)
s = re.sub(r"\[\[(?:[^|\]]*\|)?([^\]]+)\]\]", r"\1", s)
s = re.sub(r"'{2,5}", "", s)
s = re.sub(r"<[^>]+>", "", s)
s = re.sub(r"\x02MW(?:BLK|INL)\d+\x03", "", s)
return html.unescape(re.sub(r"\s+", " ", s)).strip()
def _process_wikilinks(
self,
text: str,
categories: List[str],
seen_cats: set,
make_token,
stash_html: Dict[str, str],
stash_txt: Dict[str, str],
) -> str:
"""Balanced [[...]] scanner supporting nested links inside [[File:...|caption with [[Link]]]]."""
out: List[str] = []
n = len(text)
i = 0
while i < n:
start = text.find("[[", i)
if start == -1:
out.append(text[i:])
break
out.append(text[i:start])
depth = 0
j = start
end = -1
while j < n - 1:
two = text[j : j + 2]
if two == "[[":
depth += 1
j += 2
elif two == "]]":
depth -= 1
j += 2
if depth == 0:
end = j
break
else:
j += 1
if end == -1:
out.append("[[")
i = start + 2
continue
inner = text[start + 2 : end - 2]
# Capture Unicode word suffix blended right onto ]] (e.g. Swedish [[bok]]en -> boken)
trail_start = end
while end < n and text[end].isalpha():
end += 1
trail = text[trail_start:end]
# Split top-level | inside inner (not splitting nested [[a|b]])
segs = self._split_top_pipes(inner)
target = segs[0].strip() if segs else ""
ns_prefix = ""
rest_title = target
if ":" in target and not target.startswith(":"):
ns_prefix, rest_title = target.split(":", 1)
ns_prefix = ns_prefix.strip().casefold()
rest_title = rest_title.strip()
if ns_prefix in CATEGORY_NS_PREFIXES and rest_title:
cat_name = nfc(rest_title)
if cat_name.casefold() not in seen_cats:
seen_cats.add(cat_name.casefold())
categories.append(cat_name)
i = end
continue
if ns_prefix in FILE_NS_PREFIXES and rest_title:
# Extract human-readable caption (last non-option segment)
img_opts = {
"thumb", "thumbnail", "frame", "framed", "frameless", "border",
"right", "left", "center", "none", "upright",
"miniatyr", "höger", "vänster", "centrerad",
"サムネイル", "右", "左", "中央",
}
caption_raw = ""
for seg in segs[1:]:
s_clean = seg.strip()
s_low = s_clean.casefold()
if not s_clean:
continue
if s_low in img_opts or re.match(r"^\d*x?\d+\s*px$", s_low):
continue
if re.match(r"^(?:alt|link|page|class|lang|upright)\s*=", s_low):
continue
caption_raw = s_clean
if caption_raw:
# Recursively convert links inside caption!
cap_processed = self._process_wikilinks(
caption_raw, categories, seen_cats, make_token, stash_html, stash_txt
)
cap_h = self._format_inline_html(cap_processed, stash_html)
cap_t = self._format_inline_txt(cap_processed, stash_txt).strip()
fig_h = (
f''
f'
")
txt_out.append(f"{indent} {dt}")
elif last == "#":
counters[depth] = counters.get(depth, 0) + 1
ih = self._format_inline_html(rest, stash_html)
it = self._format_inline_txt(rest, stash_txt)
html_out.append(f"
{ih}
")
txt_out.append(f"{indent}{counters[depth]}. {it}")
else:
ih = self._format_inline_html(rest, stash_html)
it = self._format_inline_txt(rest, stash_txt)
html_out.append(f"
{ih}
")
txt_out.append(f"{indent}• {it}")
sync_stack([])
return ("".join(html_out), "\n".join(txt_out))
_EXT_LINK_RE = re.compile(r"\[(https?://[^\s\]]+)(?:\s+([^\]]+))?\]")
_BR_TAG_RE = re.compile(r" ", re.IGNORECASE)
_SAFE_INLINE_TAG_RE = re.compile(
r"<(sup|sub|s|del|u|mark|b|i|em|strong|small|cite|kbd)(?:\s[^>]*)?>([\s\S]*?)\1>",
re.IGNORECASE,
)
_UNWRAP_TAG_HTML_RE = re.compile(r"?(?:span|font|center|div)(?:\s[^>]*)?>", re.IGNORECASE)
_STRIP_TAG_TXT_RE = re.compile(
r"?(?:sup|sub|s|del|u|mark|span|div|small|big|center|font)(?:\s[^>]*)?>",
re.IGNORECASE,
)
_BOLD_ITALIC_5_RE = re.compile(r"'''''(.+?)'''''")
_BOLD_3_RE = re.compile(r"'''(.+?)'''")
_ITALIC_2_RE = re.compile(r"''(.+?)''")
_QUOTES_2_5_RE = re.compile(r"'{2,5}")
_MULTI_WS_RE = re.compile(r"[ \t]+")
_ANY_TOKEN_RE = re.compile(r"\x02MW(?:BLK|INL)\d+\x03|\x04LOC\d+\x05")
_STASH_TOKEN_RE = re.compile(r"\x02MW(?:BLK|INL)\d+\x03")
def _format_inline_html(self, s: str, stash_html: Dict[str, str]) -> str:
"""Format inline wikitext (external links, bold/italic, safe inline tags, tokens) into HTML."""
if not s:
return ""
local_tokens: Dict[str, str] = {}
seq = 0
def hold(val: str) -> str:
nonlocal seq
seq += 1
k = f"\x04LOC{seq}\x05"
local_tokens[k] = val
return k
if "[http" in s:
def _ext_link(m: re.Match) -> str:
url = m.group(1).strip()
lbl = (m.group(2) or "").strip() or url
lbl_esc = html.escape(html.unescape(lbl)) if "&" in lbl else html.escape(lbl)
url_esc = html.escape(url, quote=True)
return hold(f'{lbl_esc}')
s = self._EXT_LINK_RE.sub(_ext_link, s)
if "<" in s:
s = self._BR_TAG_RE.sub(lambda _: hold(" "), s)
for _ in range(3):
if "<" not in s:
break
next_s = self._SAFE_INLINE_TAG_RE.sub(
lambda m: hold(f"<{m.group(1).lower()}>{html.escape(html.unescape(m.group(2)))}{m.group(1).lower()}>"),
s,
)
if next_s == s:
break
s = next_s
s = self._UNWRAP_TAG_HTML_RE.sub("", s)
if "&" in s:
s = html.escape(html.unescape(s), quote=False)
elif "<" in s or ">" in s:
s = html.escape(s, quote=False)
if "''" in s:
if "'''''" in s:
s = self._BOLD_ITALIC_5_RE.sub(r"\1", s)
if "'''" in s:
s = self._BOLD_3_RE.sub(r"\1", s)
if "''" in s:
s = self._ITALIC_2_RE.sub(r"\1", s)
if "\x02" in s or "\x04" in s:
def _tok_repl(m: re.Match) -> str:
k = m.group(0)
return local_tokens.get(k, k) if k[0] == "\x04" else stash_html.get(k, k)
for _ in range(3):
if "\x02" not in s and "\x04" not in s:
break
next_s = self._ANY_TOKEN_RE.sub(_tok_repl, s)
if next_s == s:
break
s = next_s
return s
def _format_inline_txt(self, s: str, stash_txt: Dict[str, str]) -> str:
"""Format inline wikitext into clean, readable plain text."""
if not s:
return ""
if "[http" in s:
def _ext_txt(m: re.Match) -> str:
url = m.group(1).strip()
lbl = (m.group(2) or "").strip()
if lbl and lbl != url:
return f"{lbl} ({url})"
return url
s = self._EXT_LINK_RE.sub(_ext_txt, s)
if "<" in s:
s = self._BR_TAG_RE.sub("\n", s)
s = self._STRIP_TAG_TXT_RE.sub("", s)
if "''" in s:
s = self._QUOTES_2_5_RE.sub("", s)
if "\x02" in s and stash_txt:
def _txt_tok(m: re.Match) -> str:
k = m.group(0)
return stash_txt.get(k, k)
for _ in range(3):
if "\x02" not in s:
break
next_s = self._STASH_TOKEN_RE.sub(_txt_tok, s)
if next_s == s:
break
s = next_s
if "&" in s:
s = html.unescape(s)
if " " in s or "\t" in s:
s = self._MULTI_WS_RE.sub(" ", s)
return s.strip()
# ==============================================================================
# HTML Page & Searchable Archive Index Templates
# ==============================================================================
ARTICLE_CSS = """
:root {
color-scheme: light dark;
--bg: #f8fafc;
--surface: #ffffff;
--surface-alt: #f1f5f9;
--fg: #0f172a;
--muted: #475569;
--border: #cbd5e1;
--accent: #0369a1;
--accent-hover: #075985;
--missing: #9f1239;
}
@media (prefers-color-scheme: dark) {
:root {
--bg: #0b1120;
--surface: #111827;
--surface-alt: #1e293b;
--fg: #f1f5f9;
--muted: #94a3b8;
--border: #334155;
--accent: #38bdf8;
--accent-hover: #7dd3fc;
--missing: #fda4af;
}
}
* { box-sizing: border-box; }
body {
margin: 0;
padding: 24px 16px 56px;
background: var(--bg);
color: var(--fg);
font-family: system-ui, -apple-system, "Segoe UI", "Hiragino Sans", "Yu Gothic UI", "Meiryo", "Noto Sans JP", sans-serif;
line-height: 1.7;
-webkit-text-size-adjust: 100%;
}
.mw-shell {
max-width: 880px;
margin: 0 auto;
background: var(--surface);
border: 1px solid var(--border);
border-radius: 12px;
padding: 28px 32px 36px;
box-shadow: 0 4px 18px rgba(15, 23, 42, 0.06);
}
@media (max-width: 600px) {
.mw-shell { padding: 18px 16px 26px; }
}
.mw-topbar {
display: flex;
flex-wrap: wrap;
justify-content: space-between;
align-items: center;
gap: 10px;
padding-bottom: 14px;
margin-bottom: 18px;
border-bottom: 1px solid var(--border);
font-size: 0.9rem;
}
.mw-topbar a {
color: var(--accent);
text-decoration: none;
font-weight: 600;
}
.mw-topbar a:hover { text-decoration: underline; }
h1.mw-page-title {
margin: 0 0 6px;
font-size: 1.95rem;
line-height: 1.28;
overflow-wrap: anywhere;
}
.mw-meta {
color: var(--muted);
font-size: 0.86rem;
margin-bottom: 22px;
}
.mw-content { overflow-wrap: anywhere; }
.mw-content::after { content: ""; display: table; clear: both; }
.mw-content h2 {
margin-top: 1.9em;
padding-bottom: 6px;
border-bottom: 1px solid var(--border);
font-size: 1.42rem;
}
.mw-content h3 { margin-top: 1.5em; font-size: 1.18rem; }
.mw-content a { color: var(--accent); text-decoration: none; }
.mw-content a:hover { color: var(--accent-hover); text-decoration: underline; }
.mw-missing-link {
color: var(--missing);
border-bottom: 1px dashed var(--missing);
}
.mw-toc {
display: inline-block;
min-width: 240px;
max-width: 100%;
background: var(--surface-alt);
border: 1px solid var(--border);
border-radius: 8px;
padding: 12px 18px;
margin: 12px 0 20px;
font-size: 0.93rem;
}
.mw-toc-title { font-weight: 700; margin-bottom: 6px; }
.mw-toc ol { margin: 0; padding-left: 20px; }
.mw-toc li.toc-lvl-2 { margin-left: 14px; }
.mw-toc li.toc-lvl-3 { margin-left: 28px; }
.mw-toc li.toc-lvl-4 { margin-left: 42px; }
.mw-infobox {
float: right;
width: 290px;
max-width: 100%;
margin: 0 0 18px 22px;
background: var(--surface-alt);
border: 1px solid var(--border);
border-radius: 8px;
font-size: 0.9rem;
overflow: hidden;
}
@media (max-width: 680px) {
.mw-infobox { float: none; width: 100%; margin: 0 0 18px 0; }
}
.mw-infobox-title {
background: var(--accent);
color: #ffffff;
font-weight: 700;
padding: 8px 12px;
text-align: center;
}
.mw-infobox table { width: 100%; border-collapse: collapse; }
.mw-infobox th, .mw-infobox td {
padding: 6px 10px;
border-top: 1px solid var(--border);
text-align: left;
vertical-align: top;
}
.mw-infobox th { width: 38%; color: var(--muted); font-weight: 600; }
.mw-table-wrap { overflow-x: auto; margin: 16px 0; }
.mw-table {
border-collapse: collapse;
width: 100%;
font-size: 0.94rem;
}
.mw-table caption { font-weight: 700; margin-bottom: 6px; text-align: left; }
.mw-table th, .mw-table td {
border: 1px solid var(--border);
padding: 8px 11px;
text-align: left;
vertical-align: top;
}
.mw-table th { background: var(--surface-alt); font-weight: 700; }
.mw-figure {
margin: 16px 0;
padding: 10px 14px;
background: var(--surface-alt);
border: 1px solid var(--border);
border-radius: 8px;
font-size: 0.9rem;
}
.mw-figure-file { font-weight: 600; color: var(--muted); }
.mw-figure figcaption { margin-top: 4px; }
.mw-redirect-box {
padding: 12px 16px;
background: var(--surface-alt);
border-left: 4px solid var(--accent);
border-radius: 6px;
margin-bottom: 16px;
}
blockquote {
margin: 16px 0;
padding: 10px 16px;
border-left: 4px solid var(--border);
background: var(--surface-alt);
border-radius: 0 6px 6px 0;
}
pre {
background: var(--surface-alt);
border: 1px solid var(--border);
border-radius: 8px;
padding: 12px 14px;
overflow-x: auto;
font-size: 0.88rem;
}
code {
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 0.9em;
}
.mw-footnotes {
margin-top: 32px;
font-size: 0.9rem;
}
.mw-categories {
margin-top: 28px;
padding-top: 14px;
border-top: 1px solid var(--border);
display: flex;
flex-wrap: wrap;
gap: 8px;
align-items: center;
font-size: 0.88rem;
}
.mw-cat-label { font-weight: 700; color: var(--muted); }
.mw-cat-pill {
background: var(--surface-alt);
border: 1px solid var(--border);
border-radius: 999px;
padding: 2px 10px;
}
""".strip()
def build_article_html(
page: RawWikiPage,
stem: str,
body_html: str,
sitename: str,
) -> str:
meta_parts = []
if sitename:
meta_parts.append(html.escape(sitename))
if page.ns != 0:
meta_parts.append(f"Namespace {page.ns}")
if page.timestamp:
meta_parts.append(f"Updated {html.escape(page.timestamp)}")
if page.contributor:
meta_parts.append(f"By {html.escape(page.contributor)}")
meta_str = " · ".join(meta_parts) if meta_parts else "MediaWiki Archive"
txt_href = "../txt/" + urllib.parse.quote(f"{stem}.txt")
site_suffix = f" — {html.escape(sitename)}" if sitename else ""
return f"""
{html.escape(page.title)}{site_suffix}
{html.escape(page.title)}
{meta_str}
{body_html}
"""
def build_index_html(
pages: List[ExportedPageInfo],
sitename: str,
source_name: str,
) -> str:
heading = sitename or source_name
sorted_pages = sorted(pages, key=lambda p: (p.ns != 0, p.title.casefold()))
non_redirect_count = sum(1 for p in sorted_pages if not p.redirect_to)
redirect_count = sum(1 for p in sorted_pages if p.redirect_to)
rows_html = []
for p in sorted_pages:
html_href = "html/" + urllib.parse.quote(f"{p.stem}.html")
txt_href = "txt/" + urllib.parse.quote(f"{p.stem}.txt")
pom_btn = ""
if p.pomera_relpaths:
pom_href = "/".join(urllib.parse.quote(seg) for seg in p.pomera_relpaths[0].split("/"))
pom_btn = f'DM30'
is_redir = "1" if p.redirect_to else "0"
search_blob = html.escape(f"{p.title} {' '.join(p.categories)} {p.redirect_to or ''}".lower(), quote=True)
badges = []
if p.ns != 0:
badges.append(f'NS {p.ns}')
if p.redirect_to:
badges.append(f'↳ {html.escape(p.redirect_to)}')
for c in p.categories[:3]:
badges.append(f'{html.escape(c)}')
rows_html.append(
f'