Skip to main content

AI-powered privacy and harmful content detection library

Project description

Zero Harm AI Detectors

AI-powered detection of PII, secrets, and harmful content in text.

Now with transformer-based models for 85-95% accuracy in person name detection!

๐Ÿš€ What's New in v0.2.x

  • ๐Ÿค– AI-Powered Detection: Uses BERT/RoBERTa for accurate PII detection
  • ๐ŸŽฏ Unified Pipeline: Single ZeroHarmPipeline class for everything
  • ๐Ÿ“Š Confidence Scores: Every detection includes confidence (0-1)
  • ๐Ÿ”„ Backward Compatible: Drop-in replacement - works with old API
  • โšก Smart Detection: AI accuracy + regex speed where appropriate
  • ๐ŸŒ Better Support: International names, locations, organizations

๐Ÿ“ฆ Installation

Quick Start (CPU)

pip install zero_harm_ai_detectors transformers torch

For GPU (Faster)

pip install zero_harm_ai_detectors transformers
pip install torch --extra-index-url https://download.pytorch.org/whl/cu118

Lightweight (Regex Only)

pip install zero_harm_ai_detectors

๐ŸŽฏ Quick Start

One-Line Detection (Easiest)

from zero_harm_ai_detectors import detect_all_threats

result = detect_all_threats(
    "Contact John Smith at john@example.com. API key: sk-abc123."
)

print(result['redacted'])
# Output: Contact [REDACTED_PERSON] at [REDACTED_EMAIL]. API key: [REDACTED_SECRET].

print(result['detections'])
# Output: {'PERSON': [...], 'EMAIL': [...], 'API_KEY': [...]}

Full Pipeline (Recommended)

from zero_harm_ai_detectors import ZeroHarmPipeline, RedactionStrategy

# Initialize once (loads models)
pipeline = ZeroHarmPipeline()

# Use many times
text = "Email John Smith at john@example.com or call 555-123-4567"
result = pipeline.detect(text, redaction_strategy=RedactionStrategy.TOKEN)

print(f"Original: {result.original_text}")
print(f"Redacted: {result.redacted_text}")

for det in result.detections:
    print(f"  {det.type}: {det.text} (confidence: {det.confidence:.0%})")

Legacy API (Still Works!)

# Old code works unchanged!
from zero_harm_ai_detectors import detect_pii, detect_secrets, redact_text

text = "Contact john@example.com with API key sk-abc123"

pii = detect_pii(text)  # Now uses AI automatically!
secrets = detect_secrets(text)

redacted = redact_text(text, {**pii, **secrets})

๐ŸŽจ Features

Detectable Content

PII (Personally Identifiable Information)

  • โœ‰๏ธ Emails: john.doe@email.com
  • ๐Ÿ“ž Phone Numbers: 555-123-4567
  • ๐Ÿ†” SSN: 123-45-6789
  • ๐Ÿ’ณ Credit Cards: 4532-0151-1283-0366
  • ๐Ÿ‘ค Person Names: AI-powered, 85-95% accuracy (NEW!)
  • ๐Ÿ“ Locations: Cities, states, countries (NEW!)
  • ๐Ÿข Organizations: Companies, institutions (NEW!)
  • ๐Ÿ  Addresses: Street addresses, P.O. boxes
  • ๐Ÿฅ Medical Records: MRN detection
  • ๐Ÿš— Driver's Licenses: US state formats
  • ๐Ÿ“… Dates of Birth: Multiple formats

Secrets & Credentials

  • ๐Ÿ”‘ API Keys: OpenAI, AWS, Google, etc.
  • ๐ŸŽซ Tokens: GitHub, Slack, Stripe, JWT
  • ๐Ÿ” Passwords: Pattern-based detection

Harmful Content

  • โ˜ ๏ธ Toxic Language
  • โš”๏ธ Threats
  • ๐Ÿ˜ก Insults
  • ๐Ÿ”ž Obscene Content
  • ๐Ÿ‘ฟ Identity Hate

Redaction Strategies

# TOKEN: [REDACTED_EMAIL]
RedactionStrategy.TOKEN

# MASK_ALL: ********************
RedactionStrategy.MASK_ALL

# MASK_LAST4: ****************.com
RedactionStrategy.MASK_LAST4

# HASH: 8d969eef6ecad3c29a3a...
RedactionStrategy.HASH

๐Ÿ“š Advanced Usage

Custom Configuration

from zero_harm_ai_detectors import ZeroHarmPipeline, PipelineConfig

config = PipelineConfig(
    pii_threshold=0.8,  # Higher confidence threshold
    pii_model="Jean-Baptiste/roberta-large-ner-english",  # Better model
    harmful_threshold_per_label=0.6,
    device="cuda"  # Use GPU
)

pipeline = ZeroHarmPipeline(config)

Selective Detection

# Only detect PII
result = pipeline.detect(
    text,
    detect_pii=True,
    detect_secrets=False,
    detect_harmful=False
)

Filtering by Confidence

result = pipeline.detect(text)

# Only high-confidence detections
high_conf = [d for d in result.detections if d.confidence >= 0.9]

for det in high_conf:
    print(f"{det.type}: {det.text} ({det.confidence:.2%})")

Batch Processing

texts = [
    "Email: john@example.com",
    "Phone: 555-123-4567",
    "Meet Jane at Microsoft"
]

