File size: 6,789 Bytes
01ab3d4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
preprocess.py - Tiền xử lý dữ liệu trước khi phát hiện trùng lặp.

Các bước xử lý, áp dụng cho từng cột văn bản được chọn:
  1. Xử lý null: nhận diện giá trị thiếu (NaN, rỗng, "null", "n/a", ...)
  2. Chuẩn hóa Unicode (NFC) để chữ tiếng Việt có dấu luôn cùng một dạng mã hóa
  3. Chuyển về chữ thường
  4. (Tùy chọn) Bỏ dấu tiếng Việt
  5. Loại ký tự đặc biệt, giữ lại chữ cái, chữ số, khoảng trắng
  6. Gộp khoảng trắng thừa, cắt khoảng trắng hai đầu

Cách dùng (dòng lệnh):
  python -m src.preprocess -i data/raw.csv -o data/clean.csv -c given_name surname address_1
  python -m src.preprocess -i raw.csv -o clean.csv -c given_name surname -d phone_number --null-strategy drop
"""
import argparse
import re
import unicodedata

import pandas as pd

from src.schema import DIGIT_COLUMNS, TEXT_COLUMNS

# Các chuỗi được coi là giá trị thiếu, so sánh sau khi chuyển về chữ thường
NULL_TOKENS = {"", "null", "none", "nan", "n/a", "na", "-", "--", "?"}


def is_null(value) -> bool:
    # True nếu giá trị là NaN/None hoặc một chuỗi biểu diễn giá trị thiếu
    if value is None or (not isinstance(value, str) and pd.isna(value)):
        return True
    return str(value).strip().lower() in NULL_TOKENS


def strip_accents(text: str) -> str:
    # Bỏ dấu tiếng Việt
    text = text.replace("đ", "d").replace("Đ", "D")
    decomposed = unicodedata.normalize("NFD", text)
    return "".join(ch for ch in decomposed if unicodedata.category(ch) != "Mn")


def remove_special_chars(text: str) -> str:
    # Thay ký tự đặc biệt bằng khoảng trắng
    return re.sub(r"[^\w\s]|_", " ", text)



def normalize_text(value, remove_accents: bool = False):
    # Chuẩn hóa một chuỗi, trả về None nếu giá trị thiếu
    if is_null(value):
        return None
    text = unicodedata.normalize("NFC", str(value))
    text = text.lower()
    if remove_accents:
        text = strip_accents(text)
    text = remove_special_chars(text)
    return re.sub(r"\s+", " ", text).strip()


def normalize_digits(value):
    # Chỉ giữ lại chữ số (dùng cho cột số điện thoại, mã...)
    if is_null(value):
        return None
    digits = re.sub(r"\D", "", str(value))
    return digits or None


def preprocess_dataframe(
    df: pd.DataFrame,
    text_columns,
    digit_columns=(),
    null_strategy: str = "empty",
    remove_accents: bool = False,
    inplace: bool = False,
):
    """
    Tiền xử lý DataFrame và trả về (df_sạch, thống_kê).

    null_strategy:
      "empty"   - điền chuỗi rỗng ""
      "unknown" - điền chuỗi "unknown"
      "drop"    - xóa các dòng có giá trị thiếu ở bất kỳ cột được chọn
    inplace: True -> ghi đè cột gốc; False -> tạo cột mới '<tên>_clean', giữ nguyên cột gốc.
    """
    if null_strategy not in {"empty", "unknown", "drop"}:
        raise ValueError("null_strategy phải là 'empty', 'unknown' hoặc 'drop'")

    result = df.copy()
    stats = {"rows_in": len(df), "nulls_per_column": {}}
    all_cols = list(text_columns) + list(digit_columns)

    missing = [c for c in all_cols if c not in df.columns]
    if missing:
        raise KeyError(f"Không tìm thấy cột: {missing}")

    clean_names = {}
    for col in all_cols:
        func = normalize_digits if col in digit_columns else (
            lambda v: normalize_text(v, remove_accents))
        cleaned = result[col].map(func)
        stats["nulls_per_column"][col] = int(cleaned.isna().sum())
        target = col if inplace else f"{col}_clean"
        result[target] = cleaned
        clean_names[col] = target

    target_cols = list(clean_names.values())
    if null_strategy == "drop":
        result = result.dropna(subset=target_cols)
    else:
        fill = "" if null_strategy == "empty" else "unknown"
        result[target_cols] = result[target_cols].fillna(fill)

    stats["rows_out"] = len(result)
    stats["rows_dropped"] = stats["rows_in"] - stats["rows_out"]
    return result.reset_index(drop=True), stats


def preprocess_data(
    df: pd.DataFrame,
    text_columns=None,
    digit_columns=None,
    remove_accents: bool = False,
) -> pd.DataFrame:
    """
    Hàm giao diện chuẩn của module (theo đặc tả API): nhận DataFrame thô,
    trả về DataFrame đã làm sạch, GIỮ NGUYÊN số dòng.

    - Tạo thêm các cột '<tên>_clean', giữ nguyên cột gốc.
    - Giá trị thiếu được điền chuỗi rỗng (không xóa dòng).
    - Mặc định dùng TEXT_COLUMNS / DIGIT_COLUMNS trong schema.py; cột nào
      không có trong df sẽ được bỏ qua.
    """
    text_cols = [c for c in (TEXT_COLUMNS if text_columns is None else text_columns)
                 if c in df.columns]
    digit_cols = [c for c in (DIGIT_COLUMNS if digit_columns is None else digit_columns)
                  if c in df.columns]
    clean, _ = preprocess_dataframe(
        df, text_cols, digit_cols,
        null_strategy="empty", remove_accents=remove_accents, inplace=False,
    )
    return clean


def main():
    parser = argparse.ArgumentParser(description="Tiền xử lý dữ liệu cho bài toán dedup")
    parser.add_argument("-i", "--input", required=True, help="File CSV đầu vào")
    parser.add_argument("-o", "--output", required=True, help="File CSV đầu ra")
    parser.add_argument("-c", "--columns", nargs="+", required=True, help="Các cột văn bản cần chuẩn hóa")
    parser.add_argument("-d", "--digit-columns", nargs="*", default=[], help="Các cột chỉ giữ chữ số (vd: phone)")
    parser.add_argument("--null-strategy", default="empty", choices=["empty", "unknown", "drop"])
    parser.add_argument("--remove-accents", action="store_true", help="Bỏ dấu tiếng Việt")
    parser.add_argument("--inplace", action="store_true", help="Ghi đè cột gốc thay vì tạo cột *_clean")
    args = parser.parse_args()

    df = pd.read_csv(args.input, dtype=str, keep_default_na=False)
    clean, stats = preprocess_dataframe(
        df, args.columns, args.digit_columns,
        args.null_strategy, args.remove_accents, args.inplace,
    )
    clean.to_csv(args.output, index=False, encoding="utf-8-sig")

    print(f"Số dòng đầu vào : {stats['rows_in']}")
    print(f"Số dòng đầu ra  : {stats['rows_out']} (bị loại: {stats['rows_dropped']})")
    print("Số giá trị thiếu theo cột:")
    for col, n in stats["nulls_per_column"].items():
        print(f"  - {col}: {n}")
    print(f"Đã lưu: {args.output}")


if __name__ == "__main__":
    main()