|
| 1 | +"""Utility methods for working with PII data. |
| 2 | +
|
| 3 | +Python port of UiPath.SemanticProxy.Client.PiiUtilities (C#). |
| 4 | +""" |
| 5 | + |
| 6 | +import json |
| 7 | +import re |
| 8 | +from typing import Callable, Iterable |
| 9 | + |
| 10 | +from .semantic_proxy import PiiDetectionResponse, PiiEntity |
| 11 | + |
| 12 | + |
| 13 | +def rehydrate_from_pii_entities( |
| 14 | + masked_text: str, pii_entities: Iterable[PiiEntity] |
| 15 | +) -> str: |
| 16 | + """Rehydrate masked text by replacing PII placeholders with original values. |
| 17 | +
|
| 18 | + Placeholders (e.g. ``[Person-1]``) are matched case-insensitively and replaced |
| 19 | + with the corresponding original PII text. The function also replaces variants |
| 20 | + without the surrounding brackets (e.g. ``Person-1``) in case the LLM stripped |
| 21 | + them in its output. |
| 22 | +
|
| 23 | + Args: |
| 24 | + masked_text: The masked text with PII placeholders. |
| 25 | + pii_entities: The PII entities containing the original values. |
| 26 | +
|
| 27 | + Returns: |
| 28 | + The rehydrated text with original PII values. |
| 29 | + """ |
| 30 | + if not masked_text: |
| 31 | + return masked_text |
| 32 | + |
| 33 | + entities = [e for e in pii_entities if e.replacement_text] |
| 34 | + if not entities: |
| 35 | + return masked_text |
| 36 | + |
| 37 | + # Sort by replacement text length descending to avoid substring collisions |
| 38 | + # (e.g. "[Person-10]" must be replaced before "[Person-1]"). |
| 39 | + entities.sort(key=lambda e: len(e.replacement_text), reverse=True) |
| 40 | + |
| 41 | + rehydrated = masked_text |
| 42 | + for entity in entities: |
| 43 | + if not entity.replacement_text or not entity.pii_text: |
| 44 | + continue |
| 45 | + escaped_pii = _add_escape_characters(entity.pii_text) |
| 46 | + # Replace the full placeholder (with brackets) case-insensitively. |
| 47 | + # ``_literal_replacer`` bypasses regex backreference interpretation in the |
| 48 | + # replacement string. |
| 49 | + rehydrated = re.sub( |
| 50 | + re.escape(entity.replacement_text), |
| 51 | + _literal_replacer(escaped_pii), |
| 52 | + rehydrated, |
| 53 | + flags=re.IGNORECASE, |
| 54 | + ) |
| 55 | + # Also replace the content without brackets (in case the LLM dropped them). |
| 56 | + if entity.replacement_text.startswith("[") and entity.replacement_text.endswith( |
| 57 | + "]" |
| 58 | + ): |
| 59 | + no_brackets = entity.replacement_text[1:-1] |
| 60 | + rehydrated = re.sub( |
| 61 | + re.escape(no_brackets), |
| 62 | + _literal_replacer(escaped_pii), |
| 63 | + rehydrated, |
| 64 | + flags=re.IGNORECASE, |
| 65 | + ) |
| 66 | + |
| 67 | + return rehydrated |
| 68 | + |
| 69 | + |
| 70 | +def _literal_replacer(replacement: str) -> Callable[[re.Match[str]], str]: |
| 71 | + """Return a replacement function that ignores regex backreference syntax.""" |
| 72 | + |
| 73 | + def replace(_match: re.Match[str]) -> str: |
| 74 | + return replacement |
| 75 | + |
| 76 | + return replace |
| 77 | + |
| 78 | + |
| 79 | +def rehydrate_from_pii_response( |
| 80 | + masked_text: str, response: PiiDetectionResponse |
| 81 | +) -> str: |
| 82 | + """Rehydrate masked text using all PII entities from a detection response. |
| 83 | +
|
| 84 | + Merges entities from both ``response.response`` (detected in documents/prompts) |
| 85 | + and ``response.files`` (detected in files), so placeholders originating from |
| 86 | + either source are rehydrated. |
| 87 | +
|
| 88 | + Args: |
| 89 | + masked_text: The masked text with PII placeholders. |
| 90 | + response: The PII detection response containing entities to rehydrate. |
| 91 | +
|
| 92 | + Returns: |
| 93 | + The rehydrated text with original PII values. |
| 94 | + """ |
| 95 | + entities: list[PiiEntity] = [] |
| 96 | + for doc in response.response: |
| 97 | + entities.extend(doc.pii_entities) |
| 98 | + for file in response.files: |
| 99 | + entities.extend(file.pii_entities) |
| 100 | + return rehydrate_from_pii_entities(masked_text, entities) |
| 101 | + |
| 102 | + |
| 103 | +def _add_escape_characters(text: str) -> str: |
| 104 | + """Escape special characters in text using JSON serialization. |
| 105 | +
|
| 106 | + Mirrors C# ``AddEscapeCharacters`` — serializes as JSON then strips the |
| 107 | + surrounding quotes to get the escaped content. |
| 108 | + """ |
| 109 | + if not text: |
| 110 | + return "" |
| 111 | + try: |
| 112 | + serialized = json.dumps(text, ensure_ascii=False) |
| 113 | + return serialized[1:-1] |
| 114 | + except (TypeError, ValueError): |
| 115 | + return text |
0 commit comments