File size: 6,527 Bytes
ed79d45
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c256683
 
 
 
ed79d45
c256683
 
ed79d45
c256683
 
 
ed79d45
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c256683
 
 
 
 
 
 
 
 
 
ed79d45
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c256683
ed79d45
 
 
 
 
 
 
c256683
ed79d45
c256683
 
 
 
ed79d45
c256683
 
ed79d45
c256683
 
 
 
ed79d45
 
 
c256683
 
ed79d45
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c256683
 
 
 
ed79d45
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
"""
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())