Spaces:
Running
Running
Download preprocess.py from CamargoJ21/smishing-detector: direct link, hf CLI and curl.
- Browser
- Download file 5.25 kB
-
https://huggingface.co/spaces/CamargoJ21/smishing-detector/resolve/main/preprocess.py
- Command line
-
hf download hf://spaces/CamargoJ21/smishing-detector/preprocess.py
-
curl -L -o preprocess.py https://huggingface.co/spaces/CamargoJ21/smishing-detector/resolve/main/preprocess.py
5.25 kB
| """Phase 2 preprocessing: text normalization, entity tokens, OCR cleanup, | |
| deduplication keys and label mapping. | |
| Two text versions are kept for every message: | |
| text the original message (used later for attacks and the demo) | |
| clean_text normalized, with entities replaced by tokens (model input) | |
| """ | |
| import re | |
| import unicodedata | |
| import pandas as pd | |
| # --------------------------------------------------------------------------- | |
| # Entity patterns. Order matters: emails contain domains, and money contains | |
| # numbers, so the more specific patterns run first. | |
| # --------------------------------------------------------------------------- | |
| TLDS = ("com|net|org|co|info|top|xyz|ly|us|uk|me|io|biz|link|site|online|club|" | |
| "app|cc|ru|cn|in|shop|live|vip|gov|edu|ca|au|de|fr|tk|ml|ga|cf|gq|pw|" | |
| "icu|cyou|sbs|buzz|click|support|help|services") | |
| EMAIL_RE = re.compile(r"\b[\w.+-]+@[\w-]+(?:\.[\w-]+)+\b") | |
| URL_RE = re.compile( | |
| r"(?:https?://\S+" # http(s)://... | |
| r"|www\.\S+" # www.... | |
| rf"|\b[a-z0-9-]+(?:\.[a-z0-9-]+)*\.(?:{TLDS})\b(?:/\S*)?)", # bare domain | |
| re.IGNORECASE) | |
| MONEY_RE = re.compile( | |
| r"(?:[£$€₹]\s?\d[\d,]*(?:\.\d+)?" | |
| r"|\b\d[\d,]*(?:\.\d+)?\s?(?:usd|gbp|eur|dollars?|pounds?|p)\b)", | |
| re.IGNORECASE) | |
| PHONE_RE = re.compile(r"(?<!\w)\+?\d[\d\-\s().]{7,}\d(?!\w)") | |
| NUM_RE = re.compile(r"\b\d+\b") | |
| ENTITY_TOKENS = ["<EMAIL>", "<URL>", "<MONEY>", "<PHONE>", "<NUM>"] | |
| # --------------------------------------------------------------------------- | |
| # Smishtank text was extracted from phone screenshots by OCR, so it can carry | |
| # pieces of the messaging app around the message. These patterns remove the | |
| # most common ones. Review samples in notebook 02 and add patterns if needed. | |
| # --------------------------------------------------------------------------- | |
| OCR_NOISE_RE = [ | |
| re.compile(r"\b(?:today|yesterday|mon|tue|wed|thu|fri|sat|sun)\w*,?\s+" | |
| r"\d{1,2}:\d{2}\s?(?:am|pm)?\b", re.I), # Today 10:32 AM | |
| re.compile(r"\b\d{1,2}:\d{2}\s?(?:am|pm)\b", re.I), # 10:32 AM | |
| re.compile(r"\b(?:text message|imessage|sms)\b(?=\s|$)", re.I), # app labels | |
| re.compile(r"\btap to load preview\b", re.I), | |
| re.compile(r"\bthe sender is not in your contact list\.?", re.I), | |
| re.compile(r"\breport junk\b", re.I), | |
| re.compile(r"\bif you did not expect this message from an unknown sender.*$", | |
| re.I), | |
| re.compile(r"\bdelivered\b\s*$", re.I), | |
| ] | |
| def normalize_text(s: str) -> str: | |
| """Unicode NFKC, remove zero-width characters, collapse whitespace. | |
| Case is kept; the vectorizer and DistilBERT handle lower-casing.""" | |
| s = unicodedata.normalize("NFKC", str(s)) | |
| s = re.sub(r"[-]", "", s) # zero-width chars | |
| s = re.sub(r"\s+", " ", s) | |
| return s.strip() | |
| def replace_entities(s: str) -> str: | |
| s = EMAIL_RE.sub(" <EMAIL> ", s) | |
| s = URL_RE.sub(" <URL> ", s) | |
| s = MONEY_RE.sub(" <MONEY> ", s) | |
| s = PHONE_RE.sub(" <PHONE> ", s) | |
| s = NUM_RE.sub(" <NUM> ", s) | |
| return re.sub(r"\s+", " ", s).strip() | |
| def clean_text(s: str) -> str: | |
| """Model input: normalized text with entity tokens.""" | |
| return replace_entities(normalize_text(s)) | |
| def clean_ocr(s: str) -> str: | |
| """Strip common screenshot artifacts from Smishtank messages.""" | |
| s = normalize_text(s) | |
| for pat in OCR_NOISE_RE: | |
| s = pat.sub(" ", s) | |
| return re.sub(r"\s+", " ", s).strip() | |
| def dedup_key(clean: pd.Series) -> pd.Series: | |
| """Messages that differ only in case, punctuation, a link or a number get | |
| the same key, so near-copies are caught as duplicates.""" | |
| return (clean.str.lower() | |
| .str.replace(r"[^\w<> ]", "", regex=True) | |
| .str.replace(r"\s+", " ", regex=True) | |
| .str.strip()) | |
| def to_binary(label: pd.Series) -> pd.Series: | |
| """1 = malicious (spam or smishing), 0 = legitimate (ham).""" | |
| return label.map({"ham": 0, "spam": 1, "smishing": 1}) | |
| def add_columns(df: pd.DataFrame, source: str) -> pd.DataFrame: | |
| """Add clean_text, key, binary label and source name.""" | |
| out = df.copy() | |
| out["clean_text"] = out["text"].map(clean_text) | |
| out["key"] = dedup_key(out["clean_text"]) | |
| out["label_3"] = out["label"] | |
| out["label"] = to_binary(out["label_3"]) | |
| out["source"] = source | |
| return out | |
| def drop_internal_duplicates(df: pd.DataFrame, name: str, log: list): | |
| """Remove repeated messages within one dataset. If the same key appears | |
| with conflicting labels, all copies are dropped (the label is unreliable).""" | |
| n0 = len(df) | |
| conflict_keys = df.groupby("key")["label"].nunique() | |
| conflict_keys = set(conflict_keys[conflict_keys > 1].index) | |
| df = df[~df["key"].isin(conflict_keys)] | |
| n1 = len(df) | |
| df = df.drop_duplicates("key", keep="first") | |
| log.append({"dataset": name, "step": "drop label conflicts", | |
| "removed": n0 - n1, "remaining": n1}) | |
| log.append({"dataset": name, "step": "drop internal duplicates", | |
| "removed": n1 - len(df), "remaining": len(df)}) | |
| return df.reset_index(drop=True) | |
| KEEP_COLS = ["text", "clean_text", "label", "label_3", "source"] | |