File size: 2,486 Bytes
46e547f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
"""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"<ref\b[^>]*>.*?</ref\s*>|<ref\b[^>]*/\s*>", flags=re.I | re.S)
_TAG_RE = re.compile(r"</?(?:br|p|div|span|small|sup|sub|table|tr|td|th|ul|ol|li)\b[^>]*>", 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],
    }