address-normalizer 2.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- address_normalizer/__init__.py +30 -0
- address_normalizer/api.py +84 -0
- address_normalizer/cli.py +37 -0
- address_normalizer/data/model.json +1 -0
- address_normalizer/detection.py +511 -0
- address_normalizer/normalization.py +49 -0
- address_normalizer/parser.py +705 -0
- address_normalizer/py.typed +1 -0
- address_normalizer/tagger.py +145 -0
- address_normalizer/tokenizer.py +42 -0
- address_normalizer/types.py +232 -0
- address_normalizer-2.0.0.dist-info/METADATA +160 -0
- address_normalizer-2.0.0.dist-info/RECORD +17 -0
- address_normalizer-2.0.0.dist-info/WHEEL +5 -0
- address_normalizer-2.0.0.dist-info/entry_points.txt +2 -0
- address_normalizer-2.0.0.dist-info/licenses/LICENSE +675 -0
- address_normalizer-2.0.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,705 @@
|
|
|
1
|
+
"""Hybrid rule and compact-model parser for Russian address strings."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
import re
|
|
7
|
+
from typing import Callable, Iterable, Protocol, Sequence
|
|
8
|
+
|
|
9
|
+
from .normalization import normalize_name, normalize_number
|
|
10
|
+
from .tagger import CompactSequenceTagger
|
|
11
|
+
from .tokenizer import Token, tokenize
|
|
12
|
+
from .types import AddressPart, Alternative, ParsedAddress
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class SequenceTagger(Protocol):
|
|
16
|
+
def tag(self, tokens: Sequence[Token]) -> tuple[list[str], list[float]]: ...
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
_LETTER = r"A-Za-zА-Яа-яЁё"
|
|
20
|
+
_SIMPLE_NUMBER = rf"\d+[{_LETTER}]?"
|
|
21
|
+
_SLASH_NUMBER = rf"{_SIMPLE_NUMBER}(?:\s*/\s*{_SIMPLE_NUMBER})?"
|
|
22
|
+
_HOUSE_NUMBER = rf"{_SLASH_NUMBER}(?:\s*-\s*{_SIMPLE_NUMBER})?"
|
|
23
|
+
|
|
24
|
+
_POSTAL_RE = re.compile(r"(?<!\d)(?P<value>\d{6})(?!\d)")
|
|
25
|
+
_COUNTRY_RE = re.compile(
|
|
26
|
+
r"(?<!\w)(?:Российская\s+Федерация|Россия|РФ)(?!\w)",
|
|
27
|
+
re.IGNORECASE,
|
|
28
|
+
)
|
|
29
|
+
_EXPLICIT_NUMERIC = {
|
|
30
|
+
"house_num": re.compile(
|
|
31
|
+
rf"(?<!\w)(?:д(?:ом)?|вл(?:адение)?)\.?\s*(?:№\s*)?"
|
|
32
|
+
rf"(?P<value>{_HOUSE_NUMBER})(?!\w)",
|
|
33
|
+
re.IGNORECASE,
|
|
34
|
+
),
|
|
35
|
+
"corpus": re.compile(
|
|
36
|
+
rf"(?<!\w)(?:корп(?:ус)?|кор|к)\.?\s*(?:№\s*)?"
|
|
37
|
+
rf"(?P<value>{_SLASH_NUMBER})(?!\w)",
|
|
38
|
+
re.IGNORECASE,
|
|
39
|
+
),
|
|
40
|
+
"structure": re.compile(
|
|
41
|
+
rf"(?<!\w)(?:стр(?:оение)?|соор(?:ужение)?)\.?\s*(?:№\s*)?"
|
|
42
|
+
rf"(?P<value>{_SLASH_NUMBER})(?!\w)",
|
|
43
|
+
re.IGNORECASE,
|
|
44
|
+
),
|
|
45
|
+
"apartment": re.compile(
|
|
46
|
+
rf"(?<!\w)(?:кв(?:артира)?|комн(?:ата)?|оф(?:ис)?|"
|
|
47
|
+
rf"пом(?:ещение)?)\.?\s*(?:№\s*)?"
|
|
48
|
+
rf"(?P<value>{_SLASH_NUMBER})(?!\w)",
|
|
49
|
+
re.IGNORECASE,
|
|
50
|
+
),
|
|
51
|
+
}
|
|
52
|
+
_NUMERIC_TAIL_RE = re.compile(
|
|
53
|
+
rf"(?<![\w/])(?P<house>{_SIMPLE_NUMBER})\s*-\s*"
|
|
54
|
+
rf"(?P<apartment>{_SIMPLE_NUMBER})\s*[,.]?\s*$",
|
|
55
|
+
re.IGNORECASE,
|
|
56
|
+
)
|
|
57
|
+
_SPACE_NUMBER_TAIL_RE = re.compile(
|
|
58
|
+
rf"(?<![\w/])(?P<house>{_SIMPLE_NUMBER})\s+"
|
|
59
|
+
rf"(?P<apartment>{_SIMPLE_NUMBER})\s*[,.]?\s*$",
|
|
60
|
+
re.IGNORECASE,
|
|
61
|
+
)
|
|
62
|
+
_PLAIN_HOUSE_TAIL_RE = re.compile(
|
|
63
|
+
rf"(?<![\w/])(?P<value>{_SLASH_NUMBER})\s*[,.]?\s*$",
|
|
64
|
+
re.IGNORECASE,
|
|
65
|
+
)
|
|
66
|
+
|
|
67
|
+
_MARKER_RE = re.compile(
|
|
68
|
+
r"(?<!\w)(?P<marker>"
|
|
69
|
+
r"обл(?:асть)?|край|респ(?:ублика)?|а\.?\s*о\.?|"
|
|
70
|
+
r"р-?н|район|"
|
|
71
|
+
r"г(?:ород)?|"
|
|
72
|
+
r"пгт|пос(?:елок|ёлок)?|село|деревня|хутор|х|с|п|д|"
|
|
73
|
+
r"ул(?:ица)?|пр-?кт|просп(?:ект)?|пер(?:еулок)?|"
|
|
74
|
+
r"б-?р|бульвар|наб(?:ережная)?|ш(?:оссе)?|проезд|пр-?д|"
|
|
75
|
+
r"пл(?:ощадь)?|аллея|мкр(?:орайон)?"
|
|
76
|
+
r")\.?(?!\w)",
|
|
77
|
+
re.IGNORECASE,
|
|
78
|
+
)
|
|
79
|
+
|
|
80
|
+
_MARKER_INFO: dict[str, tuple[str, str]] = {
|
|
81
|
+
"обл": ("region", "обл"),
|
|
82
|
+
"область": ("region", "обл"),
|
|
83
|
+
"край": ("region", "край"),
|
|
84
|
+
"респ": ("region", "респ"),
|
|
85
|
+
"республика": ("region", "респ"),
|
|
86
|
+
"ао": ("region", "АО"),
|
|
87
|
+
"рн": ("district", "р-н"),
|
|
88
|
+
"район": ("district", "р-н"),
|
|
89
|
+
"г": ("city", "г"),
|
|
90
|
+
"город": ("city", "г"),
|
|
91
|
+
"пгт": ("settlement", "пгт"),
|
|
92
|
+
"пос": ("settlement", "п"),
|
|
93
|
+
"поселок": ("settlement", "п"),
|
|
94
|
+
"посёлок": ("settlement", "п"),
|
|
95
|
+
"село": ("settlement", "с"),
|
|
96
|
+
"деревня": ("settlement", "д"),
|
|
97
|
+
"хутор": ("settlement", "х"),
|
|
98
|
+
"х": ("settlement", "х"),
|
|
99
|
+
"с": ("settlement", "с"),
|
|
100
|
+
"п": ("settlement", "п"),
|
|
101
|
+
"д": ("settlement", "д"),
|
|
102
|
+
"ул": ("street", "ул"),
|
|
103
|
+
"улица": ("street", "ул"),
|
|
104
|
+
"пркт": ("street", "пр-кт"),
|
|
105
|
+
"просп": ("street", "пр-кт"),
|
|
106
|
+
"проспект": ("street", "пр-кт"),
|
|
107
|
+
"пер": ("street", "пер"),
|
|
108
|
+
"переулок": ("street", "пер"),
|
|
109
|
+
"бр": ("street", "б-р"),
|
|
110
|
+
"бульвар": ("street", "б-р"),
|
|
111
|
+
"наб": ("street", "наб"),
|
|
112
|
+
"набережная": ("street", "наб"),
|
|
113
|
+
"ш": ("street", "ш"),
|
|
114
|
+
"шоссе": ("street", "ш"),
|
|
115
|
+
"проезд": ("street", "пр-д"),
|
|
116
|
+
"прд": ("street", "пр-д"),
|
|
117
|
+
"пл": ("street", "пл"),
|
|
118
|
+
"площадь": ("street", "пл"),
|
|
119
|
+
"аллея": ("street", "аллея"),
|
|
120
|
+
"мкр": ("street", "мкр"),
|
|
121
|
+
"микрорайон": ("street", "мкр"),
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
_SUFFIX_MARKERS = {
|
|
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
|
+
_KNOWN_CITY_ALIASES = {
|
|
153
|
+
"мск": "Москва",
|
|
154
|
+
"москва": "Москва",
|
|
155
|
+
"спб": "Санкт-Петербург",
|
|
156
|
+
"питер": "Санкт-Петербург",
|
|
157
|
+
"санкт-петербург": "Санкт-Петербург",
|
|
158
|
+
"ростов-на-дону": "Ростов-на-Дону",
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
@dataclass(frozen=True, slots=True)
|
|
163
|
+
class _Marker:
|
|
164
|
+
kind: str
|
|
165
|
+
canonical_type: str
|
|
166
|
+
key: str
|
|
167
|
+
start: int
|
|
168
|
+
end: int
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def _marker_key(value: str) -> str:
|
|
172
|
+
return re.sub(r"[\s.\-]", "", value.casefold().replace("ё", "е"))
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def _trim_span(text: str, start: int, end: int) -> tuple[int, int]:
|
|
176
|
+
while start < end and (text[start].isspace() or text[start] in ",.;:"):
|
|
177
|
+
start += 1
|
|
178
|
+
while end > start and (text[end - 1].isspace() or text[end - 1] in ",.;:"):
|
|
179
|
+
end -= 1
|
|
180
|
+
return start, end
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def _overlaps(start: int, end: int, intervals: Iterable[tuple[int, int]]) -> bool:
|
|
184
|
+
return any(start < right and end > left for left, right in intervals)
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def _available_spans(
|
|
188
|
+
text: str,
|
|
189
|
+
start: int,
|
|
190
|
+
end: int,
|
|
191
|
+
intervals: Iterable[tuple[int, int]],
|
|
192
|
+
) -> list[tuple[int, int]]:
|
|
193
|
+
"""Return trimmed portions of a span not covered by consumed intervals."""
|
|
194
|
+
|
|
195
|
+
spans = [(start, end)]
|
|
196
|
+
for left, right in sorted(intervals):
|
|
197
|
+
next_spans: list[tuple[int, int]] = []
|
|
198
|
+
for span_start, span_end in spans:
|
|
199
|
+
if right <= span_start or left >= span_end:
|
|
200
|
+
next_spans.append((span_start, span_end))
|
|
201
|
+
continue
|
|
202
|
+
if span_start < left:
|
|
203
|
+
next_spans.append((span_start, left))
|
|
204
|
+
if right < span_end:
|
|
205
|
+
next_spans.append((right, span_end))
|
|
206
|
+
spans = next_spans
|
|
207
|
+
return [
|
|
208
|
+
trimmed
|
|
209
|
+
for span in spans
|
|
210
|
+
if (trimmed := _trim_span(text, *span))[0] < trimmed[1]
|
|
211
|
+
]
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def _part(
|
|
215
|
+
text: str,
|
|
216
|
+
start: int,
|
|
217
|
+
end: int,
|
|
218
|
+
*,
|
|
219
|
+
confidence: float,
|
|
220
|
+
source: str,
|
|
221
|
+
normalizer: Callable[[str], str] = normalize_name,
|
|
222
|
+
) -> AddressPart:
|
|
223
|
+
raw = text[start:end]
|
|
224
|
+
return AddressPart(
|
|
225
|
+
value=normalizer(raw),
|
|
226
|
+
raw=raw,
|
|
227
|
+
start=start,
|
|
228
|
+
end=end,
|
|
229
|
+
confidence=confidence,
|
|
230
|
+
source=source,
|
|
231
|
+
)
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
class AddressParser:
|
|
235
|
+
"""Parse addresses without consulting or bundling an address registry."""
|
|
236
|
+
|
|
237
|
+
def __init__(self, tagger: SequenceTagger | None = None) -> None:
|
|
238
|
+
self.tagger: SequenceTagger | None
|
|
239
|
+
if tagger is not None:
|
|
240
|
+
self.tagger = tagger
|
|
241
|
+
else:
|
|
242
|
+
try:
|
|
243
|
+
self.tagger = CompactSequenceTagger.from_package()
|
|
244
|
+
except (FileNotFoundError, ModuleNotFoundError):
|
|
245
|
+
self.tagger = None
|
|
246
|
+
|
|
247
|
+
def parse(self, text: str) -> ParsedAddress:
|
|
248
|
+
tokens = tokenize(text)
|
|
249
|
+
if not tokens:
|
|
250
|
+
return ParsedAddress(raw=text)
|
|
251
|
+
|
|
252
|
+
components: dict[str, AddressPart] = {}
|
|
253
|
+
consumed: list[tuple[int, int]] = []
|
|
254
|
+
warnings: list[str] = []
|
|
255
|
+
alternatives: list[Alternative] = []
|
|
256
|
+
|
|
257
|
+
postal = _POSTAL_RE.search(text)
|
|
258
|
+
if postal:
|
|
259
|
+
components["postal_code"] = _part(
|
|
260
|
+
text,
|
|
261
|
+
postal.start("value"),
|
|
262
|
+
postal.end("value"),
|
|
263
|
+
confidence=0.995,
|
|
264
|
+
source="rule",
|
|
265
|
+
normalizer=lambda value: value,
|
|
266
|
+
)
|
|
267
|
+
consumed.append(postal.span())
|
|
268
|
+
|
|
269
|
+
consumed.extend(match.span() for match in _COUNTRY_RE.finditer(text))
|
|
270
|
+
|
|
271
|
+
for name, pattern in _EXPLICIT_NUMERIC.items():
|
|
272
|
+
match = pattern.search(text)
|
|
273
|
+
if not match:
|
|
274
|
+
continue
|
|
275
|
+
components[name] = _part(
|
|
276
|
+
text,
|
|
277
|
+
match.start("value"),
|
|
278
|
+
match.end("value"),
|
|
279
|
+
confidence=0.995,
|
|
280
|
+
source="rule",
|
|
281
|
+
normalizer=normalize_number,
|
|
282
|
+
)
|
|
283
|
+
consumed.append(match.span())
|
|
284
|
+
|
|
285
|
+
explicit_house = components.get("house_num")
|
|
286
|
+
if explicit_house and "apartment" not in components:
|
|
287
|
+
split = re.fullmatch(
|
|
288
|
+
rf"(?P<house>{_SLASH_NUMBER})\s*-\s*"
|
|
289
|
+
rf"(?P<apartment>{_SIMPLE_NUMBER})",
|
|
290
|
+
explicit_house.raw,
|
|
291
|
+
re.IGNORECASE,
|
|
292
|
+
)
|
|
293
|
+
if split:
|
|
294
|
+
original_value = normalize_number(explicit_house.raw)
|
|
295
|
+
house_start = explicit_house.start + split.start("house")
|
|
296
|
+
house_end = explicit_house.start + split.end("house")
|
|
297
|
+
apartment_start = explicit_house.start + split.start("apartment")
|
|
298
|
+
apartment_end = explicit_house.start + split.end("apartment")
|
|
299
|
+
components["house_num"] = _part(
|
|
300
|
+
text,
|
|
301
|
+
house_start,
|
|
302
|
+
house_end,
|
|
303
|
+
confidence=0.91,
|
|
304
|
+
source="postprocessor",
|
|
305
|
+
normalizer=normalize_number,
|
|
306
|
+
)
|
|
307
|
+
components["apartment"] = _part(
|
|
308
|
+
text,
|
|
309
|
+
apartment_start,
|
|
310
|
+
apartment_end,
|
|
311
|
+
confidence=0.87,
|
|
312
|
+
source="postprocessor",
|
|
313
|
+
normalizer=normalize_number,
|
|
314
|
+
)
|
|
315
|
+
alternatives.append(
|
|
316
|
+
Alternative(
|
|
317
|
+
components={"house_num": original_value},
|
|
318
|
+
confidence=0.09,
|
|
319
|
+
reason=(
|
|
320
|
+
"A hyphenated numeric tail can also be a compound "
|
|
321
|
+
"house number."
|
|
322
|
+
),
|
|
323
|
+
)
|
|
324
|
+
)
|
|
325
|
+
warnings.append("ambiguous_numeric_tail")
|
|
326
|
+
|
|
327
|
+
if "house_num" not in components and "apartment" not in components:
|
|
328
|
+
numeric_tail = _NUMERIC_TAIL_RE.search(text) or _SPACE_NUMBER_TAIL_RE.search(
|
|
329
|
+
text
|
|
330
|
+
)
|
|
331
|
+
if numeric_tail:
|
|
332
|
+
components["house_num"] = _part(
|
|
333
|
+
text,
|
|
334
|
+
numeric_tail.start("house"),
|
|
335
|
+
numeric_tail.end("house"),
|
|
336
|
+
confidence=0.91,
|
|
337
|
+
source="postprocessor",
|
|
338
|
+
normalizer=normalize_number,
|
|
339
|
+
)
|
|
340
|
+
components["apartment"] = _part(
|
|
341
|
+
text,
|
|
342
|
+
numeric_tail.start("apartment"),
|
|
343
|
+
numeric_tail.end("apartment"),
|
|
344
|
+
confidence=0.87,
|
|
345
|
+
source="postprocessor",
|
|
346
|
+
normalizer=normalize_number,
|
|
347
|
+
)
|
|
348
|
+
consumed.append(numeric_tail.span())
|
|
349
|
+
if "-" in numeric_tail.group(0):
|
|
350
|
+
alternatives.append(
|
|
351
|
+
Alternative(
|
|
352
|
+
components={
|
|
353
|
+
"house_num": normalize_number(
|
|
354
|
+
numeric_tail.group(0).strip(" ,.")
|
|
355
|
+
)
|
|
356
|
+
},
|
|
357
|
+
confidence=0.09,
|
|
358
|
+
reason=(
|
|
359
|
+
"A hyphenated numeric tail can also be a compound "
|
|
360
|
+
"house number."
|
|
361
|
+
),
|
|
362
|
+
)
|
|
363
|
+
)
|
|
364
|
+
warnings.append("ambiguous_numeric_tail")
|
|
365
|
+
|
|
366
|
+
if "house_num" not in components and not any(
|
|
367
|
+
name in components for name in ("corpus", "structure", "apartment")
|
|
368
|
+
):
|
|
369
|
+
plain_tail = _PLAIN_HOUSE_TAIL_RE.search(text)
|
|
370
|
+
if plain_tail and not (
|
|
371
|
+
components.get("postal_code")
|
|
372
|
+
and plain_tail.span("value") == components["postal_code"].span
|
|
373
|
+
):
|
|
374
|
+
components["house_num"] = _part(
|
|
375
|
+
text,
|
|
376
|
+
plain_tail.start("value"),
|
|
377
|
+
plain_tail.end("value"),
|
|
378
|
+
confidence=0.9,
|
|
379
|
+
source="postprocessor",
|
|
380
|
+
normalizer=normalize_number,
|
|
381
|
+
)
|
|
382
|
+
consumed.append(plain_tail.span())
|
|
383
|
+
|
|
384
|
+
self._extract_residual_house(text, tokens, components, consumed)
|
|
385
|
+
markers = self._markers(text)
|
|
386
|
+
self._extract_known_initial_city(text, components, consumed)
|
|
387
|
+
self._extract_marked_names(text, markers, components, consumed)
|
|
388
|
+
self._extract_with_model(text, tokens, components, consumed)
|
|
389
|
+
self._extract_implicit_segments(text, components, consumed)
|
|
390
|
+
|
|
391
|
+
unparsed = self._unparsed(text, tokens, consumed)
|
|
392
|
+
if unparsed:
|
|
393
|
+
warnings.append("unparsed_text")
|
|
394
|
+
|
|
395
|
+
confidences = [
|
|
396
|
+
part.confidence
|
|
397
|
+
for name, part in components.items()
|
|
398
|
+
if name != "street_type"
|
|
399
|
+
]
|
|
400
|
+
overall = sum(confidences) / len(confidences) if confidences else 0.0
|
|
401
|
+
if unparsed:
|
|
402
|
+
overall *= 0.9
|
|
403
|
+
|
|
404
|
+
return ParsedAddress(
|
|
405
|
+
raw=text,
|
|
406
|
+
postal_code=components.get("postal_code"),
|
|
407
|
+
region=components.get("region"),
|
|
408
|
+
district=components.get("district"),
|
|
409
|
+
city=components.get("city"),
|
|
410
|
+
settlement=components.get("settlement"),
|
|
411
|
+
street=components.get("street"),
|
|
412
|
+
street_type=components.get("street_type"),
|
|
413
|
+
house_num=components.get("house_num"),
|
|
414
|
+
corpus=components.get("corpus"),
|
|
415
|
+
structure=components.get("structure"),
|
|
416
|
+
apartment=components.get("apartment"),
|
|
417
|
+
unparsed=tuple(unparsed),
|
|
418
|
+
warnings=tuple(dict.fromkeys(warnings)),
|
|
419
|
+
alternatives=tuple(alternatives),
|
|
420
|
+
confidence=overall,
|
|
421
|
+
)
|
|
422
|
+
|
|
423
|
+
def _markers(self, text: str) -> list[_Marker]:
|
|
424
|
+
markers: list[_Marker] = []
|
|
425
|
+
for match in _MARKER_RE.finditer(text):
|
|
426
|
+
key = _marker_key(match.group("marker"))
|
|
427
|
+
info = _MARKER_INFO.get(key)
|
|
428
|
+
if not info:
|
|
429
|
+
continue
|
|
430
|
+
markers.append(
|
|
431
|
+
_Marker(
|
|
432
|
+
kind=info[0],
|
|
433
|
+
canonical_type=info[1],
|
|
434
|
+
key=key,
|
|
435
|
+
start=match.start(),
|
|
436
|
+
end=match.end(),
|
|
437
|
+
)
|
|
438
|
+
)
|
|
439
|
+
return markers
|
|
440
|
+
|
|
441
|
+
def _extract_known_initial_city(
|
|
442
|
+
self,
|
|
443
|
+
text: str,
|
|
444
|
+
components: dict[str, AddressPart],
|
|
445
|
+
consumed: list[tuple[int, int]],
|
|
446
|
+
) -> None:
|
|
447
|
+
if "city" in components:
|
|
448
|
+
return
|
|
449
|
+
postal_code = components.get("postal_code")
|
|
450
|
+
start = postal_code.end if postal_code else 0
|
|
451
|
+
while start < len(text) and (text[start].isspace() or text[start] in ",.;"):
|
|
452
|
+
start += 1
|
|
453
|
+
match = re.match(r"[A-Za-zА-Яа-яЁё]+(?:-[A-Za-zА-Яа-яЁё]+)*", text[start:])
|
|
454
|
+
if not match:
|
|
455
|
+
return
|
|
456
|
+
raw = match.group(0)
|
|
457
|
+
canonical = _KNOWN_CITY_ALIASES.get(raw.casefold().replace("ё", "е"))
|
|
458
|
+
if not canonical:
|
|
459
|
+
return
|
|
460
|
+
end = start + len(raw)
|
|
461
|
+
components["city"] = AddressPart(
|
|
462
|
+
value=canonical,
|
|
463
|
+
raw=raw,
|
|
464
|
+
start=start,
|
|
465
|
+
end=end,
|
|
466
|
+
confidence=0.98,
|
|
467
|
+
source="rule",
|
|
468
|
+
)
|
|
469
|
+
consumed.append((start, end))
|
|
470
|
+
|
|
471
|
+
def _extract_marked_names(
|
|
472
|
+
self,
|
|
473
|
+
text: str,
|
|
474
|
+
markers: Sequence[_Marker],
|
|
475
|
+
components: dict[str, AddressPart],
|
|
476
|
+
consumed: list[tuple[int, int]],
|
|
477
|
+
) -> None:
|
|
478
|
+
for index, marker in enumerate(markers):
|
|
479
|
+
if marker.kind in components:
|
|
480
|
+
continue
|
|
481
|
+
if _overlaps(marker.start, marker.end, consumed):
|
|
482
|
+
continue
|
|
483
|
+
|
|
484
|
+
previous_boundary = 0
|
|
485
|
+
if index:
|
|
486
|
+
previous_boundary = markers[index - 1].end
|
|
487
|
+
comma = max(
|
|
488
|
+
text.rfind(",", previous_boundary, marker.start),
|
|
489
|
+
text.rfind(";", previous_boundary, marker.start),
|
|
490
|
+
)
|
|
491
|
+
before_start = comma + 1 if comma >= 0 else previous_boundary
|
|
492
|
+
before_start, before_end = _trim_span(text, before_start, marker.start)
|
|
493
|
+
|
|
494
|
+
next_boundary = len(text)
|
|
495
|
+
if index + 1 < len(markers):
|
|
496
|
+
next_boundary = markers[index + 1].start
|
|
497
|
+
comma_positions = [
|
|
498
|
+
position
|
|
499
|
+
for position in (
|
|
500
|
+
text.find(",", marker.end, next_boundary),
|
|
501
|
+
text.find(";", marker.end, next_boundary),
|
|
502
|
+
)
|
|
503
|
+
if position >= 0
|
|
504
|
+
]
|
|
505
|
+
if comma_positions:
|
|
506
|
+
next_boundary = min(next_boundary, *comma_positions)
|
|
507
|
+
after_start, after_end = _trim_span(text, marker.end, next_boundary)
|
|
508
|
+
|
|
509
|
+
prefer_before = marker.key in _SUFFIX_MARKERS
|
|
510
|
+
before_candidates = _available_spans(
|
|
511
|
+
text, before_start, before_end, consumed
|
|
512
|
+
)
|
|
513
|
+
after_candidates = _available_spans(text, after_start, after_end, consumed)
|
|
514
|
+
candidates = (
|
|
515
|
+
(*reversed(before_candidates), *after_candidates)
|
|
516
|
+
if prefer_before
|
|
517
|
+
else (*after_candidates, *reversed(before_candidates))
|
|
518
|
+
)
|
|
519
|
+
selected: tuple[int, int] | None = None
|
|
520
|
+
for start, end in candidates:
|
|
521
|
+
if start >= end:
|
|
522
|
+
continue
|
|
523
|
+
value = text[start:end]
|
|
524
|
+
if not re.search(rf"[{_LETTER}]", value):
|
|
525
|
+
continue
|
|
526
|
+
selected = start, end
|
|
527
|
+
break
|
|
528
|
+
if not selected:
|
|
529
|
+
continue
|
|
530
|
+
|
|
531
|
+
start, end = selected
|
|
532
|
+
components[marker.kind] = _part(
|
|
533
|
+
text,
|
|
534
|
+
start,
|
|
535
|
+
end,
|
|
536
|
+
confidence=0.96,
|
|
537
|
+
source="rule",
|
|
538
|
+
)
|
|
539
|
+
consumed.extend(((marker.start, marker.end), (start, end)))
|
|
540
|
+
if marker.kind == "street":
|
|
541
|
+
components["street_type"] = AddressPart(
|
|
542
|
+
value=marker.canonical_type,
|
|
543
|
+
raw=text[marker.start:marker.end],
|
|
544
|
+
start=marker.start,
|
|
545
|
+
end=marker.end,
|
|
546
|
+
confidence=0.995,
|
|
547
|
+
source="rule",
|
|
548
|
+
)
|
|
549
|
+
|
|
550
|
+
def _extract_residual_house(
|
|
551
|
+
self,
|
|
552
|
+
text: str,
|
|
553
|
+
tokens: Sequence[Token],
|
|
554
|
+
components: dict[str, AddressPart],
|
|
555
|
+
consumed: list[tuple[int, int]],
|
|
556
|
+
) -> None:
|
|
557
|
+
if "house_num" in components:
|
|
558
|
+
return
|
|
559
|
+
candidates = [
|
|
560
|
+
token
|
|
561
|
+
for token in tokens
|
|
562
|
+
if token.is_number
|
|
563
|
+
and len(token.text) < 6
|
|
564
|
+
and not _overlaps(token.start, token.end, consumed)
|
|
565
|
+
]
|
|
566
|
+
if not candidates:
|
|
567
|
+
return
|
|
568
|
+
# With explicit corpus/apartment markers, the remaining right-most number is
|
|
569
|
+
# normally the house. Without them, plain-tail extraction is more reliable.
|
|
570
|
+
if not any(name in components for name in ("corpus", "structure", "apartment")):
|
|
571
|
+
return
|
|
572
|
+
token = candidates[-1]
|
|
573
|
+
components["house_num"] = _part(
|
|
574
|
+
text,
|
|
575
|
+
token.start,
|
|
576
|
+
token.end,
|
|
577
|
+
confidence=0.86,
|
|
578
|
+
source="postprocessor",
|
|
579
|
+
normalizer=normalize_number,
|
|
580
|
+
)
|
|
581
|
+
consumed.append((token.start, token.end))
|
|
582
|
+
|
|
583
|
+
def _extract_with_model(
|
|
584
|
+
self,
|
|
585
|
+
text: str,
|
|
586
|
+
tokens: Sequence[Token],
|
|
587
|
+
components: dict[str, AddressPart],
|
|
588
|
+
consumed: list[tuple[int, int]],
|
|
589
|
+
) -> None:
|
|
590
|
+
if self.tagger is None:
|
|
591
|
+
return
|
|
592
|
+
residual = [
|
|
593
|
+
token
|
|
594
|
+
for token in tokens
|
|
595
|
+
if token.is_word and not _overlaps(token.start, token.end, consumed)
|
|
596
|
+
]
|
|
597
|
+
if not residual:
|
|
598
|
+
return
|
|
599
|
+
labels, confidences = self.tagger.tag(residual)
|
|
600
|
+
runs: list[tuple[str, int, int, list[float]]] = []
|
|
601
|
+
for token, label, confidence in zip(residual, labels, confidences):
|
|
602
|
+
if label == "O" or label.lower() in components:
|
|
603
|
+
continue
|
|
604
|
+
if runs and runs[-1][0] == label and token.start - runs[-1][2] <= 2:
|
|
605
|
+
previous = runs[-1]
|
|
606
|
+
runs[-1] = (
|
|
607
|
+
previous[0],
|
|
608
|
+
previous[1],
|
|
609
|
+
token.end,
|
|
610
|
+
[*previous[3], confidence],
|
|
611
|
+
)
|
|
612
|
+
else:
|
|
613
|
+
runs.append((label, token.start, token.end, [confidence]))
|
|
614
|
+
for label, start, end, scores in runs:
|
|
615
|
+
kind = label.lower()
|
|
616
|
+
if kind not in {"region", "district", "city", "settlement", "street"}:
|
|
617
|
+
continue
|
|
618
|
+
if kind in components or _overlaps(start, end, consumed):
|
|
619
|
+
continue
|
|
620
|
+
components[kind] = _part(
|
|
621
|
+
text,
|
|
622
|
+
start,
|
|
623
|
+
end,
|
|
624
|
+
confidence=min(0.92, sum(scores) / len(scores)),
|
|
625
|
+
source="model",
|
|
626
|
+
)
|
|
627
|
+
consumed.append((start, end))
|
|
628
|
+
|
|
629
|
+
def _extract_implicit_segments(
|
|
630
|
+
self,
|
|
631
|
+
text: str,
|
|
632
|
+
components: dict[str, AddressPart],
|
|
633
|
+
consumed: list[tuple[int, int]],
|
|
634
|
+
) -> None:
|
|
635
|
+
chunks: list[tuple[int, int]] = []
|
|
636
|
+
for available_start, available_end in _available_spans(
|
|
637
|
+
text, 0, len(text), consumed
|
|
638
|
+
):
|
|
639
|
+
for match in re.finditer(
|
|
640
|
+
rf"[{_LETTER}](?:[{_LETTER}\d]|[\s\-](?=[{_LETTER}\d]))*",
|
|
641
|
+
text[available_start:available_end],
|
|
642
|
+
):
|
|
643
|
+
start = available_start + match.start()
|
|
644
|
+
end = available_start + match.end()
|
|
645
|
+
start, end = _trim_span(text, start, end)
|
|
646
|
+
if start < end and re.search(rf"[{_LETTER}]", text[start:end]):
|
|
647
|
+
chunks.append((start, end))
|
|
648
|
+
|
|
649
|
+
if "street" not in components and chunks and "house_num" in components:
|
|
650
|
+
start, end = chunks[-1]
|
|
651
|
+
components["street"] = _part(
|
|
652
|
+
text,
|
|
653
|
+
start,
|
|
654
|
+
end,
|
|
655
|
+
confidence=0.82,
|
|
656
|
+
source="postprocessor",
|
|
657
|
+
)
|
|
658
|
+
consumed.append((start, end))
|
|
659
|
+
|
|
660
|
+
remaining = [
|
|
661
|
+
span for span in chunks if not _overlaps(span[0], span[1], consumed)
|
|
662
|
+
]
|
|
663
|
+
if "city" not in components and len(remaining) >= 2:
|
|
664
|
+
start, end = remaining[0]
|
|
665
|
+
components["city"] = _part(
|
|
666
|
+
text,
|
|
667
|
+
start,
|
|
668
|
+
end,
|
|
669
|
+
confidence=0.72,
|
|
670
|
+
source="postprocessor",
|
|
671
|
+
)
|
|
672
|
+
consumed.append((start, end))
|
|
673
|
+
|
|
674
|
+
def _unparsed(
|
|
675
|
+
self,
|
|
676
|
+
text: str,
|
|
677
|
+
tokens: Sequence[Token],
|
|
678
|
+
consumed: Sequence[tuple[int, int]],
|
|
679
|
+
) -> list[AddressPart]:
|
|
680
|
+
residual = [
|
|
681
|
+
token
|
|
682
|
+
for token in tokens
|
|
683
|
+
if (token.is_word or token.is_number)
|
|
684
|
+
and not _overlaps(token.start, token.end, consumed)
|
|
685
|
+
]
|
|
686
|
+
if not residual:
|
|
687
|
+
return []
|
|
688
|
+
|
|
689
|
+
groups: list[list[Token]] = []
|
|
690
|
+
for token in residual:
|
|
691
|
+
if groups and token.start - groups[-1][-1].end <= 2:
|
|
692
|
+
groups[-1].append(token)
|
|
693
|
+
else:
|
|
694
|
+
groups.append([token])
|
|
695
|
+
return [
|
|
696
|
+
_part(
|
|
697
|
+
text,
|
|
698
|
+
group[0].start,
|
|
699
|
+
group[-1].end,
|
|
700
|
+
confidence=0.0,
|
|
701
|
+
source="unparsed",
|
|
702
|
+
normalizer=lambda value: value.strip(),
|
|
703
|
+
)
|
|
704
|
+
for group in groups
|
|
705
|
+
]
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|