Spaces:
Paused
Paused
Download app.py from datahub0/piimasking: direct link, hf CLI and curl.
- Browser
- Download file 5.82 kB
-
https://huggingface.co/spaces/datahub0/piimasking/resolve/main/app.py
- Command line
-
hf download hf://spaces/datahub0/piimasking/app.py
-
curl -L -o app.py https://huggingface.co/spaces/datahub0/piimasking/resolve/main/app.py
5.82 kB
| 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() |