|
53 | 53 | from presidio_anonymizer import AnonymizerEngine |
54 | 54 | from presidio_anonymizer.entities import OperatorConfig |
55 | 55 | from pydantic import BaseModel, model_validator |
| 56 | +from spacy.tokenizer import Tokenizer |
| 57 | +from spacy.tokens import Doc |
56 | 58 |
|
57 | 59 | # Languages served. Each needs its spaCy model installed in the image; the |
58 | 60 | # es/it/pl/fi predefined recognizers (ES_NIF, IT_FISCAL_CODE, PL_PESEL, ...) |
@@ -153,12 +155,61 @@ def _register_common_recognizers(analyzer: AnalyzerEngine) -> None: |
153 | 155 | analyzer.registry.add_recognizer(recognizer_cls()) |
154 | 156 |
|
155 | 157 |
|
| 158 | +# spaCy's tokenizer peels a whitespace-free run one prefix or suffix at a time and |
| 159 | +# searches the whole run again for each, so a long run such as minified JSON costs |
| 160 | +# time quadratic in its length (about 4.5s for a 100,000-character array of small |
| 161 | +# objects). That work holds the GIL throughout, so the worker misses uvicorn's 5s |
| 162 | +# health ping and is killed with every request it is serving. A run at least this |
| 163 | +# long is instead split in linear time into single symbols and words, keeping |
| 164 | +# word characters joined by `.`, `,` or `:` together as spaCy does (`1,2,3`, |
| 165 | +# `example.com`) so NER does not read each piece of a number as its own entity. |
| 166 | +# Shorter runs tokenize as before. |
| 167 | +TOKENIZER_RUN_CHARS = 100 |
| 168 | +_LONG_RUN = regex_module.compile(rf"(?<!\S)\S{{{TOKENIZER_RUN_CHARS},}}") |
| 169 | +_RUN_PIECE = regex_module.compile(r"\w+(?:[.,:]\w+)*|\W") |
| 170 | + |
| 171 | + |
| 172 | +class LongRunTokenizer: |
| 173 | + """spaCy tokenizer that splits runs of TOKENIZER_RUN_CHARS or more non-space |
| 174 | + characters in linear time and leaves the rest to spaCy's own tokenizer. The |
| 175 | + Doc's text is the input unchanged, because Presidio runs its pattern |
| 176 | + recognizers on `doc.text`.""" |
| 177 | + |
| 178 | + def __init__(self, tokenizer: Tokenizer) -> None: |
| 179 | + self.tokenizer = tokenizer |
| 180 | + |
| 181 | + def __call__(self, text: str) -> Doc: |
| 182 | + if not _LONG_RUN.search(text): |
| 183 | + return self.tokenizer(text) |
| 184 | + words: list[str] = [] |
| 185 | + spaces: list[bool] = [] |
| 186 | + start = 0 |
| 187 | + for run in _LONG_RUN.finditer(text): |
| 188 | + self._tokenize_into(text[start : run.start()], words, spaces) |
| 189 | + pieces = _RUN_PIECE.findall(run.group()) |
| 190 | + words.extend(pieces) |
| 191 | + spaces.extend([False] * len(pieces)) |
| 192 | + start = run.end() |
| 193 | + # spaCy attaches one following space to the token before it. |
| 194 | + if text.startswith(" ", start): |
| 195 | + spaces[-1] = True |
| 196 | + start += 1 |
| 197 | + self._tokenize_into(text[start:], words, spaces) |
| 198 | + return Doc(self.tokenizer.vocab, words=words, spaces=spaces) |
| 199 | + |
| 200 | + def _tokenize_into(self, text: str, words: list[str], spaces: list[bool]) -> None: |
| 201 | + for token in self.tokenizer(text): |
| 202 | + words.append(token.text) |
| 203 | + spaces.append(bool(token.whitespace_)) |
| 204 | + |
| 205 | + |
156 | 206 | def build_analyzer() -> AnalyzerEngine: |
157 | 207 | nlp_engine = NlpEngineProvider(nlp_configuration=NLP_CONFIGURATION).create_engine() |
158 | 208 | for nlp in getattr(nlp_engine, "nlp", {}).values(): |
159 | 209 | for pipe in NER_ONLY_DISABLE: |
160 | 210 | if pipe in nlp.pipe_names: |
161 | 211 | nlp.disable_pipe(pipe) |
| 212 | + nlp.tokenizer = LongRunTokenizer(nlp.tokenizer) |
162 | 213 | analyzer = AnalyzerEngine(nlp_engine=nlp_engine, supported_languages=SUPPORTED_LANGUAGES) |
163 | 214 | _register_common_recognizers(analyzer) |
164 | 215 | return analyzer |
|
0 commit comments