sms-spam / scripts /clean.py
Jakob Neugebauer
Clean whitespace in message text; update README
c256683
Raw
History Blame Contribute Delete
6.53 kB
"""
Clean and deduplicate the SMS Spam Collection v.1.
Source corpus:
Almeida, T.A., Gomez Hidalgo, J.M., Yamakami, A. (2011).
Contributions to the study of SMS Spam Filtering: New Collection and Results.
ACM DOCENG 2011.
https://archive.ics.uci.edu/dataset/228/sms+spam+collection
What this script does (and why):
1. Reads the raw tab-separated file (label\tmessage).
2. Fixes a small set of CP1252 control bytes (e.g. \\x91-\\x97, \\x85) that
appear in the original file as artifacts of an earlier round-trip
through a Windows-1252 environment. These render as control characters
when the file is read as UTF-8; we map them to their intended
typographic equivalents (curly quotes, en/em dashes, ellipsis).
3. Cleans whitespace in every message: strips leading/trailing whitespace
and collapses runs of internal whitespace (multiple spaces, tabs) to a
single space. Casing is preserved.
4. Deduplicates aggressively. The dedupe key applies:
- NFKC unicode normalization,
- whitespace collapse,
- leading/trailing strip,
- lowercase.
The first occurrence of each normalized key is retained. No label
conflicts exist in the corpus.
5. Writes the cleaned data to data.csv and data.jsonl.
Usage:
python scripts/clean.py \\
--in /path/to/raw/SMSSpamCollection \\
--out /path/to/SMSSpamCollectionDeduplicated
"""
from __future__ import annotations
import argparse
import csv
import json
import re
import sys
import unicodedata
from collections import Counter
from pathlib import Path
CP1252_FIXES = {
"\x91": "'",
"\x92": "'",
"\x93": '"',
"\x94": '"',
"\x96": "-",
"\x97": "-",
"\x85": "...",
}
def repair_cp1252_artifacts(text: str) -> str:
"""Replace leaked CP1252 control bytes with their intended characters."""
for bad, good in CP1252_FIXES.items():
text = text.replace(bad, good)
return text
def clean_whitespace(message: str) -> str:
"""Strip leading/trailing whitespace and collapse internal runs of
whitespace (multiple spaces, tabs, etc.) to a single space.
Applied to the stored message text. Removes typing/encoding artifacts
without altering the semantics of the message.
"""
return re.sub(r"\s+", " ", message.strip())
def normalized_key(message: str) -> str:
"""Build the dedupe key from a message.
NFKC + collapse-whitespace + strip + lowercase. Aggressive enough to
catch trivial variants; conservative enough to keep genuinely distinct
messages separate.
"""
s = unicodedata.normalize("NFKC", message)
s = re.sub(r"\s+", " ", s.strip())
return s.lower()
def load_raw(path: Path) -> list[tuple[str, str]]:
"""Read the raw tab-separated SMS file. Returns list of (label, message)."""
content = path.read_text(encoding="utf-8")
content = repair_cp1252_artifacts(content)
rows: list[tuple[str, str]] = []
for line_no, line in enumerate(content.splitlines(), start=1):
if not line:
continue
if "\t" not in line:
print(f" warning: line {line_no} has no tab, skipping: {line!r}",
file=sys.stderr)
continue
label, _, message = line.partition("\t")
rows.append((label.strip(), message))
return rows
def deduplicate_and_clean(
rows: list[tuple[str, str]],
) -> tuple[list[tuple[str, str]], int, int]:
"""Apply whitespace cleanup to each message, then deduplicate using
normalized_key. First occurrence wins. Returns
(cleaned_rows, num_duplicates_removed, num_messages_whitespace_changed)."""
seen: set[str] = set()
cleaned: list[tuple[str, str]] = []
ws_changed = 0
for label, message in rows:
cleaned_message = clean_whitespace(message)
if cleaned_message != message:
ws_changed += 1
key = normalized_key(cleaned_message)
if key in seen:
continue
seen.add(key)
cleaned.append((label, cleaned_message))
return cleaned, len(rows) - len(cleaned), ws_changed
def write_csv(rows: list[tuple[str, str]], path: Path) -> None:
"""Write data as CSV with proper escaping. Columns: label, text."""
with path.open("w", encoding="utf-8", newline="") as fp:
writer = csv.writer(fp, quoting=csv.QUOTE_ALL)
writer.writerow(["label", "text"])
for label, message in rows:
writer.writerow([label, message])
def write_jsonl(rows: list[tuple[str, str]], path: Path) -> None:
"""Write data as line-delimited JSON. Schema: {"label": ..., "text": ...}."""
with path.open("w", encoding="utf-8") as fp:
for label, message in rows:
json.dump({"label": label, "text": message}, fp, ensure_ascii=False)
fp.write("\n")
def summarize(label: str, rows: list[tuple[str, str]]) -> None:
counts = Counter(r[0] for r in rows)
total = sum(counts.values())
print(f"{label}: total={total}")
for k in sorted(counts):
v = counts[k]
pct = 100.0 * v / total if total else 0
print(f" {k}: {v} ({pct:.1f}%)")
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("--in", dest="input", required=True,
help="Path to raw SMSSpamCollection file")
parser.add_argument("--out", dest="output", required=True,
help="Output directory for cleaned data")
args = parser.parse_args()
in_path = Path(args.input)
out_dir = Path(args.output)
out_dir.mkdir(parents=True, exist_ok=True)
print(f"Reading raw corpus: {in_path}")
raw = load_raw(in_path)
summarize("Raw", raw)
print("\nDeduplicating (NFKC + whitespace + lowercase key) ...")
print("Also stripping leading/trailing whitespace and collapsing internal runs ...")
deduped, removed, ws_changed = deduplicate_and_clean(raw)
print(f" Duplicates removed: {removed}")
print(f" Messages with whitespace changes: {ws_changed}")
summarize("Cleaned", deduped)
csv_path = out_dir / "data.csv"
jsonl_path = out_dir / "data.jsonl"
write_csv(deduped, csv_path)
write_jsonl(deduped, jsonl_path)
print(f"\nWrote:")
print(f" {csv_path} ({csv_path.stat().st_size} bytes)")
print(f" {jsonl_path} ({jsonl_path.stat().st_size} bytes)")
return 0
if __name__ == "__main__":
raise SystemExit(main())