"""Text normalisation, hashing, PII scrubbing and cheap quality heuristics.""" import hashlib import re import unicodedata _WS = re.compile(r"\s+") _WORD = re.compile(r"\w+", re.UNICODE) EMAIL = re.compile(r"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b") IPV4 = re.compile(r"\b(?:(?:25[0-5]|2[0-4]\d|1?\d?\d)\.){3}(?:25[0-5]|2[0-4]\d|1?\d?\d)\b") PHONE = re.compile(r"(? str: text = unicodedata.normalize("NFKC", text) return _WS.sub(" ", text).strip() def key(text: str) -> str: """Hash used for exact de-duplication (case/whitespace/punctuation-insensitive).""" canon = " ".join(_WORD.findall(normalize(text).casefold())) return hashlib.blake2b(canon.encode(), digest_size=16).hexdigest() def stable_id(*parts: str) -> str: return hashlib.sha256("\x1f".join(parts).encode()).hexdigest()[:24] def words(text: str): return _WORD.findall(text.casefold()) def ngrams(tokens, n): return {" ".join(tokens[i:i + n]) for i in range(len(tokens) - n + 1)} def scrub_pii(text: str) -> str: text = EMAIL.sub("", text) text = IPV4.sub("", text) return text def guess_language(text: str) -> str: sample = text[:4000] toks = words(sample) if not toks: return "unk" tr = sum(t in TR_WORDS for t in toks) + 3 * sum(c in TR_CHARS for c in sample) / max(1, len(sample) / 100) en = sum(t in EN_WORDS for t in toks) if tr > en and tr > 2: return "tr" if en >= 2 or (len(toks) < 30 and sample.isascii()): return "en" return "other" def gopher_quality(text: str): """A subset of the Gopher (Rae et al., 2021) document quality rules. Returns list of failures.""" fails = [] toks = text.split() n = len(toks) if n < 50: fails.append("too_short") if n > 100_000: fails.append("too_long") if n: mean = sum(len(t) for t in toks) / n if not 3 <= mean <= 10: fails.append("mean_word_length") if sum(t.startswith(("#", "...")) or t.endswith("…") for t in toks) / n > 0.1: fails.append("symbol_ratio") alpha = sum(any(c.isalpha() for c in t) for t in toks) / n if alpha < 0.8: fails.append("non_alpha_words") lines = [l for l in text.splitlines() if l.strip()] if lines: if sum(l.lstrip().startswith(("•", "-", "*")) for l in lines) / len(lines) > 0.9: fails.append("bullet_lines") if sum(l.rstrip().endswith(("...", "…")) for l in lines) / len(lines) > 0.3: fails.append("ellipsis_lines") dup = 1 - len(set(lines)) / len(lines) if dup > 0.3: fails.append("duplicate_lines") return fails def approx_tokens(text: str) -> int: """~4 characters per token for English/code; used only where an exact count is too costly.""" return max(1, round(len(text) / 4))