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
ZeroHarmPipelineclass 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
- Email: info@zeroharmai.com
- GitHub Issues: Create an issue
๐ 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
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
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
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
9a3a1d7ca542afb0af3717ca96b22245519ecbe9c0afe1b7e4d13794531416ff
|
|
| MD5 |
5ff3d32b3192b0c474bced51dba3d614
|
|
| BLAKE2b-256 |
f05c495c252e65e558f1bfb8ca15b6f343821f86dcab3d2c47027990efb6cc9e
|
File details
Details for the file zero_harm_ai_detectors-0.2.3-py3-none-any.whl.
File metadata
- Download URL: zero_harm_ai_detectors-0.2.3-py3-none-any.whl
- Upload date:
- Size: 23.0 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.9.24
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
e5ef2b4644eb506f6643de77f2729baed8a10122be5c068048c5bcdd9b5f0baf
|
|
| MD5 |
c71a98a125e6a5d34c55aef45250960f
|
|
| BLAKE2b-256 |
ebaefcee31685959508ed4ca186f4e1a6bb3504d4e1f28efd848ca53635df0a1
|