File size: 3,319 Bytes
5fbb148
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
"""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"(?<!\d)(?:\+?1[-. ]?)?\(?\d{3}\)?[-. ]?\d{3}[-. ]\d{4}(?!\d)")


def _unwrap(lines: list[str], min_len: int = 55) -> 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()