Skip to main content

Privacy protection library for detecting and masking PII in text, logs, and files.

Project description

DataCloak ๐Ÿ”’

Privacy protection for Python applications โ€” detect and mask PII in text, logs, files, and data pipelines.

PyPI version Python License: MIT Tests Coverage


DataCloak is a production-ready Python library for automatically detecting and masking Personally Identifiable Information (PII) โ€” built for India-first compliance use cases (Aadhaar, PAN, UPI) while covering universal types like email and credit cards.

โœจ Features

Capability Description
8 built-in detectors Aadhaar, PAN, Mobile, Email, UPI ID, Credit Card (Luhn), IFSC, IPv4/IPv6
3 masking modes partial (keep trailing chars), full (redaction tags), hash (SHA-256)
File scanning .txt, .log, .csv โ€” extensible to PDF, DOCX, and more
Structured scan Returns findings dict without modifying original text
JSON reports Risk-level classified reports with per-type counts
CLI datacloak scan / mask / report commands
Pluggable detectors Subclass BaseDetector to add your own PII types

๐Ÿš€ Installation

pip install datacloak

Requires Python 3.11+.


โšก Quick Start

from datacloak import mask, scan

text = """
Aadhaar: 2345 6789 0123
PAN: ABCPE1234F
Email: alice@example.com
Phone: 9876543210
"""

# Partial masking (default) โ€” keeps trailing characters visible
print(mask(text))

Output:

Aadhaar: XXXX XXXX 0123
PAN: XXXXX1234F
Email: a***@example.com
Phone: ******3210

๐Ÿ“– Usage Guide

1. Masking Modes

from datacloak import mask

text = "Contact: alice@example.com | Phone: 9876543210"

# Partial โ€” show trailing characters (default)
mask(text, mode="partial")
# โ†’ 'Contact: a***@example.com | Phone: ******3210'

# Full โ€” replace with descriptive redaction tags
mask(text, mode="full")
# โ†’ 'Contact: [EMAIL_REDACTED] | Phone: [PHONE_REDACTED]'

# Hash โ€” SHA-256 digest (deterministic, reversible with original)
mask(text, mode="hash")
# โ†’ 'Contact: [HASH:142d78e466cacab3] | Phone: [HASH:7619ee8cea49187f]'

2. Scan Without Masking

from datacloak import scan

findings = scan("Send invoice to billing@acme.com, call 9876543210")
print(findings)
# {
#   "email": ["billing@acme.com"],
#   "phone": ["9876543210"]
# }

3. File Scanning

from datacloak import scan_file

# Scan a plain text or log file
result = scan_file("application.log")

# Scan a CSV (each cell is scanned individually)
result = scan_file("customers.csv")

print(result.summary)
# {"email": 142, "phone": 38, "aadhaar": 5}

print(result.findings[0])
# FileFinding(email='alice@example.com' @customers.csv:line=2)

4. Report Generation

from datacloak import report

r = report(text, source_label="user_input")
print(r.to_json())
{
  "generated_at": "2025-06-01T10:23:00+00:00",
  "source": "user_input",
  "total_findings": 4,
  "summary": {
    "aadhaar": 1,
    "email": 1,
    "phone": 1,
    "pan": 1
  },
  "details": { ... },
  "risk_level": "MEDIUM"
}

Save to disk:

r.save("pii_report.json")

๐Ÿ–ฅ๏ธ Command-Line Interface

DataCloak ships a full CLI via datacloak:

# Scan a file and display findings as a table
datacloak scan customers.txt

# Scan with JSON output
datacloak scan --format json customers.txt

# Mask a file (writes customers.masked.txt by default)
datacloak mask customers.txt

# Mask with full-redaction mode, specify output file
datacloak mask customers.txt --mode full --output clean.txt

# Print masked output to stdout (pipe-friendly)
datacloak mask customers.txt --stdout | grep "REDACTED"

# Generate a JSON report
datacloak report customers.txt

# Save report to file
datacloak report customers.txt --output report.json

# Verbose logging
datacloak -v scan customers.txt

๐Ÿ”Œ Writing a Custom Detector

DataCloak's detector framework is designed for extension. Subclass BaseDetector, set _pattern, and optionally override _validate():

import re
from datacloak.detectors import BaseDetector, Detection
from datacloak import scan

class PassportDetector(BaseDetector):
    name = "indian_passport"
    description = "Indian Passport Number (A-Z followed by 7 digits)"
    _pattern = re.compile(r"\b[A-Z]\d{7}\b")

# Use alongside built-in detectors
from datacloak.detectors import DEFAULT_DETECTORS

my_detectors = DEFAULT_DETECTORS + [PassportDetector()]
findings = scan("Passport: A1234567", detectors=my_detectors)
# {"indian_passport": ["A1234567"]}

Adding a new file format

from datacloak.file_scanner import FileHandler, register_handler
from pathlib import Path

class PDFHandler(FileHandler):
    extensions = (".pdf",)

    def extract_chunks(self, path: Path):
        # Use any PDF library (pdfplumber, PyMuPDF, etc.)
        import pdfplumber
        with pdfplumber.open(path) as pdf:
            for page_num, page in enumerate(pdf.pages, start=1):
                text = page.extract_text() or ""
                yield page_num, None, text

