"""Conservative Wikipedia passage cleaning. The cleaner intentionally avoids lower-casing or aggressive punctuation removal: both operations can remove distinctions in entity-heavy Natural Questions retrieval. """ from __future__ import annotations import html import re from typing import Any _COMMENT_RE = re.compile(r"", flags=re.DOTALL) _REF_RE = re.compile(r"]*>.*?|]*/\s*>", flags=re.I | re.S) _TAG_RE = re.compile(r"]*>", flags=re.I) _TEMPLATE_RE = re.compile(r"\{\{[^{}]{0,500}\}\}") _WIKI_LINK_RE = re.compile(r"\[\[(?:[^\]|]+\|)?([^\]]+)\]\]") _EXTERNAL_LINK_RE = re.compile(r"\[(?:https?://\S+)(?:\s+([^\]]+))?\]") _HEADING_RE = re.compile(r"(?m)^\s*=+\s*(.*?)\s*=+\s*$") _MULTISPACE_RE = re.compile(r"[\t\x0b\x0c\r ]+") _MULTINEWLINE_RE = re.compile(r"\n{3,}") def clean_wiki_text(text: str | None) -> str: """Repair Unicode and remove residual MediaWiki markup conservatively.""" try: from ftfy import fix_text except ImportError as exc: # pragma: no cover - installation guard raise RuntimeError("Install the wiki extra with pip install -e '.[wiki]'") from exc value = fix_text(text or "", normalization="NFC") value = html.unescape(value) value = _COMMENT_RE.sub(" ", value) value = _REF_RE.sub(" ", value) value = _HEADING_RE.sub(r"\1", value) # A bounded repeated pass removes simple/nested residual templates without # risking catastrophic regex behavior on malformed Wikipedia text. for _ in range(3): updated = _TEMPLATE_RE.sub(" ", value) if updated == value: break value = updated value = _WIKI_LINK_RE.sub(r"\1", value) value = _EXTERNAL_LINK_RE.sub(lambda m: m.group(1) or " ", value) value = _TAG_RE.sub(" ", value) value = value.replace("'''", "").replace("''", "") value = value.replace("\u00a0", " ").replace("\u200b", "") value = _MULTISPACE_RE.sub(" ", value) value = re.sub(r" *\n *", "\n", value) value = _MULTINEWLINE_RE.sub("\n\n", value) return value.strip() def clean_batch(batch: dict[str, list[Any]]) -> dict[str, list[str]]: """Hugging Face ``Dataset.map(..., batched=True)`` adapter.""" originals = ["" if value is None else str(value) for value in batch["text"]] return { "original_text": originals, "clean_text": [clean_wiki_text(value) for value in originals], }