Spaces:
Sleeping
Sleeping
File size: 7,690 Bytes
dbaa71b |
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 |
import logging
from typing import Any, Dict, List, Optional
from presidio_analyzer import AnalyzerEngine, EntityRecognizer
from presidio_anonymizer import AnonymizerEngine
from presidio_analyzer.nlp_engine import NlpEngineProvider
from presidio_anonymizer.entities.engine import OperatorConfig
from pydantic import BaseModel, Field, PrivateAttr
from obsei.analyzer.base_analyzer import (
BaseAnalyzer,
BaseAnalyzerConfig,
)
from obsei.payload import TextPayload
logger = logging.getLogger(__name__)
class PresidioModelConfig(BaseModel):
lang_code: Optional[str] = Field("en")
model_name: Optional[str] = Field("en_core_web_lg")
class PresidioEngineConfig(BaseModel):
nlp_engine_name: Optional[str] = Field("spacy")
models: Optional[List[PresidioModelConfig]] = None
def __init__(self, **data: Any):
super().__init__(**data)
if not self.models or len(self.models) == 0:
self.models = [PresidioModelConfig()]
class PresidioAnonymizerConfig(OperatorConfig, BaseModel): # type: ignore
def __init__(self, anonymizer_name: str, params: Optional[Dict[str, Any]] = None):
super().__init__(anonymizer_name=anonymizer_name, params=params)
class Config:
arbitrary_types_allowed = True
class PresidioPIIAnalyzerConfig(BaseAnalyzerConfig):
TYPE: str = "PresidioPII"
# To find more details refer https://microsoft.github.io/presidio/anonymizer/
anonymizers_config: Optional[Dict[str, PresidioAnonymizerConfig]] = None
# To see list of supported entities refer https://microsoft.github.io/presidio/supported_entities/
# By default it will search for all the supported entities
entities: Optional[List[str]] = None
analyze_only: Optional[bool] = False
replace_original_text: Optional[bool] = True
# Whether the analysis decision process steps returned in the response
return_decision_process: Optional[bool] = False
class PresidioPIIAnalyzer(BaseAnalyzer):
_analyzer: AnalyzerEngine = PrivateAttr()
_anonymizer: AnonymizerEngine = PrivateAttr()
TYPE: str = "PresidioPII"
engine_config: Optional[PresidioEngineConfig] = None
# To see list of supported entities refer https://microsoft.github.io/presidio/supported_entities/
# To add customer recognizers refer https://microsoft.github.io/presidio/analyzer/adding_recognizers/
entity_recognizers: Optional[List[EntityRecognizer]] = None
# To find more details refer https://microsoft.github.io/presidio/anonymizer/
anonymizers_config: Optional[Dict[str, OperatorConfig]] = None
def __init__(self, **data: Any):
super().__init__(**data)
if not self.engine_config:
self.engine_config = PresidioEngineConfig()
if not self.engine_config.models or len(self.engine_config.models) == 0:
self.engine_config.models = [PresidioModelConfig()]
# If spacy engine then load Spacy models and select languages
languages = []
for model_config in self.engine_config.models:
languages.append(model_config.lang_code)
# Check SpacyNlpEngine.engine_name
if (
self.engine_config.nlp_engine_name == "spacy"
and model_config.model_name is not None
):
try:
spacy_model = __import__(model_config.model_name)
spacy_model.load()
logger.info(
f"Spacy model {model_config.model_name} is already downloaded"
)
except:
logger.warning(
f"Spacy model {model_config.model_name} is not downloaded"
)
logger.warning(
f"Downloading spacy model {model_config.model_name}, it might take some time"
)
from spacy.cli import download # type: ignore
download(model_config.model_name)
# Create NLP engine based on configuration
provider = NlpEngineProvider(nlp_configuration=self.engine_config.dict())
nlp_engine = provider.create_engine()
# Pass the created NLP engine and supported_languages to the AnalyzerEngine
self._analyzer = AnalyzerEngine(
nlp_engine=nlp_engine, supported_languages=languages
)
# self._analyzer.registry.load_predefined_recognizers()
if self.entity_recognizers:
for entity_recognizer in self.entity_recognizers:
self._analyzer.registry.add_recognizer(entity_recognizer)
# Initialize the anonymizer with logger
self._anonymizer = AnonymizerEngine()
def analyze_input( # type: ignore[override]
self,
source_response_list: List[TextPayload],
analyzer_config: Optional[PresidioPIIAnalyzerConfig] = None,
language: Optional[str] = "en",
**kwargs: Any,
) -> List[TextPayload]:
if analyzer_config is None:
raise ValueError("analyzer_config can't be None")
analyzer_output: List[TextPayload] = []
for batch_responses in self.batchify(source_response_list, self.batch_size):
for source_response in batch_responses:
analyzer_result = self._analyzer.analyze(
text=source_response.processed_text,
entities=analyzer_config.entities,
return_decision_process=analyzer_config.return_decision_process,
language=language,
)
anonymized_result = None
if not analyzer_config.analyze_only:
anonymizers_config = (
analyzer_config.anonymizers_config or self.anonymizers_config
)
if (
source_response.processed_text is not None
and len(source_response.processed_text) > 0
):
anonymized_result = self._anonymizer.anonymize(
text=source_response.processed_text,
operators=anonymizers_config,
analyzer_results=analyzer_result,
)
if (
analyzer_config.replace_original_text
and anonymized_result is not None
):
text = anonymized_result.text
else:
text = source_response.processed_text
segmented_data = {
"pii_data": {
"analyzer_result": [vars(result) for result in analyzer_result],
"anonymized_result": None
if not anonymized_result
else [vars(item) for item in anonymized_result.items],
"anonymized_text": None
if not anonymized_result
else anonymized_result.text,
}
}
if source_response.segmented_data:
segmented_data = {
**segmented_data,
**source_response.segmented_data,
}
analyzer_output.append(
TextPayload(
processed_text=text,
meta=source_response.meta,
segmented_data=segmented_data,
source_name=source_response.source_name,
)
)
return analyzer_output
|