"""Text clean-up for PostBERT. Call normalize() on every email body before scoring. The model was trained on text cleaned by exactly this function. It removes surface features that say nothing about who wrote an email: typography (curly quotes, long dashes, odd spaces), spacing, hard line wraps, and contact details. Skipping it changes scores. Standard library only. Licence: Apache-2.0, Copyright 2026 Skootr. """ from __future__ import annotations import re import unicodedata __all__ = ["normalize"] # Typography mapped to plain ASCII; zero-width characters and CR removed. _TRANSLATE = str.maketrans({ "‘": "'", "’": "'", "‚": "'", "‛": "'", "′": "'", "“": '"', "”": '"', "„": '"', "‟": '"', "″": '"', "«": '"', "»": '"', "‐": "-", "‑": "-", "‒": "-", "–": "-", "—": "-", "―": "-", "−": "-", "…": "...", " ": " ", " ": " ", " ": " ", " ": " ", " ": " ", " ": " ", " ": " ", "•": "-", "·": "-", "●": "-", "▪": "-", "​": None, "‌": None, "‍": None, "⁠": None, "": None, "\r": None, }) _SPACES = re.compile(r"[ \t\f\v]+") _BLANKS = re.compile(r"\n{3,}") _NO_END = re.compile(r"[^.!?:;,)\]\"'>]$") # line does not end a sentence _CONT = re.compile(r"^[a-z(]") # next line continues in lower case _LIST_ITEM = re.compile(r"^\s*([-*+]|\d+[.)]|[a-zA-Z][.)])\s") # Every email address, link and North American phone number becomes one constant. _OCR_AT = re.compile(r"(?<=\w)\u00a9(?=\w)") # "@" misread as a copyright sign _EMAIL = re.compile(r"[\w.+'-]+@[\w-]+(?:\.[\w-]+)+") _URL = re.compile(r"(?:https?://|www\.)[^\s<>()\[\]]+[^\s<>()\[\].,;:!?'\"]") _PHONE = re.compile(r"(? list[str]: """Undo hard wraps: join a line to the next only when it is long, does not end a sentence, and the next line continues in lower case and is not a list item. Short lines (sign-offs, addresses) are never joined.""" out: list[str] = [] for ln in lines: if (out and out[-1] and ln and len(out[-1]) >= min_len and _NO_END.search(out[-1]) and _CONT.match(ln) and not _LIST_ITEM.match(ln)): out[-1] = out[-1] + " " + ln else: out.append(ln) return out def normalize(text: str) -> str: """Return the cleaned form of one email body. - email addresses, links and phone numbers -> fixed placeholders - Unicode NFKC; curly quotes, dashes, ellipsis and odd spaces -> ASCII - zero-width characters and CR removed - runs of spaces and tabs -> one space; spaces trimmed at line ends - hard-wrapped lines joined back together - at most one blank line between paragraphs; outer whitespace removed Call it once, on the raw email body. """ if not text: return "" t = _OCR_AT.sub("@", text).replace("■", "-") t = _URL.sub("https://example.com", t) t = _EMAIL.sub("name@example.com", t) t = _PHONE.sub("555-0100", t) t = unicodedata.normalize("NFKC", t).translate(_TRANSLATE) lines = [_SPACES.sub(" ", ln).strip() for ln in t.split("\n")] t = "\n".join(_unwrap(lines)) t = _BLANKS.sub("\n\n", t) return t.strip()