register_handler(PDFHandler())

# Now scan_file("document.pdf") works automatically

๐Ÿ•ต๏ธ Supported PII Types

Detector Example Validation
aadhaar 2345 6789 0123 12 digits, starts 2-9, space/hyphen/plain
pan ABCPE1234F AAAAA9999A format, valid entity code
phone 9876543210, +91 9876543210 10 digits, starts 6-9, optional country code
email alice@example.com RFC-5321 compliant
upi_id user@okaxis VPA format, non-email handles only
credit_card 4111 1111 1111 1111 13-19 digits, Luhn algorithm validated
ifsc HDFC0001234 4-alpha + 0 + 6-alphanumeric
ip_address 192.168.1.1, ::1 IPv4 (range-validated) and IPv6

๐Ÿงช Running Tests

# Clone the repo
git clone https://github.com/datacloak/datacloak.git
cd datacloak

# Install dev dependencies
pip install -e ".[dev]"

# Run tests
pytest

# Run with coverage
pytest --cov=datacloak --cov-report=term-missing

Target: โ‰ฅ 90% coverage.


๐Ÿ—๏ธ Architecture

datacloak/
โ”œโ”€โ”€ __init__.py          # Public API: mask(), scan(), report(), scan_file()
โ”œโ”€โ”€ detectors/
โ”‚   โ”œโ”€โ”€ __init__.py      # Exports all detectors + DEFAULT_DETECTORS registry
โ”‚   โ”œโ”€โ”€ base.py          # BaseDetector, Detection dataclass
โ”‚   โ”œโ”€โ”€ aadhaar.py
โ”‚   โ”œโ”€โ”€ pan.py
โ”‚   โ”œโ”€โ”€ mobile.py
โ”‚   โ”œโ”€โ”€ email.py
โ”‚   โ”œโ”€โ”€ upi.py
โ”‚   โ”œโ”€โ”€ credit_card.py   # Luhn validation
โ”‚   โ”œโ”€โ”€ ifsc.py
โ”‚   โ””โ”€โ”€ ip_address.py    # IPv4 + IPv6
โ”œโ”€โ”€ masker.py            # mask_text(), masking modes logic
โ”œโ”€โ”€ scanner.py           # scan_text(), scan_summary()
โ”œโ”€โ”€ file_scanner.py      # scan_file(), mask_file(), FileHandler interface
โ”œโ”€โ”€ reporter.py          # Report dataclass, generate_report_*()
โ””โ”€โ”€ cli.py               # Click CLI: scan, mask, report commands

Design principles applied:

  • Single Responsibility โ€” each detector, masker, scanner, and reporter is self-contained
  • Open/Closed โ€” extend via BaseDetector or FileHandler without modifying core
  • Liskov Substitution โ€” any BaseDetector subclass drops in transparently
  • Dependency Injection โ€” all public functions accept detectors= for testability
  • Logging โ€” structured logging throughout, silent by default (NullHandler)

๐Ÿ“ฆ Publishing to PyPI

See PUBLISHING.md for a complete step-by-step guide.

# Quick summary
pip install build twine
python -m build
twine upload dist/*

๐Ÿ“„ License

MIT License โ€” Copyright ยฉ 2025 DataCloak Contributors.


๐Ÿค Contributing

Contributions, issues, and feature requests are welcome! Please read the contributing guide and open a pull request.

  1. Fork the repository
  2. Create a feature branch: git checkout -b feat/my-detector
  3. Write your code and tests
  4. Run pytest and ensure coverage stays โ‰ฅ 90%
  5. Open a pull request

DataCloak โ€” because privacy is not optional.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

datacloak-0.1.0.tar.gz (23.7 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

datacloak-0.1.0-py3-none-any.whl (26.4 kB view details)

Uploaded Python 3

File details

Details for the file datacloak-0.1.0.tar.gz.

File metadata

  • Download URL: datacloak-0.1.0.tar.gz
  • Upload date:
  • Size: 23.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.6

File hashes

Hashes for datacloak-0.1.0.tar.gz
Algorithm Hash digest
SHA256 8aaa8ff692e2d9ec7265184ebab4df1df37b63fd7140dc1529cc22b8ee407519
MD5 69d5ba5e5cbe8809c4093a2aa637e55c
BLAKE2b-256 8a326ac5f54bebd3a35a3dbcdda726e50d889a99f37be78ca508d24dc4153015

See more details on using hashes here.

File details

Details for the file datacloak-0.1.0-py3-none-any.whl.

File metadata

  • Download URL: datacloak-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 26.4 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.6

File hashes

Hashes for datacloak-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 471aa94d336b7186908a72e6168c98550b594d55ce0f9db89212afc4b59690aa
MD5 0a93a250b75106afc0ac7d1fa93c0173
BLAKE2b-256 cdb67c43d90b904de26fd2b8ef36b0dea9908d3929bf6a3d0937c460c4557547

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page