File size: 5,819 Bytes
73e2be4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ac646bf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
73e2be4
 
 
 
 
 
ac646bf
73e2be4
 
 
 
 
 
e6a1816
73e2be4
 
 
 
 
 
 
 
 
 
 
 
 
 
ac646bf
 
 
 
 
 
 
73e2be4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e6a1816
 
9d1c980
73e2be4
 
 
 
 
 
 
 
 
 
 
ac646bf
 
 
73e2be4
9d1c980
73e2be4
 
 
 
 
9d1c980
73e2be4
 
 
 
 
 
ac646bf
73e2be4
 
 
 
 
 
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
import gradio as gr
import pandas as pd
import hashlib
import tempfile
import os

# ==========================================
# PHẦN 1: CÁC HÀM BIẾN ĐỔI DỮ LIỆU (TRANSFORM)
# ==========================================

def mask_ho_ten(name):
    parts = str(name).strip().split()
    if len(parts) <= 1: return name
    masked = [parts[0]] # Giữ nguyên Họ
    for p in parts[1:]:
        # Che Tên đệm và Tên chính (Giữ chữ cái đầu)
        masked.append(p[0] + '*' * (len(p) - 1))
    return ' '.join(masked)

def mask_cccd(cccd):
    # Loại bỏ ".0" nếu pandas đọc nhầm thành số thực, đảm bảo đủ 12 số
    s = str(cccd).split('.')[0].strip().zfill(12) 
    return s[:3] + '******' + s[-3:]

def mask_phone(phone):
    s = str(phone).split('.')[0].strip().zfill(10)
    return s[:3] + '*****' + s[-2:]

def mask_email(email):
    email_str = str(email).strip()
    if '@' not in email_str: 
        return email_str
    
    name_part, domain_part = email_str.split('@', 1)
    if len(name_part) <= 2:
        masked_name = name_part[0] + '*' * (len(name_part)-1) if len(name_part) > 0 else ""
    else:
        masked_name = name_part[:2] + '*' * (len(name_part) - 2)
        
    return f"{masked_name}@{domain_part}"

def hash_sha256(data):
    return hashlib.sha256(str(data).strip().encode()).hexdigest()


# ==========================================
# PHẦN 2: LUỒNG ETL CHÍNH (PIPELINE)
# ==========================================

def process_data(file_obj, opt_name, opt_cccd, opt_phone, opt_email, opt_credit, opt_password):
    if file_obj is None:
        return None, None, None
    
    try:
        # BƯỚC 1 - EXTRACT: Đọc file CSV
        df = pd.read_csv(file_obj.name)
        df_original_preview = df.head(5).copy()
        
        # BƯỚC 2 - TRANSFORM: Áp dụng các luật che giấu
        df_secured = df.copy()
        
        if opt_name and 'Ho_Ten' in df_secured.columns:
            df_secured['Ho_Ten'] = df_secured['Ho_Ten'].apply(mask_ho_ten)
            
        if opt_cccd and 'CCCD' in df_secured.columns:
            df_secured['CCCD'] = df_secured['CCCD'].apply(mask_cccd)
            
        if opt_phone and 'So_Dien_Thoai' in df_secured.columns:
            df_secured['So_Dien_Thoai'] = df_secured['So_Dien_Thoai'].apply(mask_phone)
            
        if opt_email and 'Email' in df_secured.columns:
            df_secured['Email'] = df_secured['Email'].apply(mask_email)
            
        if opt_credit and 'So_The_Tin_Dung' in df_secured.columns:
            df_secured['So_The_Tin_Dung'] = df_secured['So_The_Tin_Dung'].apply(hash_sha256)
            
        if opt_password and 'Mat_Khau' in df_secured.columns:
            df_secured['Mat_Khau'] = df_secured['Mat_Khau'].apply(hash_sha256)
            
        df_secured_preview = df_secured.head(5).copy()
        
        # BƯỚC 3 - LOAD: Xuất ra file tạm an toàn để tải xuống
        temp_dir = tempfile.gettempdir()
        output_path = os.path.join(temp_dir, "ecommerce_customers_secured.csv")
        df_secured.to_csv(output_path, index=False)
        
        return df_original_preview, df_secured_preview, output_path
    
    except Exception as e:
        error_df = pd.DataFrame([{"Lỗi hệ thống": str(e)}])
        return error_df, pd.DataFrame(), None


# ==========================================
# PHẦN 3: XÂY DỰNG GIAO DIỆN WEB VỚI GRADIO
# ==========================================

# Khôi phục lại theme Soft bo góc siêu đẹp của m đây
with gr.Blocks(theme=gr.themes.Soft()) as demo:
    gr.Markdown("# Hệ Thống Ẩn Danh Hóa Dữ Liệu (PII Masking Tool)")
    gr.Markdown("Công cụ tự động làm sạch và che giấu thông tin định danh cá nhân trước khi trích xuất dữ liệu.")
    
    with gr.Row():
        # CỘT TRÁI: Khu vực tải file và cài đặt
        with gr.Column(scale=1):
            input_file = gr.File(label="1. Tải lên tệp dữ liệu thô (.csv)", file_types=[".csv"])
            
            gr.Markdown("### 2. Cấu hình Luật Bảo Mật (Transform Rules)")
            chk_name = gr.Checkbox(label="Che khuất Họ Tên (Partial Masking)", value=True)
            chk_cccd = gr.Checkbox(label="Che khuất số CCCD (Giữ 3 số đầu/cuối)", value=True)
            chk_phone = gr.Checkbox(label="Che khuất Số Điện Thoại (Che 5 số giữa)", value=True)
            chk_email = gr.Checkbox(label="Che khuất Email (Giữ 2 ký tự đầu và tên miền)", value=True)
            chk_credit = gr.Checkbox(label="Băm Số Thẻ Tín Dụng (Thuật toán SHA-256)", value=True)
            chk_password = gr.Checkbox(label="Băm Mật Khẩu (Thuật toán SHA-256)", value=True)
            
            btn_run = gr.Button("THỰC THI PIPELINE", variant="primary")
            
            output_file = gr.File(label="3. Tải xuống tệp dữ liệu an toàn", interactive=False)
            
        # CỘT PHẢI: Khu vực hiển thị kết quả (Bảng Before & After)
        with gr.Column(scale=2):
            gr.Markdown("### Trực quan hóa đối chiếu dữ liệu")
            df_before = gr.Dataframe(label="Dữ liệu Gốc (Bản xem trước 5 dòng)", interactive=False)
            df_after = gr.Dataframe(label="Dữ liệu An Toàn (Bản xem trước 5 dòng)", interactive=False)
            
    # Gắn sự kiện: Khi bấm nút "Thực thi", chạy hàm process_data
    btn_run.click(
        fn=process_data,
        inputs=[input_file, chk_name, chk_cccd, chk_phone, chk_email, chk_credit, chk_password],
        outputs=[df_before, df_after, output_file]
    )

# Khởi chạy ứng dụng
if __name__ == "__main__":
    demo.launch()