#!/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/<Title>.txt) 3. King Jim Pomera DM30 ready Shift_JIS text files (pomera/<Title>.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 <page> records from a MediaWiki XML export without holding the whole DOM in memory. If a <page> has multiple <revision> 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"<!--[\s\S]*?-->", "", text) text = re.sub(r"__(?:NOTOC|FORCETOC|TOC|NOEDITSECTION|NEWSECTIONLINK|HIDDENCAT)__", "", text) # 2. Protect <nowiki>, <pre>, <syntaxhighlight>/<source>, and <code> blocks stash_html: Dict[str, str] = {} stash_txt: Dict[str, str] = {} stash_seq = 0 def make_token(h_val: str, t_val: str, block: bool = False) -> str: nonlocal stash_seq stash_seq += 1 kind = "BLK" if block else "INL" tok = f"\x02MW{kind}{stash_seq}\x03" stash_html[tok] = h_val stash_txt[tok] = t_val return tok def _protect_pre(m: re.Match) -> str: inner = html.unescape(m.group(2)) inner_clean = inner.strip("\n") h = f"<pre><code>{html.escape(inner_clean)}</code></pre>" indented = "\n".join(" " + ln for ln in inner_clean.splitlines()) return "\n" + make_token(h, indented, block=True) + "\n" text = re.sub( r"<(pre|syntaxhighlight|source)(?:\s[^>]*)?>([\s\S]*?)</\1>", _protect_pre, text, flags=re.IGNORECASE, ) def _protect_nowiki(m: re.Match) -> str: inner = html.unescape(m.group(1)) return make_token(html.escape(inner), inner, block=False) text = re.sub(r"<nowiki(?:\s[^>]*)?>([\s\S]*?)</nowiki>", _protect_nowiki, text, flags=re.IGNORECASE) text = re.sub(r"<nowiki\s*/>", "", text, flags=re.IGNORECASE) def _protect_code(m: re.Match) -> str: inner = html.unescape(m.group(1)) return make_token(f"<code>{html.escape(inner)}</code>", inner, block=False) text = re.sub(r"<code(?:\s[^>]*)?>([\s\S]*?)</code>", _protect_code, text, flags=re.IGNORECASE) # 3. Extract <ref> footnotes (preserving named ref reuse!) footnotes: List[str] = [] named_refs: Dict[str, int] = {} def _handle_ref_pair(m: re.Match) -> str: attrs = m.group(1) or "" body = (m.group(2) or "").strip() name_m = re.search(r'name\s*=\s*(?:"([^"]+)"|\'([^\']+)\'|([^\s/>]+))', attrs, re.IGNORECASE) ref_name = (name_m.group(1) or name_m.group(2) or name_m.group(3) or "").strip() if name_m else "" if ref_name and ref_name in named_refs: idx = named_refs[ref_name] if body and not footnotes[idx - 1]: footnotes[idx - 1] = body else: footnotes.append(body) idx = len(footnotes) if ref_name: named_refs[ref_name] = idx h = f'<sup class="mw-ref" id="cite_ref-{idx}"><a href="#cite_note-{idx}">[{idx}]</a></sup>' return make_token(h, f"[{idx}]", block=False) def _handle_ref_self(m: re.Match) -> str: attrs = m.group(1) or "" name_m = re.search(r'name\s*=\s*(?:"([^"]+)"|\'([^\']+)\'|([^\s/>]+))', attrs, re.IGNORECASE) ref_name = (name_m.group(1) or name_m.group(2) or name_m.group(3) or "").strip() if name_m else "" if ref_name and ref_name in named_refs: idx = named_refs[ref_name] h = f'<sup class="mw-ref"><a href="#cite_note-{idx}">[{idx}]</a></sup>' return make_token(h, f"[{idx}]", block=False) return "" text = re.sub(r"<ref(\s[^>]*)?>([\s\S]*?)</ref>", _handle_ref_pair, text, flags=re.IGNORECASE) text = re.sub(r"<ref(\s[^>]*?)/>", _handle_ref_self, text, flags=re.IGNORECASE) text = re.sub(r"<references\s*/?>|<references(?:\s[^>]*)?>[\s\S]*?</references>", "", text, flags=re.IGNORECASE) # 4. Expand / clean {{templates}} from innermost outward infobox_blocks_html: List[str] = [] infobox_blocks_txt: List[str] = [] text = self._process_templates(text, infobox_blocks_html, infobox_blocks_txt, make_token) # 5. Extract MediaWiki {| ... |} tables into block tokens text = self._process_tables(text, make_token, stash_html, stash_txt) # 6. Extract Categories and transform [[WikiLinks]] + [[File:...]] via balanced scanner categories: List[str] = [] seen_cats: set = set() text = self._process_wikilinks(text, categories, seen_cats, make_token, stash_html, stash_txt) # 7. Parse block structure: headings, lists, blockquotes, horizontal rules, paragraphs headings: List[Tuple[int, str, str]] = [] # (level, plain_title, anchor_id) used_anchors: set = set() html_blocks: List[str] = [] txt_blocks: List[str] = [] pomera_blocks: List[str] = [] if page.redirect_to: stem, anchor = self.resolve_stem(page.redirect_to) target_disp = html.escape(page.redirect_to) if stem: href = urllib.parse.quote(f"{stem}.html") + (f"#{urllib.parse.quote(anchor)}" if anchor else "") html_blocks.append( f'<div class="mw-redirect-box">↳ Redirects to <a href="{href}"><strong>{target_disp}</strong></a></div>' ) else: html_blocks.append( f'<div class="mw-redirect-box">↳ Redirects to <strong>{target_disp}</strong></div>' ) 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"<p>{h_in}</p>") 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("<blockquote"): flush_para() flush_list() bq_lines = [] cur = re.sub(r"^<blockquote[^>]*>", "", stripped, flags=re.IGNORECASE) while True: end_m = re.search(r"</blockquote>", 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"<blockquote><p>{self._format_inline_html(bq_raw, stash_html)}</p></blockquote>") 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("<hr>") 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{lvl} id="{html.escape(anchor_id)}">{h_html}</h{lvl}>') 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"<pre><code>{html.escape(joined_pre)}</code></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'<li class="{indent_cls}"><a href="#{html.escape(aid)}">{html.escape(h_txt)}</a></li>' ) toc_html = ( '<nav class="mw-toc" aria-label="Contents">' '<div class="mw-toc-title">Contents</div>' f'<ol>{"".join(toc_items)}</ol>' "</nav>" ) # 9. Render Footnotes if any if footnotes: fn_html_items = [] fn_txt_items = ["Notes & References\n------------------"] for idx, raw_fn in enumerate(footnotes, 1): fn_clean_h = self._format_inline_html(raw_fn, stash_html) if raw_fn else "<em>(empty reference)</em>" fn_clean_t = self._format_inline_txt(raw_fn, stash_txt).strip() if raw_fn else "(empty reference)" fn_html_items.append( f'<li id="cite_note-{idx}"><a class="mw-cite-back" href="#cite_ref-{idx}" aria-label="Jump up">↑</a> {fn_clean_h}</li>' ) fn_txt_items.append(f" [{idx}] {fn_clean_t}") html_blocks.append( '<section class="mw-footnotes"><h2>Notes & References</h2>' f'<ol>{"".join(fn_html_items)}</ol></section>' ) 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'<a class="mw-cat-pill" href="{urllib.parse.quote(c_stem + ".html")}">{html.escape(c)}</a>') else: cat_pills.append(f'<span class="mw-cat-pill">{html.escape(c)}</span>') html_blocks.append( f'<footer class="mw-categories"><span class="mw-cat-label">Categories:</span> {" ".join(cat_pills)}</footer>' ) 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("<h"): html_blocks.insert(idx, toc_html) inserted = True break if not inserted: html_blocks.insert(0, toc_html) full_txt_header = f"{page.title}\n{'=' * max(4, len(page.title))}" meta_bits = [] if page.timestamp: meta_bits.append(f"Last updated: {page.timestamp}") if page.contributor: meta_bits.append(f"Contributor: {page.contributor}") if meta_bits: full_txt_header += "\n" + " | ".join(meta_bits) pomera_header = pomera_heading(1, page.title) if meta_bits: pomera_header += "\n" + guard_pomera_body_lines(" | ".join(meta_bits)) final_txt = full_txt_header + "\n\n" + "\n\n".join(b for b in txt_blocks if b.strip()) + "\n" final_pomera = pomera_header + "\n\n" + "\n\n".join(b for b in pomera_blocks if b.strip()) + "\n" final_html = "\n".join(html_blocks) return final_html, final_txt, final_pomera, categories def _make_anchor(self, heading_txt: str, used: set) -> 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"<ruby>{html.escape(pos_args[0])}<rp>(</rp><rt>{html.escape(pos_args[1])}</rt><rp>)</rp></ruby>" 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<blockquote>{q_body}{cite}</blockquote>\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"<tr><th>{html.escape(k_clean)}</th><td>{html.escape(v_clean)}</td></tr>" ) rows_t.append(f" {k_clean}: {v_clean}") if rows_h: infobox_html.append( f'<aside class="mw-infobox"><div class="mw-infobox-title">{html.escape(self._strip_wiki_markup_simple(box_title))}</div>' f'<table><tbody>{"".join(rows_h)}</tbody></table></aside>' ) 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"<br\s*/?>", ", ", 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'<figure class="mw-figure">' f'<div class="mw-figure-file">◆ {html.escape(rest_title)}</div>' f"<figcaption>{cap_h}</figcaption></figure>" ) fig_t = f"[Image: {rest_title} — {cap_t}]" out.append("\n" + make_token(fig_h, fig_t, block=True) + "\n") else: fig_h = f'<figure class="mw-figure"><div class="mw-figure-file">◆ {html.escape(rest_title)}</div></figure>' out.append("\n" + make_token(fig_h, f"[Image: {rest_title}]", block=True) + "\n") i = end continue # Regular internal [[Target|Label]] link (strip leading colon [[:Category:...]]) clean_target = target.lstrip(":").strip() label_raw = segs[-1].strip() if len(segs) >= 2 else clean_target display = (label_raw or clean_target) + trail disp_h = self._format_inline_html(display, stash_html) disp_t = self._format_inline_txt(display, stash_txt) stem, anchor = self.resolve_stem(clean_target) if stem: href = urllib.parse.quote(f"{stem}.html") if anchor: href += "#" + urllib.parse.quote(anchor.replace(" ", "_")) h_link = f'<a href="{href}">{disp_h}</a>' elif clean_target.startswith("#") and len(clean_target) > 1: href = "#" + urllib.parse.quote(clean_target[1:].replace(" ", "_")) h_link = f'<a href="{href}">{disp_h}</a>' else: h_link = f'<span class="mw-missing-link" title="{html.escape(clean_target)}">{disp_h}</span>' out.append(make_token(h_link, disp_t, block=False)) i = end return "".join(out) @staticmethod def _split_top_pipes(s: str) -> List[str]: parts: List[str] = [] buf: List[str] = [] depth = 0 i = 0 while i < len(s): if s[i : i + 2] == "[[": depth += 1 buf.append("[[") i += 2 elif s[i : i + 2] == "]]" and depth > 0: depth -= 1 buf.append("]]") i += 2 elif s[i] == "|" and depth == 0: parts.append("".join(buf)) buf.clear() i += 1 else: buf.append(s[i]) i += 1 parts.append("".join(buf)) return parts def _process_tables( self, text: str, make_token, stash_html: Dict[str, str], stash_txt: Dict[str, str], ) -> str: """Convert MediaWiki {| ... |} tables into semantic <table> HTML and clean ASCII/UTF-8 text.""" table_re = re.compile(r"^[ \t:]*\{\|[^\n]*\n([\s\S]*?)^[ \t:]*\|\}", re.MULTILINE) def _repl_table(m: re.Match) -> str: body = m.group(1) # First resolve wikilinks inside table body so [[A|B]] pipes don't look like cell separators! dummy_cats: List[str] = [] body = self._process_wikilinks(body, dummy_cats, set(), make_token, stash_html, stash_txt) caption = "" rows: List[List[Tuple[bool, str, str]]] = [] cur_row: List[Tuple[bool, str, str]] = [] for raw_ln in body.splitlines(): ln = raw_ln.strip() if not ln: continue if ln.startswith("|+"): cap_txt = ln[2:].lstrip() if "|" in cap_txt: cap_attr, cap_val = cap_txt.split("|", 1) if not any(tok in cap_attr for tok in ("<", "\x02MW", "''", "[")): cap_txt = cap_val.strip() caption = cap_txt elif ln.startswith("|-"): if cur_row: rows.append(cur_row) cur_row = [] elif ln.startswith("!") or ln.startswith("|"): is_hdr = ln.startswith("!") content = ln[1:] raw_cells = re.split(r"!!|\|\|", content) if is_hdr else content.split("||") for cell in raw_cells: c = cell.strip() cell_attrs_html = "" # Match MediaWiki Parser::doTableStuff(): after [[links]], {{templates}}, and # <nowiki> are tokenized, a single `|` separates optional cell attributes # (even when empty, e.g. `|| ()`, `| | (x)`, `! | Header`, or `! nowrap | Col`) # from cell content unless markup/tags appear before `|`. if "|" in c: maybe_attr, maybe_val = c.split("|", 1) if not any(tok in maybe_attr for tok in ("<", "\x02MW", "''", "[")): colspan_m = re.search( r'\bcolspan\s*=\s*["\']?(\d{1,3})["\']?', maybe_attr, re.IGNORECASE ) rowspan_m = re.search( r'\browspan\s*=\s*["\']?(\d{1,3})["\']?', maybe_attr, re.IGNORECASE ) attr_parts = [] if colspan_m and int(colspan_m.group(1)) > 1: attr_parts.append(f'colspan="{int(colspan_m.group(1))}"') if rowspan_m and int(rowspan_m.group(1)) > 1: attr_parts.append(f'rowspan="{int(rowspan_m.group(1))}"') if attr_parts: cell_attrs_html = " " + " ".join(attr_parts) c = maybe_val.strip() cur_row.append((is_hdr, cell_attrs_html, c)) elif cur_row: # Continuation line of previous cell prev_hdr, prev_attrs, prev_val = cur_row[-1] cur_row[-1] = (prev_hdr, prev_attrs, prev_val + " " + ln) if cur_row: rows.append(cur_row) if not rows: return "" h_rows = [] t_rows = [] if caption: cap_h = self._format_inline_html(caption, stash_html) cap_t = self._format_inline_txt(caption, stash_txt).strip() h_rows.append(f"<caption>{cap_h}</caption>") t_rows.append(f"[{cap_t}]") for r in rows: h_cells = [] t_cells = [] for is_hdr, c_attrs, c_raw in r: tag = "th" if is_hdr else "td" ch = self._format_inline_html(c_raw, stash_html) ct = self._format_inline_txt(c_raw, stash_txt).strip() h_cells.append(f"<{tag}{c_attrs}>{ch}</{tag}>") t_cells.append(ct) h_rows.append("<tr>" + "".join(h_cells) + "</tr>") t_rows.append(" | " + " | ".join(t_cells) + " |") h_table = '<div class="mw-table-wrap"><table class="mw-table">' + "".join(h_rows) + "</table></div>" t_table = "\n".join(t_rows) return "\n" + make_token(h_table, t_table, block=True) + "\n" return table_re.sub(_repl_table, text) def _render_list_block( self, lines: List[str], stash_html: Dict[str, str], stash_txt: Dict[str, str], ) -> Tuple[str, str]: """Render MediaWiki *, #, ;, : list lines into clean nested HTML and plain text.""" html_out: List[str] = [] txt_out: List[str] = [] open_tags: List[str] = [] counters: Dict[int, int] = {} def sync_stack(target_tags: List[str]) -> None: common = 0 while common < len(open_tags) and common < len(target_tags) and open_tags[common] == target_tags[common]: common += 1 while len(open_tags) > common: tag = open_tags.pop() html_out.append(f"</{tag}>") while len(open_tags) < len(target_tags): tag = target_tags[len(open_tags)] open_tags.append(tag) html_out.append(f"<{tag}>") for ln in lines: m = re.match(r"^([*#;:]+)\s*(.*)$", ln) if not m: continue prefix, rest = m.group(1), m.group(2) depth = len(prefix) # Reset deeper ordered counters for d in list(counters.keys()): if d > depth: del counters[d] target_tags = [] for ch in prefix: if ch == "*": target_tags.append("ul") elif ch == "#": target_tags.append("ol") else: target_tags.append("dl") sync_stack(target_tags) last = prefix[-1] indent = " " * (depth - 1) if last == ";": # Definition term `; Term : Definition` if " : " in rest or ":" in rest: # Split only outside tokens term_raw, def_raw = rest.split(":", 1) th = self._format_inline_html(term_raw.strip(), stash_html) dh = self._format_inline_html(def_raw.strip(), stash_html) tt = self._format_inline_txt(term_raw.strip(), stash_txt) dt = self._format_inline_txt(def_raw.strip(), stash_txt) html_out.append(f"<dt>{th}</dt><dd>{dh}</dd>") txt_out.append(f"{indent}{tt}: {dt}") else: th = self._format_inline_html(rest, stash_html) tt = self._format_inline_txt(rest, stash_txt) html_out.append(f"<dt>{th}</dt>") txt_out.append(f"{indent}{tt}") elif last == ":": dh = self._format_inline_html(rest, stash_html) dt = self._format_inline_txt(rest, stash_txt) html_out.append(f"<dd>{dh}</dd>") 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"<li>{ih}</li>") 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"<li>{ih}</li>") 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"<br\s*/?>", 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'<a class="mw-ext-link" href="{url_esc}" rel="noopener noreferrer">{lbl_esc}</a>') s = self._EXT_LINK_RE.sub(_ext_link, s) if "<" in s: s = self._BR_TAG_RE.sub(lambda _: hold("<br>"), 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"<strong><em>\1</em></strong>", s) if "'''" in s: s = self._BOLD_3_RE.sub(r"<strong>\1</strong>", s) if "''" in s: s = self._ITALIC_2_RE.sub(r"<em>\1</em>", 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"""<!DOCTYPE html> <html lang="mul"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>{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'
  • ' f'
    ' f'{html.escape(p.title)}' f'{" ".join(badges)}' f"
    " f'" f"
  • " ) return f""" {html.escape(heading)} — Unpacked MediaWiki Index

    {html.escape(heading)}

    Source: {html.escape(source_name)} · {non_redirect_count:,} articles {f" + {redirect_count:,} redirects" if redirect_count else ""} · UTF-8 HTML, Plain Text & Pomera DM30
    {len(sorted_pages):,} shown
    """ # ============================================================================== # Two-Pass Export Runner (Streaming + Cross-Linked) # ============================================================================== def unpack_mediawiki_xml( xml_path: Path, out_dir: Optional[Path] = None, main_only: bool = False, skip_redirects: bool = False, export_pomera: bool = True, pomera_encoding: str = "cp932", ) -> Tuple[Path, List[ExportedPageInfo]]: """ Unpack `xml_path` into `out_dir` (defaults to `/_export/`). Pass 1 streams titles + redirects to assign collision-free Unicode stems. Pass 2 streams pages and writes: - `html/.html` (standalone UTF-8 HTML) - `txt/.txt` (clean UTF-8 plain text) - `pomera/.txt` (King Jim Pomera DM30 Shift_JIS/cp932 + `.` Outline Mode TOC) - `index.html` + `_manifest.txt` """ xml_path = xml_path.resolve() if not xml_path.is_file(): raise FileNotFoundError(f"File not found: {xml_path}") if out_dir is None: base_name = xml_path.name for ext in (".xml.gz", ".xml.bz2", ".xml"): if base_name.lower().endswith(ext): base_name = base_name[: -len(ext)] break base_name = base_name.strip() or "mediawiki" out_dir = xml_path.parent / f"{base_name}_export" html_dir = out_dir / "html" txt_dir = out_dir / "txt" pomera_dir = out_dir / "pomera" html_dir.mkdir(parents=True, exist_ok=True) txt_dir.mkdir(parents=True, exist_ok=True) if export_pomera: pomera_dir.mkdir(parents=True, exist_ok=True) print(f"\n[1/2] Indexing titles in: {xml_path.name} ...") t0 = time.time() used_casefold: set = set() title_to_stem: Dict[str, str] = {} redirects: Dict[str, str] = {} site_meta, pass1_iter = iter_mediawiki_pages(xml_path) total_seen = 0 for page in pass1_iter: if main_only and page.ns != 0: continue if page.redirect_to: redirects[canonical_wiki_key(page.title)] = page.redirect_to if skip_redirects: continue total_seen += 1 key = canonical_wiki_key(page.title) if key not in title_to_stem: title_to_stem[key] = make_safe_stem(page.title, used_casefold) sitename = site_meta.get("sitename", "") print(f" Found {total_seen:,} page(s)" + (f" from '{sitename}'" if sitename else "") + ".") pom_note = f" + Pomera DM30 ({pomera_encoding})" if export_pomera else "" print(f"[2/2] Rendering HTML + UTF-8 TXT{pom_note} into: {out_dir} ...") converter = WikitextConverter(title_to_stem=title_to_stem, redirects=redirects) exported: List[ExportedPageInfo] = [] used_pomera_casefold: set = {"_index"} # Guard DM30's 3,000-file per-folder limit by sharding if an archive exceeds 2,500 pages shard_pomera = export_pomera and total_seen > 2500 pomera_file_counter = 0 _, pass2_iter = iter_mediawiki_pages(xml_path) for idx, page in enumerate(pass2_iter, 1): if main_only and page.ns != 0: continue if skip_redirects and page.redirect_to: continue key = canonical_wiki_key(page.title) stem = title_to_stem.get(key) or make_safe_stem(page.title, used_casefold) body_html, full_txt, full_pomera, categories = converter.convert_all(page) full_html = build_article_html(page, stem, body_html, sitename) (html_dir / f"{stem}.html").write_text(full_html, encoding="utf-8", newline="\n") (txt_dir / f"{stem}.txt").write_text(full_txt, encoding="utf-8", newline="\n") pom_relpaths: List[str] = [] if export_pomera: parts = split_pomera_parts(page.title, full_pomera) if len(parts) == 1: p_stem = make_pomera_stem(page.title, used_pomera_casefold, max_bytes=30) part_names = [f"{p_stem}.txt"] else: suffix_budget = len(f"_{len(parts)}") p_base = make_pomera_stem(page.title, used_pomera_casefold, max_bytes=max(12, 30 - suffix_budget)) part_names = [] for p_idx in range(1, len(parts) + 1): cand = f"{p_base}_{p_idx}" used_pomera_casefold.add(cand.casefold()) part_names.append(f"{cand}.txt") for p_name, p_text in zip(part_names, parts): pomera_file_counter += 1 if shard_pomera: shard_name = f"{((pomera_file_counter - 1) // 2000) + 1:02d}" target_dir = pomera_dir / shard_name target_dir.mkdir(parents=True, exist_ok=True) rel = f"pomera/{shard_name}/{p_name}" else: target_dir = pomera_dir rel = f"pomera/{p_name}" (target_dir / p_name).write_bytes(encode_pomera_bytes(p_text, encoding=pomera_encoding)) pom_relpaths.append(rel) exported.append( ExportedPageInfo( title=page.title, ns=page.ns, page_id=page.page_id, timestamp=page.timestamp, contributor=page.contributor, redirect_to=page.redirect_to, stem=stem, char_count=len(full_txt), categories=categories, pomera_relpaths=pom_relpaths, ) ) if idx % 100 == 0: print(f" ... exported {idx:,} / {total_seen:,} pages") if export_pomera: pom_idx_lines = [ pomera_heading(1, f"{sitename or xml_path.name} - Index"), f"Exported: {len(exported)} page(s) | Outline Mode: Ctrl+F1 (Alt+Tab switches panes)", "", pomera_heading(2, "Articles"), ] for p in sorted(exported, key=lambda x: (x.ns != 0, x.title.casefold())): files_label = ", ".join(rel.removeprefix("pomera/") for rel in p.pomera_relpaths) redir_sfx = f" -> {p.redirect_to}" if p.redirect_to else "" pom_idx_lines.append(guard_pomera_body_lines(f"- {files_label} : {p.title}{redir_sfx}")) pom_idx_text = "\n".join(pom_idx_lines) + "\n" for p_idx_part_i, p_idx_part in enumerate(split_pomera_parts("Archive Index", pom_idx_text), 1): idx_fname = "_index.txt" if p_idx_part_i == 1 else f"_index_{p_idx_part_i}.txt" (pomera_dir / idx_fname).write_bytes(encode_pomera_bytes(p_idx_part, encoding=pomera_encoding)) index_html = build_index_html(exported, sitename=sitename, source_name=xml_path.name) (out_dir / "index.html").write_text(index_html, encoding="utf-8", newline="\n") manifest_lines = [ f"MediaWiki Export Manifest — {sitename or xml_path.name}", f"Source XML : {xml_path}", f"Exported : {len(exported)} page(s)", "=" * 72, ] for p in sorted(exported, key=lambda x: (x.ns != 0, x.title.casefold())): redir_note = f" [-> {p.redirect_to}]" if p.redirect_to else "" pom_line = f"\n DM30: {', '.join(p.pomera_relpaths)}" if p.pomera_relpaths else "" manifest_lines.append(f"{p.title}{redir_note}\n HTML: html/{p.stem}.html\n TXT : txt/{p.stem}.txt{pom_line}") (out_dir / "_manifest.txt").write_text("\n".join(manifest_lines) + "\n", encoding="utf-8", newline="\n") elapsed = time.time() - t0 print(f"Done! Exported {len(exported):,} page(s) in {elapsed:.2f}s.") print(f" -> Index : {out_dir / 'index.html'}") print(f" -> HTML : {html_dir}") print(f" -> TXT : {txt_dir}") if export_pomera: print(f" -> Pomera : {pomera_dir} ({pomera_encoding}, '.' Outline TOC)") return out_dir, exported def main(argv: Optional[List[str]] = None) -> int: parser = argparse.ArgumentParser( description="Drag-and-drop MediaWiki XML export unpacker -> standalone UTF-8 HTML + plain TXT." ) parser.add_argument( "inputs", nargs="*", help="Path(s) to MediaWiki .xml / .xml.gz / .xml.bz2 export files.", ) parser.add_argument( "-o", "--out", help="Custom output folder (defaults to /_export/).", ) parser.add_argument( "--main-only", action="store_true", help="Export only main-namespace articles (ns=0).", ) parser.add_argument( "--skip-redirects", action="store_true", help="Do not write separate files for #REDIRECT pages (still resolves cross-links through them).", ) parser.add_argument( "--no-pomera", action="store_true", help="Skip creating the pomera/ King Jim Pomera DM30 subfolder.", ) parser.add_argument( "--pomera-encoding", default="cp932", help="Character encoding for pomera/ files (default: cp932 / Shift_JIS for Pomera DM30; or utf-8 for DM200/DM250).", ) parser.add_argument( "--no-pause", action="store_true", help="Exit immediately without waiting for Enter on interactive Windows runs.", ) raw_args = sys.argv[1:] if argv is None else argv args = parser.parse_args(raw_args) # Interactive fallback if user double-clicked the .py without dragging a file onto it interactive_launch = False input_paths: List[Path] = [Path(p.strip().strip('"')) for p in args.inputs if p.strip()] if not input_paths: interactive_launch = True script_dir = Path(__file__).resolve().parent nearby_xmls = sorted( p for p in script_dir.iterdir() if p.is_file() and p.name.lower().endswith((".xml", ".xml.gz", ".xml.bz2")) ) print(f"=== MediaWiki XML Unpacker v{VERSION} ===") if len(nearby_xmls) == 1: print(f"Found XML next to script: {nearby_xmls[0].name}") input_paths = [nearby_xmls[0]] else: if nearby_xmls: print("XML files found in this folder:") for idx, cand in enumerate(nearby_xmls, 1): print(f" [{idx}] {cand.name}") try: ans = input("\nDrag & drop a mediawiki.xml file here (or enter number) and press Enter: ").strip().strip('"') except EOFError: ans = "" if not ans: print("No XML file selected.") return 1 if ans.isdigit() and 1 <= int(ans) <= len(nearby_xmls): input_paths = [nearby_xmls[int(ans) - 1]] else: input_paths = [Path(ans)] # Pause at exit on Windows drag-and-drop so the console window stays open to show results should_pause = ( not args.no_pause and sys.stdin is not None and sys.stdin.isatty() and (os.name == "nt" or interactive_launch) ) exit_code = 0 for xml_path in input_paths: try: custom_out = Path(args.out) if (args.out and len(input_paths) == 1) else None unpack_mediawiki_xml( xml_path=xml_path, out_dir=custom_out, main_only=args.main_only, skip_redirects=args.skip_redirects, export_pomera=not args.no_pomera, pomera_encoding=args.pomera_encoding, ) except Exception as exc: exit_code = 1 print(f"\n[ERROR] Failed to unpack '{xml_path}': {exc}", file=sys.stderr) traceback.print_exc() if should_pause: try: input("\nAll done! Press Enter to close this window...") except EOFError: pass return exit_code if __name__ == "__main__": raise SystemExit(main())