for text in texts:
    result = pipeline.detect(text)
    print(f"Text: {text}")
    print(f"Redacted: {result.redacted_text}")

API Integration

from flask import Flask, request, jsonify
from zero_harm_ai_detectors import ZeroHarmPipeline

app = Flask(__name__)

# Load once at startup
pipeline = ZeroHarmPipeline()

@app.route("/api/check_privacy", methods=["POST"])
def check_privacy():
    data = request.json
    text = data.get("text", "")
    
    result = pipeline.detect(text)
    
    return jsonify({
        "original": result.original_text,
        "redacted": result.redacted_text,
        "detections": result.to_dict()["detections"],
        "harmful": result.harmful,
        "severity": result.severity
    })

๐Ÿ”ฌ Comparison: Regex vs AI

Feature Regex (Old) AI (New) Winner
Person Names 30-40% 85-95% ๐Ÿ† AI
Locations โŒ 80-90% ๐Ÿ† AI
Organizations โŒ 75-85% ๐Ÿ† AI
Context Understanding โŒ โœ… ๐Ÿ† AI
Email Detection 99%+ 99%+ ๐Ÿค Tie
Phone Detection 95%+ 95%+ ๐Ÿค Tie
Speed (single) 1-5ms 50-200ms ๐Ÿ† Regex
False Positives High Low ๐Ÿ† AI

โšก Performance

Speed Benchmarks

Operation Time Notes
Pipeline loading 5-10s One-time at startup
Email detection 50ms AI + regex
Person name 150ms AI (transformer)
Full detection 200ms All types

Best Practices

# โœ… Good: Load once, reuse
PIPELINE = ZeroHarmPipeline()

def process(text):
    return PIPELINE.detect(text)  # Fast!

# โŒ Bad: Load every time
def process(text):
    pipeline = ZeroHarmPipeline()  # Slow!
    return pipeline.detect(text)

๐Ÿ”„ Migration from v0.1.x

Your old code works without changes:

# Old code (v0.1.x)
from zero_harm_ai_detectors import detect_pii, detect_secrets

pii = detect_pii("Contact john@example.com")  # Now uses AI!
secrets = detect_secrets("API key sk-abc123")

# Force old regex behavior if needed
pii = detect_pii(text, use_ai=False)

See MIGRATION_GUIDE.md for detailed instructions.

๐Ÿงช Testing

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

# Run tests
pytest

# With coverage
pytest --cov=zero_harm_ai_detectors --cov-report=html

# Run specific test
pytest tests/test_ai_detectors.py -v

๐Ÿ“Š Model Information

PII Detection Models

Model Size Languages Accuracy
dslim/bert-base-NER 420MB English 85%
Jean-Baptiste/roberta-large-ner-english 1.3GB English 92%

Harmful Content Model

Model Size Languages Categories
unitary/multilingual-toxic-xlm-roberta 1.1GB 100+ 6 labels

๐Ÿ’ก Use Cases

  • API Gateways: Scan requests/responses for sensitive data
  • Chat Applications: Prevent PII leakage
  • Data Pipelines: Clean datasets before sharing
  • Content Moderation: Filter harmful content
  • Compliance: GDPR, HIPAA, PCI-DSS
  • Security: Detect leaked credentials

๐Ÿ› Troubleshooting

Models not loading

pip install transformers torch

Out of memory

config = PipelineConfig(device="cpu")  # Use CPU

Slow performance

# Skip unnecessary detection
result = pipeline.detect(text, detect_harmful=False)

๐Ÿ“ž Support

๐Ÿ“„ License

MIT License - see LICENSE file for details.

๐Ÿ™ Acknowledgments

  • Hugging Face for transformer models
  • PyTorch team for the ML framework

Made with โค๏ธ by Zero Harm AI LLC

Protecting privacy, one detection at a time.

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

zero_harm_ai_detectors-0.2.3.tar.gz (37.8 kB view details)

Uploaded Source

Built Distribution

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

zero_harm_ai_detectors-0.2.3-py3-none-any.whl (23.0 kB view details)

Uploaded Python 3

File details

Details for the file zero_harm_ai_detectors-0.2.3.tar.gz.

File metadata

  • Download URL: zero_harm_ai_detectors-0.2.3.tar.gz
  • Upload date:
  • Size: 37.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.9.24

File hashes

Hashes for zero_harm_ai_detectors-0.2.3.tar.gz
Algorithm Hash digest
SHA256 9a3a1d7ca542afb0af3717ca96b22245519ecbe9c0afe1b7e4d13794531416ff
MD5 5ff3d32b3192b0c474bced51dba3d614
BLAKE2b-256 f05c495c252e65e558f1bfb8ca15b6f343821f86dcab3d2c47027990efb6cc9e

See more details on using hashes here.

File details

Details for the file zero_harm_ai_detectors-0.2.3-py3-none-any.whl.

File metadata

File hashes

Hashes for zero_harm_ai_detectors-0.2.3-py3-none-any.whl
Algorithm Hash digest
SHA256 e5ef2b4644eb506f6643de77f2729baed8a10122be5c068048c5bcdd9b5f0baf
MD5 c71a98a125e6a5d34c55aef45250960f
BLAKE2b-256 ebaefcee31685959508ed4ca186f4e1a6bb3504d4e1f28efd848ca53635df0a1

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