Repository navigation
Expand file tree
/
Copy pathservice.py
More file actions
252 lines (196 loc) · 8.43 KB
/
Copy pathservice.py
File metadata and controls
252 lines (196 loc) · 8.43 KB
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
"""The NLP work itself.
Nothing in this module imports Flask, boto3 or ``os.environ``. It is handed a
callable that returns a loaded spaCy ``Language`` and it does linguistics with it,
which is what makes it testable against ``spacy.blank("en")`` in milliseconds and
with no AWS credentials in the environment.
"""
from __future__ import annotations
import logging
import threading
import time
from collections import Counter
from collections.abc import Callable, Iterable, Sequence
from dataclasses import asdict, dataclass, field
from nlp_lambda.errors import ValidationError
logger = logging.getLogger(__name__)
LOCATION_LABELS = ("GPE", "LOC")
@dataclass(frozen=True)
class Entity:
"""One named entity occurrence, with the offsets needed to highlight it."""
text: str
label: str
start_char: int
end_char: int
def as_dict(self) -> dict:
return asdict(self)
@dataclass(frozen=True)
class Analyzer:
"""A named way of reducing a spaCy ``Doc`` to JSON.
``requires`` lists components the analyzer cannot work without — a model that
lacks one is rejected with a clear message. ``keeps`` lists components that
are not the point of the analyzer but that the required ones depend on.
Everything else is disabled for the run, which is where most of the
per-request time goes: the dependency parser is the most expensive component
in a spaCy pipeline and an entity extractor has no use for it.
The split matters. ``doc.noun_chunks`` needs the parser *and* the POS tags the
tagger and attribute_ruler produce; run it with the parser alone and it
silently returns an empty list rather than raising. The ``en_core_web_*`` NER
component, by contrast, carries its own tok2vec, so ``entities`` needs nothing
upstream (verified against en_core_web_sm and en_core_web_md 3.8.0: identical
output with every other component disabled).
"""
name: str
run: Callable[[object], object]
requires: tuple[str, ...] = ()
description: str = ""
keeps: tuple[str, ...] = ()
_ANALYZERS: dict[str, Analyzer] = {}
def register_analyzer(analyzer: Analyzer) -> None:
"""Add or replace an analyzer. Keeps new outputs out of the HTTP layer."""
_ANALYZERS[analyzer.name] = analyzer
def available_analyzers() -> tuple[str, ...]:
return tuple(sorted(_ANALYZERS))
def describe_analyzer(name: str) -> str:
return _ANALYZERS[name].description
def _entities(doc) -> list[dict]:
return [
Entity(ent.text, ent.label_, ent.start_char, ent.end_char).as_dict() for ent in doc.ents
]
def _locations(doc) -> list[str]:
"""Location mentions, most frequent first.
The original implementation returned ``list(Counter(...).keys())`` under the
name ``locations_sorted_by_num_appearances``. ``Counter`` is a ``dict``, so
that is *insertion* order — the ranking the name promised never happened.
"""
names = [ent.text for ent in doc.ents if ent.label_ in LOCATION_LABELS]
return [name for name, _ in Counter(names).most_common()]
def _noun_chunks(doc) -> list[str]:
return [chunk.text for chunk in doc.noun_chunks]
register_analyzer(Analyzer("entities", _entities, ("ner",), "Every named entity with its offsets"))
register_analyzer(
Analyzer("locations", _locations, ("ner",), "GPE/LOC mentions, most frequent first")
)
register_analyzer(
Analyzer(
"noun_chunks",
_noun_chunks,
("parser",),
"Base noun phrases",
keeps=("tok2vec", "tagger", "attribute_ruler"),
)
)
@dataclass
class ServiceStats:
"""Counters a ``/health`` call can report without loading the model."""
model_loaded: bool = False
load_seconds: float | None = None
documents_processed: int = 0
extra: dict = field(default_factory=dict)
class NlpService:
"""Runs analyzers over text using a lazily loaded spaCy pipeline."""
def __init__(
self,
loader: Callable[[], object],
*,
max_text_chars: int = 100_000,
max_batch_size: int = 32,
) -> None:
self._loader = loader
self._nlp = None
# gunicorn runs this with several threads per worker; without the lock two
# requests racing a cold start would each spacy.load a full copy.
self._load_lock = threading.Lock()
self.max_text_chars = max_text_chars
self.max_batch_size = max_batch_size
self.stats = ServiceStats()
# -- lifecycle -------------------------------------------------------------
@property
def nlp(self):
"""The loaded pipeline. Loading happens on first use, never on import."""
if self._nlp is not None:
return self._nlp
with self._load_lock:
if self._nlp is None:
started = time.perf_counter()
nlp = self._loader()
elapsed = time.perf_counter() - started
self.stats.model_loaded = True
self.stats.load_seconds = elapsed
logger.info(
"pipeline_loaded name=%s seconds=%.3f components=%s",
getattr(nlp, "meta", {}).get("name", "unknown"),
elapsed,
",".join(nlp.pipe_names),
)
self._nlp = nlp
return self._nlp
@property
def is_loaded(self) -> bool:
return self._nlp is not None
def warm_up(self) -> dict:
"""Force the model load and report what it cost.
Called by the ``/warmup`` route and by a scheduled ping, so the first real
user request does not pay for the download.
"""
was_loaded = self.is_loaded
nlp = self.nlp
return {
"already_warm": was_loaded,
"pipeline": getattr(nlp, "meta", {}).get("name"),
"components": list(nlp.pipe_names),
"load_seconds": round(self.stats.load_seconds, 3),
}
# -- work ------------------------------------------------------------------
def _validate(self, texts: Sequence[str]) -> list[str]:
if not texts:
raise ValidationError("at least one text is required")
if len(texts) > self.max_batch_size:
raise ValidationError(
f"batch of {len(texts)} exceeds max_batch_size={self.max_batch_size}"
)
cleaned: list[str] = []
for index, text in enumerate(texts):
if not isinstance(text, str):
raise ValidationError(f"text at index {index} is not a string")
if len(text) > self.max_text_chars:
raise ValidationError(
f"text at index {index} is {len(text)} characters, "
f"over the {self.max_text_chars} limit"
)
cleaned.append(text)
return cleaned
def _disabled_for(self, analyzer: Analyzer) -> list[str]:
keep = set(analyzer.requires) | set(analyzer.keeps)
return [name for name in self.nlp.pipe_names if name not in keep]
def analyze(self, texts: Sequence[str], analyzer: str = "entities") -> list[object]:
"""Run one analyzer over a batch of texts and return one result per text."""
try:
chosen = _ANALYZERS[analyzer]
except KeyError as exc:
raise ValidationError(
f"unknown analyzer {analyzer!r}; available: {', '.join(available_analyzers())}"
) from exc
cleaned = self._validate(texts)
disable = self._disabled_for(chosen)
missing = [name for name in chosen.requires if name not in self.nlp.pipe_names]
if missing:
raise ValidationError(
f"analyzer {analyzer!r} needs pipeline component(s) "
f"{', '.join(missing)}, which this model does not have"
)
started = time.perf_counter()
docs: Iterable = self.nlp.pipe(cleaned, batch_size=self.max_batch_size, disable=disable)
results = [chosen.run(doc) for doc in docs]
self.stats.documents_processed += len(cleaned)
logger.info(
"analyze analyzer=%s documents=%d chars=%d seconds=%.4f disabled=%s",
analyzer,
len(cleaned),
sum(len(t) for t in cleaned),
time.perf_counter() - started,
",".join(disable) or "-",
)
return results
def find_locations(self, text: str) -> list[str]:
"""Backwards-compatible shorthand for the original single-text endpoint."""
return self.analyze([text], analyzer="locations")[0]