Spaces:
Runtime error
Runtime error
File size: 12,213 Bytes
829724b |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 |
import re
from presidio_analyzer import AnalyzerEngine, PatternRecognizer, Pattern
from presidio_anonymizer import AnonymizerEngine
from presidio_anonymizer.entities import OperatorConfig
from typing import List, Dict, Any
def clean_text(text: str) -> str:
"""
Remove HTML tags and normalize whitespace in the input text.
"""
text = re.sub(r"<[^>]+>", "", text)
text = re.sub(r"\s+", " ", text).strip()
return text
def setup_presidio_analyzer():
analyzer = AnalyzerEngine()
# Aadhar number pattern recognization
aadhar_pattern = Pattern(
name="AADHAR_PATTERN",
regex=r"\b\d{4}\s\d{4}\s\d{4}\b",
score=0.9
)
aadhar_recognizer = PatternRecognizer(
supported_entity="AADHAR_NUM",
patterns=[aadhar_pattern]
)
# credit card: 16 digits in groups of 4
credit_card_pattern = Pattern(
name="CREDIT_CARD_PATTERN",
regex=r"\b(?:\d{4}[-\s]?){3}\d{4}\b",
score=0.85
)
credit_card_recognizer = PatternRecognizer(
supported_entity="CREDIT_DEBIT_NO",
patterns=[credit_card_pattern]
)
# Expiry date: MM/YY or MM/YYYY
expiry_pattern = Pattern(
name="EXPIRY_PATTERN",
regex=r"\b(0[1-9]|1[0-2])[/\-](0?[0-9]|[0-9]{2}|[0-9]{4})\b",
score=0.8
)
expiry_recognizer = PatternRecognizer(
supported_entity="EXPIRY_NO",
patterns=[expiry_pattern]
)
# DOB: DD-MM-YYYY or DD/MM/YYYY
dob_pattern = Pattern(
name="DOB_PATTERN",
regex=r"\b(0[1-9]|[12][0-9]|3[01])[-/](0[1-9]|1[0-2])[-/](19|20)\d{2}\b",
score=0.9
)
dob_recognizer = PatternRecognizer(
supported_entity="DOB",
patterns=[dob_pattern]
)
# Phone number
phone_pattern = Pattern(
name="PHONE_PATTERN",
regex=r"(?:\+\d{1,3}[-.\s]?)?\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}",
score=0.8
)
phone_recognizer = PatternRecognizer(
supported_entity="PHONE_NUMBER",
patterns=[phone_pattern]
)
# Register recognizers
analyzer.registry.add_recognizer(credit_card_recognizer)
analyzer.registry.add_recognizer(aadhar_recognizer)
analyzer.registry.add_recognizer(expiry_recognizer)
analyzer.registry.add_recognizer(dob_recognizer)
analyzer.registry.add_recognizer(phone_recognizer)
return analyzer
def post_process_dates(text: str, entities: List[Dict]) -> List[Dict]:
"""Reclassify dates based on context keywords."""
for entity in entities:
if entity["entity_type"] in ["DOB", "EXPIRY_NO"]:
start, end = entity["start"], entity["end"]
context_start = max(0, start - 30)
context_end = min(len(text), end + 30)
snippet = text[context_start:context_end].lower()
# Keywords for DOB
dob_keywords = ["born", "birth", "dob", "date of birth"]
# Keywords for expiry
expiry_keywords = ["expiry", "exp", "expires", "valid until", "valid till"]
if any(keyword in snippet for keyword in dob_keywords):
entity["entity_type"] = "DOB"
elif any(keyword in snippet for keyword in expiry_keywords):
entity["entity_type"] = "EXPIRY_NO"
return entities
def resolve_overlapping_entities(entities: List[Dict]) -> List[Dict]:
"""Remove overlapping entities, keeping the one with higher confidence."""
if not entities:
return entities
# Sort by start position
entities.sort(key=lambda x: x["start"])
resolved_entities = []
for current in entities:
if not resolved_entities:
resolved_entities.append(current)
continue
last = resolved_entities[-1]
# Check for overlap
if current["start"] < last["end"]:
current_score = current.get("score", 0)
last_score = last.get("score", 0)
current_length = current["end"] - current["start"]
last_length = last["end"] - last["start"]
if (current_score > last_score or
(current_score == last_score and current_length > last_length)):
# Replace last with current
resolved_entities[-1] = current
else:
# No overlap, add current entity
resolved_entities.append(current)
return resolved_entities
def detect_cvv_from_context(text: str) -> List[Dict]:
"""
Detect CVV numbers based on context keywords and patterns
"""
cvv_entities = []
# CVV keywords that typically precede CVV numbers
cvv_keywords = [
r"cvv",
r"cvc",
r"security\s+code",
r"card\s+verification",
r"verification\s+code",
r"card\s+security\s+code",
r"three\s+digit\s+code",
r"four\s+digit\s+code"
]
# Search keyword patterns
for keyword in cvv_keywords:
# keyword followed by optional separators and 3-4 digits
pattern = rf"(?i){keyword}[\s:,\-]*(\d{{3,4}})"
for match in re.finditer(pattern, text):
cvv_digits = match.group(1)
digit_start = match.start(1)
digit_end = match.end(1)
#validation to ensure it's likely a CVV
if len(cvv_digits) in [3, 4]:
# Checking context to avoid false positives
context_start = max(0, match.start() - 20)
context_end = min(len(text), match.end() + 20)
context = text[context_start:context_end].lower()
# Keywords to avoid in cvv dectection
false_positive_keywords = [
"year", "date", "phone", "zip", "postal",
"age", "quantity", "amount", "price"
]
# Checking for a false positive
is_likely_cvv = not any(fp_keyword in context for fp_keyword in false_positive_keywords)
if is_likely_cvv:
cvv_entities.append({
"entity_type": "CVV_NO",
"start": digit_start,
"end": digit_end,
"entity": cvv_digits,
"score": 0.9,
"context": context.strip()
})
# Also looking for standalone 3-4 digit numbers near card-related keywords
card_keywords = [
r"card", r"credit", r"debit", r"payment", r"expire", r"expiry", r"valid"
]
# Find all 3-4 digi
digit_pattern = r"\b(\d{3,4})\b"
for digit_match in re.finditer(digit_pattern, text):
digit_text = digit_match.group(1)
digit_start = digit_match.start(1)
digit_end = digit_match.end(1)
# Checking if this digit sequence is near card-related keywords
context_start = max(0, digit_start - 50)
context_end = min(len(text), digit_end + 50)
context = text[context_start:context_end].lower()
# Checking if card-related keywords in context
has_card_context = any(re.search(rf"\b{keyword}\b", context) for keyword in card_keywords)
# Checking for things to avoid card, price or date
likely_cvv_context = (
has_card_context and
not re.search(r"\d{4}[-/]\d{2}[-/]\d{2,4}", context) and
not re.search(r"\$\d+", context) and
not re.search(r"\d{4}\s*\d{4}\s*\d{4}\s*\d{4}", context) and
len(digit_text) in [3, 4]
)
if likely_cvv_context:
# To avoid duplicates
is_duplicate = any(
existing["start"] == digit_start and existing["end"] == digit_end
for existing in cvv_entities
)
if not is_duplicate:
cvv_entities.append({
"entity_type": "CVV_NO",
"start": digit_start,
"end": digit_end,
"entity": digit_text,
"score": 0.7,
"context": context.strip()
})
return cvv_entities
def mask_pii(text: str) -> Dict[str, Any]:
"""
Mask personally identifiable information in the given text.
"""
analyzer = setup_presidio_analyzer()
anonymizer = AnonymizerEngine()
# Clean the input text
cleaned_text = clean_text(text)
# Detect PII on cleaned text
analyzer_results = analyzer.analyze(
text=cleaned_text,
entities=[
"PERSON", "EMAIL_ADDRESS", "PHONE_NUMBER",
"DOB", "AADHAR_NUM", "CREDIT_DEBIT_NO",
"EXPIRY_NO"
],
language="en"
)
# Map entity types to consistent naming
entity_mapping = {
"PERSON": "full_name",
"EMAIL_ADDRESS": "email",
"PHONE_NUMBER": "phone_number",
"DOB": "dob",
"AADHAR_NUM": "aadhar_num",
"CREDIT_DEBIT_NO": "credit_debit_no",
"CVV_NO": "cvv_no",
"EXPIRY_NO": "expiry_no",
}
# Convert analyzer results to our format
entities = []
for result in analyzer_results:
entity_type = result.entity_type
start, end = result.start, result.end
entity_text = cleaned_text[start:end]
score = result.score
entities.append({
"entity_type": entity_type,
"start": start,
"end": end,
"entity": entity_text,
"score": score
})
# context-based CVV detection
cvv_entities = detect_cvv_from_context(cleaned_text)
entities.extend(cvv_entities)
# Post-process dates based on context
entities = post_process_dates(cleaned_text, entities)
# Resolving overlapping entities
entities = resolve_overlapping_entities(entities)
# final masked entities list
masked_entities = []
for entity in entities:
classification = entity_mapping.get(entity["entity_type"], entity["entity_type"].lower())
masked_entities.append({
"position": [entity["start"], entity["end"]],
"classification": classification,
"entity": entity["entity"],
})
# Sort entities by position
masked_entities.sort(key=lambda x: x["position"][0])
# Recreate analyzer results for anonymization with resolved positions
final_analyzer_results = []
for entity in entities:
from presidio_analyzer import RecognizerResult
result = RecognizerResult(
entity_type=entity["entity_type"],
start=entity["start"],
end=entity["end"],
score=entity.get("score", 0.9)
)
final_analyzer_results.append(result)
# Anonymize the cleaned text
anonymized = anonymizer.anonymize(
text=cleaned_text,
analyzer_results=final_analyzer_results,
operators={
"PERSON": OperatorConfig("replace", {"new_value": "[full_name]"}),
"EMAIL_ADDRESS": OperatorConfig("replace", {"new_value": "[email]"}),
"PHONE_NUMBER": OperatorConfig("replace", {"new_value": "[phone_number]"}),
"DOB": OperatorConfig("replace", {"new_value": "[dob]"}),
"AADHAR_NUM": OperatorConfig("replace", {"new_value": "[aadhar_num]"}),
"CREDIT_DEBIT_NO": OperatorConfig("replace", {"new_value": "[credit_debit_no]"}),
"CVV_NO": OperatorConfig("replace", {"new_value": "[cvv_no]"}),
"EXPIRY_NO": OperatorConfig("replace", {"new_value": "[expiry_no]"}),
}
)
return {
"masked_email": anonymized.text,
"list_of_masked_entities": masked_entities,
} |