Spaces:
Runtime error
Runtime error
add pii guardrails that also work for banned words guardrails
Browse files- guardrails_genie/{spacy_model.py → guardrails/banned_terms/llm_judge.py} +0 -0
- guardrails_genie/guardrails/pii/presidio_pii_guardrail.py +76 -20
- guardrails_genie/guardrails/pii/regex_pii_guardrail.py +27 -11
- guardrails_genie/guardrails/pii/run_transformers.py +35 -0
- guardrails_genie/guardrails/pii/transformers_pipeline_guardrail.py +179 -0
guardrails_genie/{spacy_model.py → guardrails/banned_terms/llm_judge.py}
RENAMED
|
File without changes
|
guardrails_genie/guardrails/pii/presidio_pii_guardrail.py
CHANGED
|
@@ -1,8 +1,8 @@
|
|
| 1 |
-
from typing import List, Dict, Optional, ClassVar
|
| 2 |
import weave
|
| 3 |
from pydantic import BaseModel
|
| 4 |
|
| 5 |
-
from presidio_analyzer import AnalyzerEngine
|
| 6 |
from presidio_anonymizer import AnonymizerEngine
|
| 7 |
|
| 8 |
from ..base import Guardrail
|
|
@@ -10,18 +10,22 @@ from ..base import Guardrail
|
|
| 10 |
class PresidioPIIGuardrailResponse(BaseModel):
|
| 11 |
contains_pii: bool
|
| 12 |
detected_pii_types: Dict[str, List[str]]
|
| 13 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
explanation: str
|
| 15 |
anonymized_text: Optional[str] = None
|
| 16 |
|
| 17 |
#TODO: Add support for transformers workflow and not just Spacy
|
| 18 |
class PresidioPIIGuardrail(Guardrail):
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
|
| 26 |
analyzer: AnalyzerEngine
|
| 27 |
anonymizer: AnonymizerEngine
|
|
@@ -33,7 +37,10 @@ class PresidioPIIGuardrail(Guardrail):
|
|
| 33 |
self,
|
| 34 |
selected_entities: Optional[List[str]] = None,
|
| 35 |
should_anonymize: bool = False,
|
| 36 |
-
language: str = "en"
|
|
|
|
|
|
|
|
|
|
| 37 |
):
|
| 38 |
# Initialize default values
|
| 39 |
if selected_entities is None:
|
|
@@ -42,13 +49,48 @@ class PresidioPIIGuardrail(Guardrail):
|
|
| 42 |
"LOCATION", "CREDIT_CARD", "US_SSN"
|
| 43 |
]
|
| 44 |
|
|
|
|
|
|
|
|
|
|
| 45 |
# Validate selected entities
|
| 46 |
-
invalid_entities = set(selected_entities) - set(
|
| 47 |
if invalid_entities:
|
| 48 |
raise ValueError(f"Invalid entities: {invalid_entities}")
|
| 49 |
|
| 50 |
-
# Initialize
|
| 51 |
analyzer = AnalyzerEngine()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 52 |
anonymizer = AnonymizerEngine()
|
| 53 |
|
| 54 |
# Call parent class constructor with all fields
|
|
@@ -61,9 +103,13 @@ class PresidioPIIGuardrail(Guardrail):
|
|
| 61 |
)
|
| 62 |
|
| 63 |
@weave.op()
|
| 64 |
-
def guard(self, prompt: str, **kwargs) -> PresidioPIIGuardrailResponse:
|
| 65 |
"""
|
| 66 |
Check if the input prompt contains any PII using Presidio.
|
|
|
|
|
|
|
|
|
|
|
|
|
| 67 |
"""
|
| 68 |
# Analyze text for PII
|
| 69 |
analyzer_results = self.analyzer.analyze(
|
|
@@ -104,10 +150,20 @@ class PresidioPIIGuardrail(Guardrail):
|
|
| 104 |
)
|
| 105 |
anonymized_text = anonymized_result.text
|
| 106 |
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import List, Dict, Optional, ClassVar, Any
|
| 2 |
import weave
|
| 3 |
from pydantic import BaseModel
|
| 4 |
|
| 5 |
+
from presidio_analyzer import AnalyzerEngine, RecognizerRegistry, Pattern, PatternRecognizer
|
| 6 |
from presidio_anonymizer import AnonymizerEngine
|
| 7 |
|
| 8 |
from ..base import Guardrail
|
|
|
|
| 10 |
class PresidioPIIGuardrailResponse(BaseModel):
|
| 11 |
contains_pii: bool
|
| 12 |
detected_pii_types: Dict[str, List[str]]
|
| 13 |
+
explanation: str
|
| 14 |
+
anonymized_text: Optional[str] = None
|
| 15 |
+
|
| 16 |
+
class PresidioPIIGuardrailSimpleResponse(BaseModel):
|
| 17 |
+
contains_pii: bool
|
| 18 |
explanation: str
|
| 19 |
anonymized_text: Optional[str] = None
|
| 20 |
|
| 21 |
#TODO: Add support for transformers workflow and not just Spacy
|
| 22 |
class PresidioPIIGuardrail(Guardrail):
|
| 23 |
+
@staticmethod
|
| 24 |
+
def get_available_entities() -> List[str]:
|
| 25 |
+
registry = RecognizerRegistry()
|
| 26 |
+
analyzer = AnalyzerEngine(registry=registry)
|
| 27 |
+
return [recognizer.supported_entities[0]
|
| 28 |
+
for recognizer in analyzer.registry.recognizers]
|
| 29 |
|
| 30 |
analyzer: AnalyzerEngine
|
| 31 |
anonymizer: AnonymizerEngine
|
|
|
|
| 37 |
self,
|
| 38 |
selected_entities: Optional[List[str]] = None,
|
| 39 |
should_anonymize: bool = False,
|
| 40 |
+
language: str = "en",
|
| 41 |
+
deny_lists: Optional[Dict[str, List[str]]] = None,
|
| 42 |
+
regex_patterns: Optional[Dict[str, List[Dict[str, str]]]] = None,
|
| 43 |
+
custom_recognizers: Optional[List[Any]] = None
|
| 44 |
):
|
| 45 |
# Initialize default values
|
| 46 |
if selected_entities is None:
|
|
|
|
| 49 |
"LOCATION", "CREDIT_CARD", "US_SSN"
|
| 50 |
]
|
| 51 |
|
| 52 |
+
# Get available entities dynamically
|
| 53 |
+
available_entities = self.get_available_entities()
|
| 54 |
+
|
| 55 |
# Validate selected entities
|
| 56 |
+
invalid_entities = set(selected_entities) - set(available_entities)
|
| 57 |
if invalid_entities:
|
| 58 |
raise ValueError(f"Invalid entities: {invalid_entities}")
|
| 59 |
|
| 60 |
+
# Initialize analyzer with default recognizers
|
| 61 |
analyzer = AnalyzerEngine()
|
| 62 |
+
|
| 63 |
+
# Add custom recognizers if provided
|
| 64 |
+
if custom_recognizers:
|
| 65 |
+
for recognizer in custom_recognizers:
|
| 66 |
+
analyzer.registry.add_recognizer(recognizer)
|
| 67 |
+
|
| 68 |
+
# Add deny list recognizers if provided
|
| 69 |
+
if deny_lists:
|
| 70 |
+
for entity_type, tokens in deny_lists.items():
|
| 71 |
+
deny_list_recognizer = PatternRecognizer(
|
| 72 |
+
supported_entity=entity_type,
|
| 73 |
+
deny_list=tokens
|
| 74 |
+
)
|
| 75 |
+
analyzer.registry.add_recognizer(deny_list_recognizer)
|
| 76 |
+
|
| 77 |
+
# Add regex pattern recognizers if provided
|
| 78 |
+
if regex_patterns:
|
| 79 |
+
for entity_type, patterns in regex_patterns.items():
|
| 80 |
+
presidio_patterns = [
|
| 81 |
+
Pattern(
|
| 82 |
+
name=pattern.get("name", f"pattern_{i}"),
|
| 83 |
+
regex=pattern["regex"],
|
| 84 |
+
score=pattern.get("score", 0.5)
|
| 85 |
+
) for i, pattern in enumerate(patterns)
|
| 86 |
+
]
|
| 87 |
+
regex_recognizer = PatternRecognizer(
|
| 88 |
+
supported_entity=entity_type,
|
| 89 |
+
patterns=presidio_patterns
|
| 90 |
+
)
|
| 91 |
+
analyzer.registry.add_recognizer(regex_recognizer)
|
| 92 |
+
|
| 93 |
+
# Initialize Presidio engines
|
| 94 |
anonymizer = AnonymizerEngine()
|
| 95 |
|
| 96 |
# Call parent class constructor with all fields
|
|
|
|
| 103 |
)
|
| 104 |
|
| 105 |
@weave.op()
|
| 106 |
+
def guard(self, prompt: str, return_detected_types: bool = True, **kwargs) -> PresidioPIIGuardrailResponse | PresidioPIIGuardrailSimpleResponse:
|
| 107 |
"""
|
| 108 |
Check if the input prompt contains any PII using Presidio.
|
| 109 |
+
|
| 110 |
+
Args:
|
| 111 |
+
prompt: The text to analyze
|
| 112 |
+
return_detected_types: If True, returns detailed PII type information
|
| 113 |
"""
|
| 114 |
# Analyze text for PII
|
| 115 |
analyzer_results = self.analyzer.analyze(
|
|
|
|
| 150 |
)
|
| 151 |
anonymized_text = anonymized_result.text
|
| 152 |
|
| 153 |
+
if return_detected_types:
|
| 154 |
+
return PresidioPIIGuardrailResponse(
|
| 155 |
+
contains_pii=bool(detected_pii),
|
| 156 |
+
detected_pii_types=detected_pii,
|
| 157 |
+
explanation="\n".join(explanation_parts),
|
| 158 |
+
anonymized_text=anonymized_text
|
| 159 |
+
)
|
| 160 |
+
else:
|
| 161 |
+
return PresidioPIIGuardrailSimpleResponse(
|
| 162 |
+
contains_pii=bool(detected_pii),
|
| 163 |
+
explanation="\n".join(explanation_parts),
|
| 164 |
+
anonymized_text=anonymized_text
|
| 165 |
+
)
|
| 166 |
+
|
| 167 |
+
@weave.op()
|
| 168 |
+
def predict(self, prompt: str, return_detected_types: bool = True, **kwargs) -> PresidioPIIGuardrailResponse | PresidioPIIGuardrailSimpleResponse:
|
| 169 |
+
return self.guard(prompt, return_detected_types=return_detected_types, **kwargs)
|
guardrails_genie/guardrails/pii/regex_pii_guardrail.py
CHANGED
|
@@ -10,7 +10,12 @@ from ..base import Guardrail
|
|
| 10 |
class RegexPIIGuardrailResponse(BaseModel):
|
| 11 |
contains_pii: bool
|
| 12 |
detected_pii_types: Dict[str, list[str]]
|
| 13 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
explanation: str
|
| 15 |
anonymized_text: Optional[str] = None
|
| 16 |
|
|
@@ -51,15 +56,16 @@ class RegexPIIGuardrail(Guardrail):
|
|
| 51 |
)
|
| 52 |
|
| 53 |
@weave.op()
|
| 54 |
-
def guard(self, prompt: str, **kwargs) -> RegexPIIGuardrailResponse:
|
| 55 |
"""
|
| 56 |
Check if the input prompt contains any PII based on the regex patterns.
|
| 57 |
|
| 58 |
Args:
|
| 59 |
prompt: Input text to check for PII
|
|
|
|
| 60 |
|
| 61 |
Returns:
|
| 62 |
-
RegexPIIGuardrailResponse containing PII detection results
|
| 63 |
"""
|
| 64 |
result = self.regex_model.check(prompt)
|
| 65 |
|
|
@@ -85,11 +91,21 @@ class RegexPIIGuardrail(Guardrail):
|
|
| 85 |
for match in matches:
|
| 86 |
replacement = f"[{pii_type.upper()}]"
|
| 87 |
anonymized_text = anonymized_text.replace(match, replacement)
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
class RegexPIIGuardrailResponse(BaseModel):
|
| 11 |
contains_pii: bool
|
| 12 |
detected_pii_types: Dict[str, list[str]]
|
| 13 |
+
explanation: str
|
| 14 |
+
anonymized_text: Optional[str] = None
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class RegexPIIGuardrailSimpleResponse(BaseModel):
|
| 18 |
+
contains_pii: bool
|
| 19 |
explanation: str
|
| 20 |
anonymized_text: Optional[str] = None
|
| 21 |
|
|
|
|
| 56 |
)
|
| 57 |
|
| 58 |
@weave.op()
|
| 59 |
+
def guard(self, prompt: str, return_detected_types: bool = True, **kwargs) -> RegexPIIGuardrailResponse | RegexPIIGuardrailSimpleResponse:
|
| 60 |
"""
|
| 61 |
Check if the input prompt contains any PII based on the regex patterns.
|
| 62 |
|
| 63 |
Args:
|
| 64 |
prompt: Input text to check for PII
|
| 65 |
+
return_detected_types: If True, returns detailed PII type information
|
| 66 |
|
| 67 |
Returns:
|
| 68 |
+
RegexPIIGuardrailResponse or RegexPIIGuardrailSimpleResponse containing PII detection results
|
| 69 |
"""
|
| 70 |
result = self.regex_model.check(prompt)
|
| 71 |
|
|
|
|
| 91 |
for match in matches:
|
| 92 |
replacement = f"[{pii_type.upper()}]"
|
| 93 |
anonymized_text = anonymized_text.replace(match, replacement)
|
| 94 |
+
|
| 95 |
+
if return_detected_types:
|
| 96 |
+
return RegexPIIGuardrailResponse(
|
| 97 |
+
contains_pii=not result.passed,
|
| 98 |
+
detected_pii_types=result.matched_patterns,
|
| 99 |
+
explanation="\n".join(explanation_parts),
|
| 100 |
+
anonymized_text=anonymized_text
|
| 101 |
+
)
|
| 102 |
+
else:
|
| 103 |
+
return RegexPIIGuardrailSimpleResponse(
|
| 104 |
+
contains_pii=not result.passed,
|
| 105 |
+
explanation="\n".join(explanation_parts),
|
| 106 |
+
anonymized_text=anonymized_text
|
| 107 |
+
)
|
| 108 |
+
|
| 109 |
+
@weave.op()
|
| 110 |
+
def predict(self, prompt: str, return_detected_types: bool = True, **kwargs) -> RegexPIIGuardrailResponse | RegexPIIGuardrailSimpleResponse:
|
| 111 |
+
return self.guard(prompt, return_detected_types=return_detected_types, **kwargs)
|
guardrails_genie/guardrails/pii/run_transformers.py
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from guardrails_genie.guardrails.pii.transformers_pipeline_guardrail import TransformersPipelinePIIGuardrail
|
| 2 |
+
import weave
|
| 3 |
+
|
| 4 |
+
def run_transformers_pipeline():
|
| 5 |
+
weave.init("guardrails-genie-pii-transformers-pipeline-model")
|
| 6 |
+
|
| 7 |
+
# Create the guardrail with default entities and anonymization enabled
|
| 8 |
+
pii_guardrail = TransformersPipelinePIIGuardrail(
|
| 9 |
+
selected_entities=["GIVENNAME", "SURNAME", "EMAIL", "TELEPHONENUM", "SOCIALNUM", "PHONE_NUMBER"],
|
| 10 |
+
should_anonymize=True,
|
| 11 |
+
model_name="lakshyakh93/deberta_finetuned_pii",
|
| 12 |
+
show_available_entities=True
|
| 13 |
+
)
|
| 14 |
+
|
| 15 |
+
# Check a prompt
|
| 16 |
+
prompt = "Please contact John Smith at [email protected] or call 123-456-7890. My SSN is 123-45-6789"
|
| 17 |
+
result = pii_guardrail.guard(prompt, aggregate_redaction=False)
|
| 18 |
+
print(result)
|
| 19 |
+
|
| 20 |
+
# Result will contain:
|
| 21 |
+
# - contains_pii: True
|
| 22 |
+
# - detected_pii_types: {
|
| 23 |
+
# "GIVENNAME": ["John"],
|
| 24 |
+
# "SURNAME": ["Smith"],
|
| 25 |
+
# "EMAIL": ["[email protected]"],
|
| 26 |
+
# "TELEPHONENUM": ["123-456-7890"],
|
| 27 |
+
# "SOCIALNUM": ["123-45-6789"]
|
| 28 |
+
# }
|
| 29 |
+
# - safe_to_process: False
|
| 30 |
+
# - explanation: Detailed explanation of findings
|
| 31 |
+
# - anonymized_text: "Please contact [redacted] [redacted] at [redacted] or call [redacted]. My SSN is [redacted]"
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
if __name__ == "__main__":
|
| 35 |
+
run_transformers_pipeline()
|
guardrails_genie/guardrails/pii/transformers_pipeline_guardrail.py
ADDED
|
@@ -0,0 +1,179 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import List, Dict, Optional, ClassVar
|
| 2 |
+
from transformers import pipeline, AutoConfig
|
| 3 |
+
import json
|
| 4 |
+
from pydantic import BaseModel
|
| 5 |
+
from ..base import Guardrail
|
| 6 |
+
import weave
|
| 7 |
+
|
| 8 |
+
class TransformersPipelinePIIGuardrailResponse(BaseModel):
|
| 9 |
+
contains_pii: bool
|
| 10 |
+
detected_pii_types: Dict[str, List[str]]
|
| 11 |
+
explanation: str
|
| 12 |
+
anonymized_text: Optional[str] = None
|
| 13 |
+
|
| 14 |
+
class TransformersPipelinePIIGuardrailSimpleResponse(BaseModel):
|
| 15 |
+
contains_pii: bool
|
| 16 |
+
explanation: str
|
| 17 |
+
anonymized_text: Optional[str] = None
|
| 18 |
+
|
| 19 |
+
class TransformersPipelinePIIGuardrail(Guardrail):
|
| 20 |
+
"""Generic guardrail for detecting PII using any token classification model."""
|
| 21 |
+
|
| 22 |
+
_pipeline: Optional[object] = None
|
| 23 |
+
selected_entities: List[str]
|
| 24 |
+
should_anonymize: bool
|
| 25 |
+
available_entities: List[str]
|
| 26 |
+
|
| 27 |
+
def __init__(
|
| 28 |
+
self,
|
| 29 |
+
model_name: str = "iiiorg/piiranha-v1-detect-personal-information",
|
| 30 |
+
selected_entities: Optional[List[str]] = None,
|
| 31 |
+
should_anonymize: bool = False,
|
| 32 |
+
show_available_entities: bool = True,
|
| 33 |
+
):
|
| 34 |
+
# Load model config and extract available entities
|
| 35 |
+
config = AutoConfig.from_pretrained(model_name)
|
| 36 |
+
entities = self._extract_entities_from_config(config)
|
| 37 |
+
|
| 38 |
+
if show_available_entities:
|
| 39 |
+
self._print_available_entities(entities)
|
| 40 |
+
|
| 41 |
+
# Initialize default values if needed
|
| 42 |
+
if selected_entities is None:
|
| 43 |
+
selected_entities = entities # Use all available entities by default
|
| 44 |
+
|
| 45 |
+
# Filter out invalid entities and warn user
|
| 46 |
+
invalid_entities = [e for e in selected_entities if e not in entities]
|
| 47 |
+
valid_entities = [e for e in selected_entities if e in entities]
|
| 48 |
+
|
| 49 |
+
if invalid_entities:
|
| 50 |
+
print(f"\nWarning: The following entities are not available and will be ignored: {invalid_entities}")
|
| 51 |
+
print(f"Continuing with valid entities: {valid_entities}")
|
| 52 |
+
selected_entities = valid_entities
|
| 53 |
+
|
| 54 |
+
# Call parent class constructor
|
| 55 |
+
super().__init__(
|
| 56 |
+
selected_entities=selected_entities,
|
| 57 |
+
should_anonymize=should_anonymize,
|
| 58 |
+
available_entities=entities
|
| 59 |
+
)
|
| 60 |
+
|
| 61 |
+
# Initialize pipeline
|
| 62 |
+
self._pipeline = pipeline(
|
| 63 |
+
task="token-classification",
|
| 64 |
+
model=model_name,
|
| 65 |
+
aggregation_strategy="simple" # Merge same entities
|
| 66 |
+
)
|
| 67 |
+
|
| 68 |
+
def _extract_entities_from_config(self, config) -> List[str]:
|
| 69 |
+
"""Extract unique entity types from the model config."""
|
| 70 |
+
# Get id2label mapping from config
|
| 71 |
+
id2label = config.id2label
|
| 72 |
+
|
| 73 |
+
# Extract unique entity types (removing B- and I- prefixes)
|
| 74 |
+
entities = set()
|
| 75 |
+
for label in id2label.values():
|
| 76 |
+
if label.startswith(('B-', 'I-')):
|
| 77 |
+
entities.add(label[2:]) # Remove prefix
|
| 78 |
+
elif label != 'O': # Skip the 'O' (Outside) label
|
| 79 |
+
entities.add(label)
|
| 80 |
+
|
| 81 |
+
return sorted(list(entities))
|
| 82 |
+
|
| 83 |
+
def _print_available_entities(self, entities: List[str]):
|
| 84 |
+
"""Print all available entity types that can be detected by the model."""
|
| 85 |
+
print("\nAvailable PII entity types:")
|
| 86 |
+
print("=" * 25)
|
| 87 |
+
for entity in entities:
|
| 88 |
+
print(f"- {entity}")
|
| 89 |
+
print("=" * 25 + "\n")
|
| 90 |
+
|
| 91 |
+
def print_available_entities(self):
|
| 92 |
+
"""Print all available entity types that can be detected by the model."""
|
| 93 |
+
self._print_available_entities(self.available_entities)
|
| 94 |
+
|
| 95 |
+
def _detect_pii(self, text: str) -> Dict[str, List[str]]:
|
| 96 |
+
"""Detect PII entities in the text using the pipeline."""
|
| 97 |
+
results = self._pipeline(text)
|
| 98 |
+
|
| 99 |
+
# Group findings by entity type
|
| 100 |
+
detected_pii = {}
|
| 101 |
+
for entity in results:
|
| 102 |
+
entity_type = entity['entity_group']
|
| 103 |
+
if entity_type in self.selected_entities:
|
| 104 |
+
if entity_type not in detected_pii:
|
| 105 |
+
detected_pii[entity_type] = []
|
| 106 |
+
detected_pii[entity_type].append(entity['word'])
|
| 107 |
+
|
| 108 |
+
return detected_pii
|
| 109 |
+
|
| 110 |
+
def _anonymize_text(self, text: str, aggregate_redaction: bool = True) -> str:
|
| 111 |
+
"""Anonymize detected PII in text using the pipeline."""
|
| 112 |
+
results = self._pipeline(text)
|
| 113 |
+
|
| 114 |
+
# Sort entities by start position in reverse order to avoid offset issues
|
| 115 |
+
entities = sorted(results, key=lambda x: x['start'], reverse=True)
|
| 116 |
+
|
| 117 |
+
# Create a mutable list of characters
|
| 118 |
+
chars = list(text)
|
| 119 |
+
|
| 120 |
+
# Apply redactions
|
| 121 |
+
for entity in entities:
|
| 122 |
+
if entity['entity_group'] in self.selected_entities:
|
| 123 |
+
start, end = entity['start'], entity['end']
|
| 124 |
+
replacement = ' [redacted] ' if aggregate_redaction else f" [{entity['entity_group']}] "
|
| 125 |
+
|
| 126 |
+
# Replace the entity with the redaction marker
|
| 127 |
+
chars[start:end] = replacement
|
| 128 |
+
|
| 129 |
+
# Join and clean up multiple spaces
|
| 130 |
+
result = ''.join(chars)
|
| 131 |
+
return ' '.join(result.split())
|
| 132 |
+
|
| 133 |
+
@weave.op()
|
| 134 |
+
def guard(self, prompt: str, return_detected_types: bool = True, aggregate_redaction: bool = True) -> TransformersPipelinePIIGuardrailResponse | TransformersPipelinePIIGuardrailSimpleResponse:
|
| 135 |
+
"""Check if the input prompt contains any PII using Piiranha.
|
| 136 |
+
|
| 137 |
+
Args:
|
| 138 |
+
prompt: The text to analyze
|
| 139 |
+
return_detected_types: If True, returns detailed PII type information
|
| 140 |
+
aggregate_redaction: If True, uses generic [redacted] instead of entity type
|
| 141 |
+
"""
|
| 142 |
+
# Detect PII
|
| 143 |
+
detected_pii = self._detect_pii(prompt)
|
| 144 |
+
|
| 145 |
+
# Create explanation
|
| 146 |
+
explanation_parts = []
|
| 147 |
+
if detected_pii:
|
| 148 |
+
explanation_parts.append("Found the following PII in the text:")
|
| 149 |
+
for pii_type, instances in detected_pii.items():
|
| 150 |
+
explanation_parts.append(f"- {pii_type}: {len(instances)} instance(s)")
|
| 151 |
+
else:
|
| 152 |
+
explanation_parts.append("No PII detected in the text.")
|
| 153 |
+
|
| 154 |
+
explanation_parts.append("\nChecked for these PII types:")
|
| 155 |
+
for entity in self.selected_entities:
|
| 156 |
+
explanation_parts.append(f"- {entity}")
|
| 157 |
+
|
| 158 |
+
# Anonymize if requested
|
| 159 |
+
anonymized_text = None
|
| 160 |
+
if self.should_anonymize and detected_pii:
|
| 161 |
+
anonymized_text = self._anonymize_text(prompt, aggregate_redaction)
|
| 162 |
+
|
| 163 |
+
if return_detected_types:
|
| 164 |
+
return TransformersPipelinePIIGuardrailResponse(
|
| 165 |
+
contains_pii=bool(detected_pii),
|
| 166 |
+
detected_pii_types=detected_pii,
|
| 167 |
+
explanation="\n".join(explanation_parts),
|
| 168 |
+
anonymized_text=anonymized_text
|
| 169 |
+
)
|
| 170 |
+
else:
|
| 171 |
+
return TransformersPipelinePIIGuardrailSimpleResponse(
|
| 172 |
+
contains_pii=bool(detected_pii),
|
| 173 |
+
explanation="\n".join(explanation_parts),
|
| 174 |
+
anonymized_text=anonymized_text
|
| 175 |
+
)
|
| 176 |
+
|
| 177 |
+
@weave.op()
|
| 178 |
+
def predict(self, prompt: str, return_detected_types: bool = True, aggregate_redaction: bool = True, **kwargs) -> TransformersPipelinePIIGuardrailResponse | TransformersPipelinePIIGuardrailSimpleResponse:
|
| 179 |
+
return self.guard(prompt, return_detected_types=return_detected_types, aggregate_redaction=aggregate_redaction, **kwargs)
|