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.
@@ -0,0 +1,511 @@
1
+ """Conservative address-span detection for free-form messages."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ import re
7
+ from typing import Iterable
8
+
9
+ from .parser import AddressParser
10
+ from .types import DetectedAddress
11
+
12
+
13
+ _LETTER = r"A-Za-zА-Яа-яЁё"
14
+ _SIMPLE_NUMBER = rf"\d+[{_LETTER}]?"
15
+ _SLASH_NUMBER = rf"{_SIMPLE_NUMBER}(?:\s*/\s*{_SIMPLE_NUMBER})?"
16
+ _HOUSE_NUMBER = rf"{_SLASH_NUMBER}(?:\s*-\s*{_SIMPLE_NUMBER})?"
17
+
18
+ _CUE_RE = re.compile(
19
+ r"(?<![\w-])(?:по\s+адресу|"
20
+ r"адрес(?:а|у|ом|е)?(?:\s+доставки|\s+офиса|\s+встречи)?)"
21
+ r"(?!\w)\s*:?\s*",
22
+ re.IGNORECASE,
23
+ )
24
+ _NETWORK_PREFIX_RE = re.compile(
25
+ r"(?:ip|ipv4|ipv6)\s*[-:]?\s*$",
26
+ re.IGNORECASE,
27
+ )
28
+ _NON_NAME_AFTER_MARKER_RE = re.compile(
29
+ r"^\s*(?:в|во|на|по|для|из|к|с|со|от)\s+",
30
+ re.IGNORECASE,
31
+ )
32
+ _STREET_MARKER_RE = re.compile(
33
+ r"(?<!\w)(?:"
34
+ r"ул(?:ица|ице|ицу|ицы|ицей)?|"
35
+ r"пр-?кт|просп(?:ект|екта|екте|екту|ектом)?|"
36
+ r"пер(?:еулок|еулка|еулке|еулку|еулком)?|"
37
+ r"б-?р|бульвар|наб(?:ережная)?|ш(?:оссе)?|"
38
+ r"проезд|пр-?д|пл(?:ощадь)?|аллея|мкр(?:орайон)?"
39
+ r")\s*\.?(?!\w)",
40
+ re.IGNORECASE,
41
+ )
42
+ _ORDINAL_BEFORE_MARKER_RE = re.compile(
43
+ r"(?<!\w)\d+\s*-\s*(?:я|й|ая|ый|ой)\s*$",
44
+ re.IGNORECASE,
45
+ )
46
+ _HOUSE_RE = re.compile(
47
+ rf"(?<!\w)(?:д(?:ом)?|вл(?:адение)?)\s*\.?\s*(?:№\s*)?"
48
+ rf"(?P<value>{_HOUSE_NUMBER})(?!\w)",
49
+ re.IGNORECASE,
50
+ )
51
+ _UNIT_RE = re.compile(
52
+ rf"(?<!\w)(?:"
53
+ rf"корп(?:ус)?|кор|к|стр(?:оение)?|соор(?:ужение)?|"
54
+ rf"кв(?:артира)?|комн(?:ата)?|оф(?:ис)?|пом(?:ещение)?"
55
+ rf")\s*\.?\s*(?:№\s*)?(?P<value>{_SLASH_NUMBER})(?!\w)",
56
+ re.IGNORECASE,
57
+ )
58
+ _BARE_NUMBER_RE = re.compile(rf"(?<![\w/]){_HOUSE_NUMBER}(?!\w)", re.IGNORECASE)
59
+ _POSTAL_RE = re.compile(r"(?<!\d)\d{6}(?!\d)")
60
+ _LOCATION_MARKER_RE = re.compile(
61
+ r"(?<!\w)(?:г(?:ород)?|обл(?:асть)?|край|респ(?:ублика)?|"
62
+ r"р-?н|район|пгт|пос(?:елок|ёлок)?|село|деревня)\s*\.?(?!\w)",
63
+ re.IGNORECASE,
64
+ )
65
+ _COUNTRY_RE = re.compile(
66
+ r"(?<!\w)(?:Российская\s+Федерация|Россия|РФ)(?!\w)",
67
+ re.IGNORECASE,
68
+ )
69
+ _KNOWN_BARE_LOCATION_RE = re.compile(
70
+ r"^(?:Москва|Санкт-Петербург|СПб|Ростов-на-Дону)$",
71
+ re.IGNORECASE,
72
+ )
73
+ _ONLY_GAP_RE = re.compile(r"^[\s,./()«»\"'–—-]*$")
74
+ _TRIM_LEFT = " \t\r\n,;:()[]{}«»\"'–—"
75
+ _TRIM_RIGHT = " \t\r\n,;:.()[]{}«»\"'"
76
+ _MAX_STREET_TO_HOUSE = 160
77
+ _MAX_CANDIDATE = 240
78
+
79
+
80
+ @dataclass(frozen=True, slots=True)
81
+ class _Candidate:
82
+ start: int
83
+ end: int
84
+ cue: bool
85
+ street_marker: bool
86
+ house_marker: bool
87
+
88
+
89
+ def _trim_span(text: str, start: int, end: int) -> tuple[int, int]:
90
+ while start < end and text[start] in _TRIM_LEFT:
91
+ start += 1
92
+ while end > start and text[end - 1] in _TRIM_RIGHT:
93
+ end -= 1
94
+ return start, end
95
+
96
+
97
+ def _is_sentence_period(text: str, index: int) -> bool:
98
+ next_index = index + 1
99
+ while next_index < len(text) and text[next_index].isspace():
100
+ next_index += 1
101
+ if next_index >= len(text) or not text[next_index].isupper():
102
+ return False
103
+
104
+ previous = text[:index].rstrip()
105
+ token_match = re.search(r"([A-Za-zА-Яа-яЁё]+|\d+)$", previous)
106
+ if token_match is None:
107
+ return True
108
+ token = token_match.group(1).casefold().replace("ё", "е")
109
+ abbreviations = {
110
+ "г",
111
+ "д",
112
+ "вл",
113
+ "ул",
114
+ "пер",
115
+ "пр",
116
+ "стр",
117
+ "корп",
118
+ "кв",
119
+ "ком",
120
+ "комн",
121
+ "кор",
122
+ "наб",
123
+ "обл",
124
+ "оф",
125
+ "пом",
126
+ "просп",
127
+ "р",
128
+ "п",
129
+ "с",
130
+ "ш",
131
+ }
132
+ return token.isdigit() or token not in abbreviations
133
+
134
+
135
+ def _clauses(text: str) -> Iterable[tuple[int, int]]:
136
+ start = 0
137
+ for index, character in enumerate(text):
138
+ boundary = character in ";\n!?"
139
+ if character == ".":
140
+ boundary = _is_sentence_period(text, index)
141
+ if not boundary:
142
+ continue
143
+ left, right = _trim_span(text, start, index)
144
+ if left < right:
145
+ yield left, right
146
+ start = index + 1
147
+ left, right = _trim_span(text, start, len(text))
148
+ if left < right:
149
+ yield left, right
150
+
151
+
152
+ def _street_start(
153
+ text: str,
154
+ clause_start: int,
155
+ street: re.Match[str],
156
+ house_start: int,
157
+ ) -> int:
158
+ ordinal = _ORDINAL_BEFORE_MARKER_RE.search(
159
+ text,
160
+ clause_start,
161
+ street.start(),
162
+ )
163
+ if ordinal is not None:
164
+ return ordinal.start()
165
+
166
+ after_marker = text[street.end() : house_start]
167
+ if re.search(rf"[{_LETTER}]", after_marker):
168
+ return street.start()
169
+
170
+ delimiter = max(
171
+ text.rfind(",", clause_start, street.start()),
172
+ text.rfind(":", clause_start, street.start()),
173
+ )
174
+ return delimiter + 1 if delimiter >= clause_start else clause_start
175
+
176
+
177
+ def _is_location_chunk(value: str) -> bool:
178
+ stripped = value.strip(" \t,")
179
+ return bool(
180
+ stripped
181
+ and (
182
+ _POSTAL_RE.fullmatch(stripped)
183
+ or _COUNTRY_RE.search(stripped)
184
+ or _LOCATION_MARKER_RE.search(stripped)
185
+ or _KNOWN_BARE_LOCATION_RE.fullmatch(stripped)
186
+ )
187
+ )
188
+
189
+
190
+ def _extend_location_prefix(
191
+ text: str,
192
+ clause_start: int,
193
+ address_start: int,
194
+ ) -> int:
195
+ extended = address_start
196
+ cursor = address_start
197
+ while cursor > clause_start:
198
+ delimiter = cursor
199
+ while delimiter > clause_start and text[delimiter - 1].isspace():
200
+ delimiter -= 1
201
+ if delimiter <= clause_start or text[delimiter - 1] != ",":
202
+ break
203
+ comma = delimiter - 1
204
+ previous = max(
205
+ text.rfind(",", clause_start, comma),
206
+ text.rfind(":", clause_start, comma),
207
+ )
208
+ chunk_start = previous + 1 if previous >= clause_start else clause_start
209
+ if not _is_location_chunk(text[chunk_start:comma]):
210
+ break
211
+ extended = chunk_start
212
+ cursor = chunk_start
213
+ return extended
214
+
215
+
216
+ def _extend_units(text: str, start: int, clause_end: int) -> int:
217
+ end = start
218
+ for unit in _UNIT_RE.finditer(text, start, clause_end):
219
+ if not _ONLY_GAP_RE.fullmatch(text[end : unit.start()]):
220
+ break
221
+ end = unit.end()
222
+ return end
223
+
224
+
225
+ def _select_bare_number(
226
+ text: str,
227
+ street: re.Match[str],
228
+ numbers: list[re.Match[str]],
229
+ ) -> re.Match[str]:
230
+ after_comma = [
231
+ number
232
+ for number in numbers
233
+ if re.search(r",\s*$", text[street.end() : number.start()])
234
+ ]
235
+ if after_comma:
236
+ return after_comma[0]
237
+ first = numbers[0]
238
+ if (
239
+ len(numbers) > 1
240
+ and not text[street.end() : first.start()].strip(" .")
241
+ ):
242
+ return numbers[1]
243
+ return first
244
+
245
+
246
+ def _explicit_candidates(text: str) -> list[_Candidate]:
247
+ candidates: list[_Candidate] = []
248
+ for clause_start, clause_end in _clauses(text):
249
+ streets = list(_STREET_MARKER_RE.finditer(text, clause_start, clause_end))
250
+ houses = list(_HOUSE_RE.finditer(text, clause_start, clause_end))
251
+ cues = list(_CUE_RE.finditer(text, clause_start, clause_end))
252
+ for house in houses:
253
+ eligible = [
254
+ street
255
+ for street in streets
256
+ if street.start() < house.start()
257
+ and house.start() - street.end() <= _MAX_STREET_TO_HOUSE
258
+ ]
259
+ if not eligible:
260
+ continue
261
+ street = eligible[-1]
262
+ cue = next(
263
+ (
264
+ item
265
+ for item in reversed(cues)
266
+ if item.end() <= street.start()
267
+ ),
268
+ None,
269
+ )
270
+ prefix_start = cue.end() if cue is not None else clause_start
271
+ start = _street_start(
272
+ text,
273
+ prefix_start,
274
+ street,
275
+ house.start(),
276
+ )
277
+ start = _extend_location_prefix(text, prefix_start, start)
278
+ end = _extend_units(text, house.end(), clause_end)
279
+ start, end = _trim_span(text, start, end)
280
+ if start < end and end - start <= _MAX_CANDIDATE:
281
+ candidates.append(
282
+ _Candidate(
283
+ start=start,
284
+ end=end,
285
+ cue=cue is not None,
286
+ street_marker=True,
287
+ house_marker=True,
288
+ )
289
+ )
290
+
291
+ for street in streets:
292
+ if any(
293
+ street.start() >= candidate.start
294
+ and street.end() <= candidate.end
295
+ for candidate in candidates
296
+ ):
297
+ continue
298
+ numbers = [
299
+ match
300
+ for match in _BARE_NUMBER_RE.finditer(
301
+ text,
302
+ street.end(),
303
+ clause_end,
304
+ )
305
+ if match.start() - street.end() <= _MAX_STREET_TO_HOUSE
306
+ ]
307
+ if not numbers:
308
+ continue
309
+ number = _select_bare_number(text, street, numbers)
310
+ cue = next(
311
+ (
312
+ item
313
+ for item in reversed(cues)
314
+ if item.end() <= street.start()
315
+ ),
316
+ None,
317
+ )
318
+ if (
319
+ cue is None
320
+ and _NON_NAME_AFTER_MARKER_RE.match(
321
+ text[street.end() : number.start()]
322
+ )
323
+ ):
324
+ continue
325
+ prefix_start = cue.end() if cue is not None else clause_start
326
+ start = _street_start(
327
+ text,
328
+ prefix_start,
329
+ street,
330
+ number.start(),
331
+ )
332
+ start = _extend_location_prefix(text, prefix_start, start)
333
+ end = _extend_units(text, number.end(), clause_end)
334
+ start, end = _trim_span(text, start, end)
335
+ if start < end and end - start <= _MAX_CANDIDATE:
336
+ candidates.append(
337
+ _Candidate(
338
+ start=start,
339
+ end=end,
340
+ cue=cue is not None,
341
+ street_marker=True,
342
+ house_marker=False,
343
+ )
344
+ )
345
+ return candidates
346
+
347
+
348
+ def _cue_candidates(text: str) -> list[_Candidate]:
349
+ candidates: list[_Candidate] = []
350
+ for clause_start, clause_end in _clauses(text):
351
+ for cue in _CUE_RE.finditer(text, clause_start, clause_end):
352
+ if _NETWORK_PREFIX_RE.search(text[clause_start : cue.start()]):
353
+ continue
354
+ numbers = list(_BARE_NUMBER_RE.finditer(text, cue.end(), clause_end))
355
+ if not numbers:
356
+ continue
357
+ start, end = _trim_span(text, cue.end(), numbers[-1].end())
358
+ if start < end and end - start <= _MAX_CANDIDATE:
359
+ candidates.append(
360
+ _Candidate(
361
+ start=start,
362
+ end=end,
363
+ cue=True,
364
+ street_marker=bool(
365
+ _STREET_MARKER_RE.search(text, start, end)
366
+ ),
367
+ house_marker=bool(_HOUSE_RE.search(text, start, end)),
368
+ )
369
+ )
370
+ return candidates
371
+
372
+
373
+ def _signals(
374
+ candidate: _Candidate,
375
+ text: str,
376
+ *,
377
+ parsed_street: bool,
378
+ parsed_house: bool,
379
+ has_unparsed: bool,
380
+ ) -> tuple[tuple[str, ...], float]:
381
+ signals: list[str] = []
382
+ score = 0.0
383
+ if candidate.cue:
384
+ signals.append("address_cue")
385
+ score += 0.18
386
+ if candidate.street_marker:
387
+ signals.append("street_marker")
388
+ score += 0.28
389
+ if candidate.house_marker:
390
+ signals.append("house_marker")
391
+ score += 0.28
392
+ if _POSTAL_RE.search(text):
393
+ signals.append("postal_code")
394
+ score += 0.08
395
+ if _LOCATION_MARKER_RE.search(text):
396
+ signals.append("location_marker")
397
+ score += 0.06
398
+ if _UNIT_RE.search(text):
399
+ signals.append("unit_marker")
400
+ score += 0.05
401
+ if parsed_street:
402
+ signals.append("parsed_street")
403
+ score += 0.08
404
+ if parsed_house:
405
+ signals.append("parsed_house")
406
+ score += 0.08
407
+ if has_unparsed:
408
+ signals.append("unparsed_text")
409
+ score -= 0.05
410
+ return tuple(signals), max(0.0, min(0.99, score))
411
+
412
+
413
+ class AddressDetector:
414
+ """Detect conservative address candidates without registry lookups."""
415
+
416
+ def __init__(self, parser: AddressParser) -> None:
417
+ self._parser = parser
418
+
419
+ def detect(self, text: str) -> tuple[DetectedAddress, ...]:
420
+ """Return non-overlapping address-like spans in message order."""
421
+
422
+ raw_candidates = [*_explicit_candidates(text), *_cue_candidates(text)]
423
+ accepted: list[DetectedAddress] = []
424
+ seen: set[tuple[int, int]] = set()
425
+ for candidate in raw_candidates:
426
+ key = candidate.start, candidate.end
427
+ if key in seen:
428
+ continue
429
+ seen.add(key)
430
+ candidate_text = text[candidate.start : candidate.end]
431
+ parsed = self._parser.parse(candidate_text)
432
+ has_street = parsed.street is not None
433
+ has_house = parsed.house_num is not None
434
+ if not (has_street and has_house):
435
+ continue
436
+ if candidate.cue and not candidate.street_marker:
437
+ assert parsed.street is not None
438
+ assert parsed.house_num is not None
439
+ street_letters = re.sub(
440
+ rf"[^{_LETTER}]",
441
+ "",
442
+ parsed.street.raw,
443
+ )
444
+ word_count = len(
445
+ re.findall(rf"[{_LETTER}]+", candidate_text)
446
+ )
447
+ if (
448
+ len(street_letters) < 3
449
+ or word_count > 8
450
+ or len(parsed.house_num.value) > 6
451
+ ):
452
+ continue
453
+ if (
454
+ not candidate.cue
455
+ and not candidate.house_marker
456
+ and parsed.unparsed
457
+ ):
458
+ continue
459
+ if not (candidate.street_marker or candidate.cue):
460
+ continue
461
+ signals, confidence = _signals(
462
+ candidate,
463
+ candidate_text,
464
+ parsed_street=has_street,
465
+ parsed_house=has_house,
466
+ has_unparsed=bool(parsed.unparsed),
467
+ )
468
+ accepted.append(
469
+ DetectedAddress(
470
+ text=candidate_text,
471
+ start=candidate.start,
472
+ end=candidate.end,
473
+ confidence=confidence,
474
+ signals=signals,
475
+ parsed=parsed,
476
+ )
477
+ )
478
+
479
+ ranked = sorted(
480
+ accepted,
481
+ key=lambda item: (
482
+ item.start,
483
+ -item.confidence,
484
+ -(item.end - item.start),
485
+ ),
486
+ )
487
+ non_overlapping: list[DetectedAddress] = []
488
+ for item in ranked:
489
+ overlapping = [
490
+ existing
491
+ for existing in non_overlapping
492
+ if item.start < existing.end and item.end > existing.start
493
+ ]
494
+ if not overlapping:
495
+ non_overlapping.append(item)
496
+ continue
497
+ best = max(
498
+ [item, *overlapping],
499
+ key=lambda value: (
500
+ value.confidence,
501
+ value.end - value.start,
502
+ ),
503
+ )
504
+ if best is item:
505
+ non_overlapping = [
506
+ existing
507
+ for existing in non_overlapping
508
+ if existing not in overlapping
509
+ ]
510
+ non_overlapping.append(item)
511
+ return tuple(sorted(non_overlapping, key=lambda item: item.start))
@@ -0,0 +1,49 @@
1
+ """Small, registry-independent normalization helpers."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+
7
+
8
+ NAME_ALIASES = {
9
+ "мск": "Москва",
10
+ "москва": "Москва",
11
+ "спб": "Санкт-Петербург",
12
+ "питер": "Санкт-Петербург",
13
+ "санкт петербург": "Санкт-Петербург",
14
+ "санкт-петербург": "Санкт-Петербург",
15
+ }
16
+
17
+ LOWERCASE_PARTS = {"в", "во", "на", "по", "им", "имени"}
18
+
19
+
20
+ def normalize_name(value: str) -> str:
21
+ value = re.sub(r"\s+", " ", value.strip(" \t\r\n,.;:"))
22
+ folded = value.casefold().replace("ё", "е")
23
+ if folded in NAME_ALIASES:
24
+ return NAME_ALIASES[folded]
25
+
26
+ words: list[str] = []
27
+ for word_index, word in enumerate(value.split(" ")):
28
+ hyphenated: list[str] = []
29
+ for part_index, part in enumerate(word.split("-")):
30
+ if not part:
31
+ hyphenated.append(part)
32
+ elif part.isdigit():
33
+ hyphenated.append(part)
34
+ elif re.fullmatch(r"\d+[A-Za-zА-Яа-яЁё]+", part):
35
+ hyphenated.append(part.upper())
36
+ elif part.casefold() in LOWERCASE_PARTS and (
37
+ word_index > 0 or part_index > 0
38
+ ):
39
+ hyphenated.append(part.casefold())
40
+ elif re.fullmatch(r"\d+", word.split("-")[0]) and part_index > 0:
41
+ hyphenated.append(part.casefold())
42
+ else:
43
+ hyphenated.append(part[:1].upper() + part[1:].lower())
44
+ words.append("-".join(hyphenated))
45
+ return " ".join(words)
46
+
47
+
48
+ def normalize_number(value: str) -> str:
49
+ return re.sub(r"\s*([/-])\s*", r"\1", value.strip()).upper()