Spaces:
Paused
Paused
File size: 6,043 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 | """
hashing_dedup.py - Hashing Engine: phát hiện bản ghi trùng HOÀN TOÀN (exact match).
Người phụ trách: Liêu Văn Đạt (cài đặt ở Tuần 5).
Quy ước kết quả (xem docs/API_SPEC.md):
- Bản ghi có rec_id nhỏ nhất trong nhóm là bản đại diện: is_duplicate=False.
- Các bản còn lại trong nhóm: is_duplicate=True.
- Mọi bản ghi trong nhóm >= 2 bản có cùng duplicate_group_id;
confidence_score = 1.0, detection_method = 'hashing'.
Cách hoạt động (xem Chương 2, mục 2.1):
1. Với MỖI bản ghi: ghép các giá trị ở `match_columns` rồi băm (SHA-256 hoặc MD5)
-> hash_digest. Mỗi bản ghi được băm độc lập, chi phí O(n).
2. Dùng dict (bảng băm) gom các vị trí dòng theo digest: tra cứu/chèn O(1) nên
toàn bộ quá trình O(n), KHÔNG cần so sánh từng cặp -> không cần Blocking.
3. Digest nào có >= 2 dòng là một nhóm trùng khớp hoàn toàn.
Lưu ý về vị trí trong pipeline: hàm này phải được gọi trên TOÀN BỘ DataFrame sau tiền
xử lý (không chia theo block), nếu không hai bản ghi trùng hoàn toàn nằm ở hai block
khác nhau sẽ bị bỏ sót.
"""
from __future__ import annotations
import hashlib
from typing import List, Optional, Sequence
import pandas as pd
from src.schema import (
DEFAULT_HASH_ALGORITHM,
DEFAULT_MATCH_COLUMNS,
GROUP_COL,
HASH_ALGORITHMS,
HASH_COL,
ID_COL,
IS_DUP_COL,
METHOD_COL,
SCORE_COL,
init_result_columns,
)
# Ký tự phân tách giữa các giá trị khi ghép để băm: ký tự điều khiển ASCII 0x1F
# (Unit Separator). Nó không xuất hiện trong dữ liệu đã qua preprocess.py (đã loại ký
# tự đặc biệt) nên ("ab", "c") và ("a", "bc") luôn cho hai digest khác nhau.
_SEPARATOR = "\x1f"
_METHOD_NAME = "hashing"
def _to_text(value) -> str:
"""Giá trị thiếu (None/NaN) -> chuỗi rỗng; còn lại -> str(value)."""
if value is None or (not isinstance(value, str) and pd.isna(value)):
return ""
return str(value)
def _check_algorithm(algorithm: str) -> None:
if algorithm not in HASH_ALGORITHMS:
raise ValueError(
f"algorithm phải thuộc {HASH_ALGORITHMS}, nhận được: {algorithm!r}"
)
def _rec_id_order(ids: pd.Series) -> List:
"""
Khóa so sánh rec_id để chọn "rec_id nhỏ nhất".
Nếu mọi rec_id đều là số thì so theo SỐ ('9' < '10'); ngược lại so theo chuỗi.
(Dữ liệu đọc bằng dtype=str nên so chuỗi trực tiếp sẽ cho '10' < '9'.)
"""
numeric = pd.to_numeric(ids, errors="coerce")
if numeric.notna().all():
return numeric.tolist()
return ids.astype(str).tolist()
def compute_hash_digest(values: Sequence[str], algorithm: str = DEFAULT_HASH_ALGORITHM) -> str:
"""
Nối các giá trị (đã chuẩn hóa) bằng ký tự phân tách an toàn rồi băm.
Trả về chuỗi hex ('md5' -> 32 ký tự, 'sha256' -> 64 ký tự).
Ném ValueError nếu `algorithm` không thuộc HASH_ALGORITHMS.
"""
_check_algorithm(algorithm)
joined = _SEPARATOR.join(_to_text(v) for v in values)
# usedforsecurity=False: chỉ dùng băm để so khớp, không phải mục đích bảo mật
# (cho phép dùng MD5 cả trên hệ thống bật chế độ FIPS).
return hashlib.new(algorithm, joined.encode("utf-8"), usedforsecurity=False).hexdigest()
def detect_exact_duplicates(
df: pd.DataFrame,
match_columns: Optional[Sequence[str]] = None,
hash_algorithm: str = DEFAULT_HASH_ALGORITHM,
) -> pd.DataFrame:
_check_algorithm(hash_algorithm)
columns = list(DEFAULT_MATCH_COLUMNS if match_columns is None else match_columns)
if not columns:
raise ValueError("match_columns không được rỗng")
missing = [c for c in [ID_COL, *columns] if c not in df.columns]
if missing:
raise ValueError(
f"Thiếu cột để băm: {missing}. Hãy chạy tiền xử lý (preprocess_data) trước."
)
out = init_result_columns(df) # bản sao, không sửa df đầu vào
if len(out) == 0:
return out
# Bước 1: băm từng bản ghi (độc lập, O(n))
rows = list(out[columns].itertuples(index=False, name=None))
digests = [compute_hash_digest(row, hash_algorithm) for row in rows]
out[HASH_COL] = digests
# Bước 2: gom vị trí dòng theo digest bằng dict (bảng băm, tra cứu O(1))
positions_by_digest: dict = {}
for pos, (row, digest) in enumerate(zip(rows, digests)):
if any(_to_text(v).strip() for v in row): # bỏ qua dòng rỗng hoàn toàn
positions_by_digest.setdefault(digest, []).append(pos)
# Bước 3: gắn nhãn cho các nhóm có >= 2 bản ghi
rec_ids = out[ID_COL].tolist()
order = _rec_id_order(out[ID_COL])
is_dup = out[IS_DUP_COL].tolist()
group_ids = out[GROUP_COL].tolist()
scores = out[SCORE_COL].tolist()
methods = out[METHOD_COL].tolist()
for positions in positions_by_digest.values():
if len(positions) < 2:
continue
representative = min(positions, key=lambda p: order[p])
group_id = f"H{rec_ids[representative]}"
for p in positions:
is_dup[p] = p != representative
group_ids[p] = group_id
scores[p] = 1.0
methods[p] = _METHOD_NAME
# Ghi lại từng cột với kiểu rõ ràng. Cột chuỗi ép về object để ô trống luôn là None
# (pandas 3.x tự suy luận sang kiểu `str` và đổi None thành NaN, pandas 2.x thì không).
out[IS_DUP_COL] = pd.Series(is_dup, index=out.index, dtype=bool)
out[GROUP_COL] = pd.Series(group_ids, index=out.index, dtype=object)
out[SCORE_COL] = pd.Series(scores, index=out.index, dtype=float)
out[METHOD_COL] = pd.Series(methods, index=out.index, dtype=object)
return out
|