address-normalizer 2.0.0a2__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.0a2.dist-info/METADATA +160 -0
- address_normalizer-2.0.0a2.dist-info/RECORD +17 -0
- address_normalizer-2.0.0a2.dist-info/WHEEL +5 -0
- address_normalizer-2.0.0a2.dist-info/entry_points.txt +2 -0
- address_normalizer-2.0.0a2.dist-info/licenses/LICENSE +675 -0
- address_normalizer-2.0.0a2.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
"""Tiny dependency-free structured sequence tagger.
|
|
2
|
+
|
|
3
|
+
The bundled model is deliberately small. It is used only to classify residual,
|
|
4
|
+
unmarked text after deterministic address syntax has been extracted.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from importlib.resources import files
|
|
10
|
+
import json
|
|
11
|
+
from math import exp
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
from typing import cast, Iterable, Sequence
|
|
14
|
+
|
|
15
|
+
from .tokenizer import Token
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
START = "<START>"
|
|
19
|
+
END = "<END>"
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def token_features(tokens: Sequence[Token], index: int) -> tuple[str, ...]:
|
|
23
|
+
token = tokens[index]
|
|
24
|
+
lower = token.lower
|
|
25
|
+
features = [
|
|
26
|
+
"bias",
|
|
27
|
+
f"word={lower}",
|
|
28
|
+
f"kind={'number' if token.is_number else 'word' if token.is_word else 'punct'}",
|
|
29
|
+
f"prefix1={lower[:1]}",
|
|
30
|
+
f"prefix2={lower[:2]}",
|
|
31
|
+
f"suffix1={lower[-1:]}",
|
|
32
|
+
f"suffix2={lower[-2:]}",
|
|
33
|
+
f"suffix3={lower[-3:]}",
|
|
34
|
+
f"position={'first' if index == 0 else 'last' if index == len(tokens) - 1 else 'middle'}",
|
|
35
|
+
]
|
|
36
|
+
if token.is_number:
|
|
37
|
+
features.append(f"digits={min(len(token.text), 6)}")
|
|
38
|
+
if index:
|
|
39
|
+
previous = tokens[index - 1]
|
|
40
|
+
features.extend(
|
|
41
|
+
(
|
|
42
|
+
f"prev={previous.lower}",
|
|
43
|
+
f"prev_kind={'number' if previous.is_number else 'word' if previous.is_word else 'punct'}",
|
|
44
|
+
)
|
|
45
|
+
)
|
|
46
|
+
else:
|
|
47
|
+
features.append("bos")
|
|
48
|
+
if index + 1 < len(tokens):
|
|
49
|
+
following = tokens[index + 1]
|
|
50
|
+
features.extend(
|
|
51
|
+
(
|
|
52
|
+
f"next={following.lower}",
|
|
53
|
+
f"next_kind={'number' if following.is_number else 'word' if following.is_word else 'punct'}",
|
|
54
|
+
)
|
|
55
|
+
)
|
|
56
|
+
else:
|
|
57
|
+
features.append("eos")
|
|
58
|
+
return tuple(features)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
class CompactSequenceTagger:
|
|
62
|
+
"""Sparse linear-chain model with Viterbi inference."""
|
|
63
|
+
|
|
64
|
+
def __init__(
|
|
65
|
+
self,
|
|
66
|
+
labels: Sequence[str],
|
|
67
|
+
emissions: dict[str, float],
|
|
68
|
+
transitions: dict[str, float],
|
|
69
|
+
) -> None:
|
|
70
|
+
self.labels = tuple(labels)
|
|
71
|
+
self.emissions = emissions
|
|
72
|
+
self.transitions = transitions
|
|
73
|
+
|
|
74
|
+
@classmethod
|
|
75
|
+
def from_package(cls) -> "CompactSequenceTagger":
|
|
76
|
+
model_path = files("address_normalizer").joinpath("data/model.json")
|
|
77
|
+
return cls.from_payload(json.loads(model_path.read_text(encoding="utf-8")))
|
|
78
|
+
|
|
79
|
+
@classmethod
|
|
80
|
+
def from_path(cls, path: str | Path) -> "CompactSequenceTagger":
|
|
81
|
+
payload = json.loads(Path(path).read_text(encoding="utf-8"))
|
|
82
|
+
return cls.from_payload(payload)
|
|
83
|
+
|
|
84
|
+
@classmethod
|
|
85
|
+
def from_payload(cls, payload: dict[str, object]) -> "CompactSequenceTagger":
|
|
86
|
+
return cls(
|
|
87
|
+
labels=cast(list[str], payload["labels"]),
|
|
88
|
+
emissions=cast(dict[str, float], payload["emissions"]),
|
|
89
|
+
transitions=cast(dict[str, float], payload["transitions"]),
|
|
90
|
+
)
|
|
91
|
+
|
|
92
|
+
def emission_score(self, label: str, features: Iterable[str]) -> float:
|
|
93
|
+
return sum(
|
|
94
|
+
self.emissions.get(f"{label}\t{feature}", 0.0)
|
|
95
|
+
for feature in features
|
|
96
|
+
)
|
|
97
|
+
|
|
98
|
+
def transition_score(self, previous: str, label: str) -> float:
|
|
99
|
+
return self.transitions.get(f"{previous}\t{label}", 0.0)
|
|
100
|
+
|
|
101
|
+
def tag(self, tokens: Sequence[Token]) -> tuple[list[str], list[float]]:
|
|
102
|
+
if not tokens:
|
|
103
|
+
return [], []
|
|
104
|
+
|
|
105
|
+
features = [token_features(tokens, index) for index in range(len(tokens))]
|
|
106
|
+
scores: dict[str, float] = {}
|
|
107
|
+
paths: dict[str, list[str]] = {}
|
|
108
|
+
for label in self.labels:
|
|
109
|
+
scores[label] = self.transition_score(START, label) + self.emission_score(
|
|
110
|
+
label, features[0]
|
|
111
|
+
)
|
|
112
|
+
paths[label] = [label]
|
|
113
|
+
|
|
114
|
+
margins: list[float] = []
|
|
115
|
+
for index in range(1, len(tokens)):
|
|
116
|
+
next_scores: dict[str, float] = {}
|
|
117
|
+
next_paths: dict[str, list[str]] = {}
|
|
118
|
+
for label in self.labels:
|
|
119
|
+
candidates = [
|
|
120
|
+
(
|
|
121
|
+
score
|
|
122
|
+
+ self.transition_score(previous, label)
|
|
123
|
+
+ self.emission_score(label, features[index]),
|
|
124
|
+
previous,
|
|
125
|
+
)
|
|
126
|
+
for previous, score in scores.items()
|
|
127
|
+
]
|
|
128
|
+
best_score, best_previous = max(candidates)
|
|
129
|
+
next_scores[label] = best_score
|
|
130
|
+
next_paths[label] = [*paths[best_previous], label]
|
|
131
|
+
ordered = sorted(next_scores.values(), reverse=True)
|
|
132
|
+
margins.append(ordered[0] - ordered[1] if len(ordered) > 1 else 10.0)
|
|
133
|
+
scores, paths = next_scores, next_paths
|
|
134
|
+
|
|
135
|
+
finals = [
|
|
136
|
+
(score + self.transition_score(label, END), label)
|
|
137
|
+
for label, score in scores.items()
|
|
138
|
+
]
|
|
139
|
+
_, best_label = max(finals)
|
|
140
|
+
labels = paths[best_label]
|
|
141
|
+
|
|
142
|
+
# These are bounded decision-strength scores, not calibrated probabilities.
|
|
143
|
+
token_confidence = [0.78]
|
|
144
|
+
token_confidence.extend(0.5 + 0.45 * (1.0 - exp(-max(0.0, margin))) for margin in margins)
|
|
145
|
+
return labels, token_confidence
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
"""Offset-preserving tokenizer for short address strings."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
import re
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
TOKEN_RE = re.compile(
|
|
10
|
+
r"[A-Za-zА-Яа-яЁё]+|\d+|[№#]|[^\w\s]",
|
|
11
|
+
re.UNICODE,
|
|
12
|
+
)
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@dataclass(frozen=True, slots=True)
|
|
16
|
+
class Token:
|
|
17
|
+
text: str
|
|
18
|
+
start: int
|
|
19
|
+
end: int
|
|
20
|
+
|
|
21
|
+
@property
|
|
22
|
+
def lower(self) -> str:
|
|
23
|
+
return self.text.casefold().replace("ё", "е")
|
|
24
|
+
|
|
25
|
+
@property
|
|
26
|
+
def is_word(self) -> bool:
|
|
27
|
+
return self.text.isalpha()
|
|
28
|
+
|
|
29
|
+
@property
|
|
30
|
+
def is_number(self) -> bool:
|
|
31
|
+
return self.text.isdigit()
|
|
32
|
+
|
|
33
|
+
@property
|
|
34
|
+
def is_separator(self) -> bool:
|
|
35
|
+
return self.text in {",", ";", ":"}
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def tokenize(text: str) -> list[Token]:
|
|
39
|
+
return [
|
|
40
|
+
Token(match.group(0), match.start(), match.end())
|
|
41
|
+
for match in TOKEN_RE.finditer(text)
|
|
42
|
+
]
|
|
@@ -0,0 +1,232 @@
|
|
|
1
|
+
"""Public result types for the parser."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from typing import TypedDict
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class AddressPartDict(TypedDict):
|
|
10
|
+
"""JSON-compatible serialization of :class:`AddressPart`."""
|
|
11
|
+
|
|
12
|
+
value: str
|
|
13
|
+
raw: str
|
|
14
|
+
span: list[int]
|
|
15
|
+
confidence: float
|
|
16
|
+
source: str
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class AlternativeDict(TypedDict):
|
|
20
|
+
"""JSON-compatible serialization of :class:`Alternative`."""
|
|
21
|
+
|
|
22
|
+
components: dict[str, str]
|
|
23
|
+
confidence: float
|
|
24
|
+
reason: str
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class ParsedAddressDict(TypedDict):
|
|
28
|
+
"""Stable JSON-compatible serialization of :class:`ParsedAddress`."""
|
|
29
|
+
|
|
30
|
+
raw: str
|
|
31
|
+
normalized: str
|
|
32
|
+
confidence: float
|
|
33
|
+
postal_code: AddressPartDict | None
|
|
34
|
+
region: AddressPartDict | None
|
|
35
|
+
district: AddressPartDict | None
|
|
36
|
+
city: AddressPartDict | None
|
|
37
|
+
settlement: AddressPartDict | None
|
|
38
|
+
street: AddressPartDict | None
|
|
39
|
+
street_type: AddressPartDict | None
|
|
40
|
+
house_num: AddressPartDict | None
|
|
41
|
+
corpus: AddressPartDict | None
|
|
42
|
+
structure: AddressPartDict | None
|
|
43
|
+
apartment: AddressPartDict | None
|
|
44
|
+
unparsed: list[AddressPartDict]
|
|
45
|
+
warnings: list[str]
|
|
46
|
+
alternatives: list[AlternativeDict]
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class DetectedAddressDict(TypedDict):
|
|
50
|
+
"""JSON-compatible serialization of :class:`DetectedAddress`."""
|
|
51
|
+
|
|
52
|
+
text: str
|
|
53
|
+
span: list[int]
|
|
54
|
+
confidence: float
|
|
55
|
+
signals: list[str]
|
|
56
|
+
parsed: ParsedAddressDict
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
@dataclass(frozen=True, slots=True)
|
|
60
|
+
class AddressPart:
|
|
61
|
+
"""One component extracted from a half-open span of the original string.
|
|
62
|
+
|
|
63
|
+
``confidence`` is a bounded decision-strength score, not a calibrated
|
|
64
|
+
probability.
|
|
65
|
+
"""
|
|
66
|
+
|
|
67
|
+
value: str
|
|
68
|
+
raw: str
|
|
69
|
+
start: int
|
|
70
|
+
end: int
|
|
71
|
+
confidence: float
|
|
72
|
+
source: str
|
|
73
|
+
|
|
74
|
+
@property
|
|
75
|
+
def span(self) -> tuple[int, int]:
|
|
76
|
+
return self.start, self.end
|
|
77
|
+
|
|
78
|
+
def as_dict(self) -> AddressPartDict:
|
|
79
|
+
"""Return the stable JSON-compatible representation."""
|
|
80
|
+
|
|
81
|
+
return {
|
|
82
|
+
"value": self.value,
|
|
83
|
+
"raw": self.raw,
|
|
84
|
+
"span": [self.start, self.end],
|
|
85
|
+
"confidence": round(self.confidence, 4),
|
|
86
|
+
"source": self.source,
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
@dataclass(frozen=True, slots=True)
|
|
91
|
+
class Alternative:
|
|
92
|
+
"""A plausible competing interpretation retained for downstream review.
|
|
93
|
+
|
|
94
|
+
``confidence`` is a relative decision-strength score, not a calibrated
|
|
95
|
+
probability.
|
|
96
|
+
"""
|
|
97
|
+
|
|
98
|
+
components: dict[str, str]
|
|
99
|
+
confidence: float
|
|
100
|
+
reason: str
|
|
101
|
+
|
|
102
|
+
def as_dict(self) -> AlternativeDict:
|
|
103
|
+
"""Return the stable JSON-compatible representation."""
|
|
104
|
+
|
|
105
|
+
return {
|
|
106
|
+
"components": dict(self.components),
|
|
107
|
+
"confidence": round(self.confidence, 4),
|
|
108
|
+
"reason": self.reason,
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
@dataclass(frozen=True, slots=True)
|
|
113
|
+
class ParsedAddress:
|
|
114
|
+
"""Structured, unverified interpretation of an address string.
|
|
115
|
+
|
|
116
|
+
Component spans always index ``raw``. Review ``warnings``, ``alternatives``,
|
|
117
|
+
and ``unparsed`` before accepting an automated interpretation.
|
|
118
|
+
``confidence`` is a decision-strength score, not a probability that the
|
|
119
|
+
address exists or is correct.
|
|
120
|
+
"""
|
|
121
|
+
|
|
122
|
+
raw: str
|
|
123
|
+
postal_code: AddressPart | None = None
|
|
124
|
+
region: AddressPart | None = None
|
|
125
|
+
district: AddressPart | None = None
|
|
126
|
+
city: AddressPart | None = None
|
|
127
|
+
settlement: AddressPart | None = None
|
|
128
|
+
street: AddressPart | None = None
|
|
129
|
+
street_type: AddressPart | None = None
|
|
130
|
+
house_num: AddressPart | None = None
|
|
131
|
+
corpus: AddressPart | None = None
|
|
132
|
+
structure: AddressPart | None = None
|
|
133
|
+
apartment: AddressPart | None = None
|
|
134
|
+
unparsed: tuple[AddressPart, ...] = ()
|
|
135
|
+
warnings: tuple[str, ...] = ()
|
|
136
|
+
alternatives: tuple[Alternative, ...] = ()
|
|
137
|
+
confidence: float = 0.0
|
|
138
|
+
|
|
139
|
+
@property
|
|
140
|
+
def normalized(self) -> str:
|
|
141
|
+
"""Return a display-oriented composition of extracted values."""
|
|
142
|
+
|
|
143
|
+
chunks: list[str] = []
|
|
144
|
+
for part in (
|
|
145
|
+
self.postal_code,
|
|
146
|
+
self.region,
|
|
147
|
+
self.district,
|
|
148
|
+
self.city,
|
|
149
|
+
self.settlement,
|
|
150
|
+
):
|
|
151
|
+
if part:
|
|
152
|
+
chunks.append(part.value)
|
|
153
|
+
|
|
154
|
+
if self.street:
|
|
155
|
+
if self.street_type:
|
|
156
|
+
chunks.append(f"{self.street_type.value} {self.street.value}")
|
|
157
|
+
else:
|
|
158
|
+
chunks.append(self.street.value)
|
|
159
|
+
|
|
160
|
+
for prefix, part in (
|
|
161
|
+
("д", self.house_num),
|
|
162
|
+
("корп", self.corpus),
|
|
163
|
+
("стр", self.structure),
|
|
164
|
+
("кв", self.apartment),
|
|
165
|
+
):
|
|
166
|
+
if part:
|
|
167
|
+
chunks.append(f"{prefix} {part.value}")
|
|
168
|
+
return ", ".join(chunks)
|
|
169
|
+
|
|
170
|
+
def as_dict(self) -> ParsedAddressDict:
|
|
171
|
+
"""Return the stable JSON-compatible representation."""
|
|
172
|
+
|
|
173
|
+
return {
|
|
174
|
+
"raw": self.raw,
|
|
175
|
+
"normalized": self.normalized,
|
|
176
|
+
"confidence": round(self.confidence, 4),
|
|
177
|
+
"postal_code": self.postal_code.as_dict()
|
|
178
|
+
if self.postal_code
|
|
179
|
+
else None,
|
|
180
|
+
"region": self.region.as_dict() if self.region else None,
|
|
181
|
+
"district": self.district.as_dict() if self.district else None,
|
|
182
|
+
"city": self.city.as_dict() if self.city else None,
|
|
183
|
+
"settlement": self.settlement.as_dict() if self.settlement else None,
|
|
184
|
+
"street": self.street.as_dict() if self.street else None,
|
|
185
|
+
"street_type": self.street_type.as_dict()
|
|
186
|
+
if self.street_type
|
|
187
|
+
else None,
|
|
188
|
+
"house_num": self.house_num.as_dict() if self.house_num else None,
|
|
189
|
+
"corpus": self.corpus.as_dict() if self.corpus else None,
|
|
190
|
+
"structure": self.structure.as_dict() if self.structure else None,
|
|
191
|
+
"apartment": self.apartment.as_dict() if self.apartment else None,
|
|
192
|
+
"unparsed": [part.as_dict() for part in self.unparsed],
|
|
193
|
+
"warnings": list(self.warnings),
|
|
194
|
+
"alternatives": [
|
|
195
|
+
alternative.as_dict() for alternative in self.alternatives
|
|
196
|
+
],
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
@dataclass(frozen=True, slots=True)
|
|
201
|
+
class DetectedAddress:
|
|
202
|
+
"""One address-like span detected inside a larger message.
|
|
203
|
+
|
|
204
|
+
``start`` and ``end`` are half-open offsets into the original message.
|
|
205
|
+
Component offsets in ``parsed`` are relative to ``text``. ``confidence`` is
|
|
206
|
+
detection decision strength, not a calibrated probability or proof that
|
|
207
|
+
the address exists.
|
|
208
|
+
"""
|
|
209
|
+
|
|
210
|
+
text: str
|
|
211
|
+
start: int
|
|
212
|
+
end: int
|
|
213
|
+
confidence: float
|
|
214
|
+
signals: tuple[str, ...]
|
|
215
|
+
parsed: ParsedAddress
|
|
216
|
+
|
|
217
|
+
@property
|
|
218
|
+
def span(self) -> tuple[int, int]:
|
|
219
|
+
"""Return the half-open span in the original message."""
|
|
220
|
+
|
|
221
|
+
return self.start, self.end
|
|
222
|
+
|
|
223
|
+
def as_dict(self) -> DetectedAddressDict:
|
|
224
|
+
"""Return the stable JSON-compatible representation."""
|
|
225
|
+
|
|
226
|
+
return {
|
|
227
|
+
"text": self.text,
|
|
228
|
+
"span": [self.start, self.end],
|
|
229
|
+
"confidence": round(self.confidence, 4),
|
|
230
|
+
"signals": list(self.signals),
|
|
231
|
+
"parsed": self.parsed.as_dict(),
|
|
232
|
+
}
|
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: address-normalizer
|
|
3
|
+
Version: 2.0.0a2
|
|
4
|
+
Summary: A small offline parser for unstructured Russian addresses
|
|
5
|
+
Author: Ilya Shigabeev
|
|
6
|
+
License-Expression: GPL-3.0-only
|
|
7
|
+
Project-URL: Homepage, https://github.com/shigabeev/address-normalizer
|
|
8
|
+
Project-URL: Repository, https://github.com/shigabeev/address-normalizer
|
|
9
|
+
Project-URL: Issues, https://github.com/shigabeev/address-normalizer/issues
|
|
10
|
+
Keywords: address,parser,russian,normalization,nlp
|
|
11
|
+
Classifier: Development Status :: 3 - Alpha
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: Natural Language :: Russian
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
21
|
+
Classifier: Typing :: Typed
|
|
22
|
+
Classifier: Operating System :: OS Independent
|
|
23
|
+
Classifier: Topic :: Text Processing :: Linguistic
|
|
24
|
+
Requires-Python: >=3.10
|
|
25
|
+
Description-Content-Type: text/markdown
|
|
26
|
+
License-File: LICENSE
|
|
27
|
+
Dynamic: license-file
|
|
28
|
+
|
|
29
|
+
# address-normalizer
|
|
30
|
+
|
|
31
|
+
Небольшой офлайн-парсер российских адресов для Python 3.10+. Извлекает поля,
|
|
32
|
+
сохраняет исходные подстроки и смещения, не требует runtime-зависимостей.
|
|
33
|
+
|
|
34
|
+
[English README](https://github.com/shigabeev/address-normalizer/blob/master/README.en.md)
|
|
35
|
+
|
|
36
|
+
## Установка
|
|
37
|
+
|
|
38
|
+
```bash
|
|
39
|
+
python -m pip install --pre address-normalizer
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
## Использование
|
|
43
|
+
|
|
44
|
+
```python
|
|
45
|
+
from address_normalizer import parse
|
|
46
|
+
|
|
47
|
+
result = parse("г. Москва, ул. Тверская, д. 4, кв. 12")
|
|
48
|
+
|
|
49
|
+
print(result.city.value) # Москва
|
|
50
|
+
print(result.street.value) # Тверская
|
|
51
|
+
print(result.house_num.value) # 4
|
|
52
|
+
print(result.apartment.value) # 12
|
|
53
|
+
print(result.normalized) # Москва, ул Тверская, д 4, кв 12
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
Каждый компонент содержит `value`, точную исходную подстроку `raw`, полуоткрытый
|
|
57
|
+
интервал `start:end`, источник решения и `confidence`. Весь результат можно
|
|
58
|
+
сериализовать:
|
|
59
|
+
|
|
60
|
+
```python
|
|
61
|
+
payload = result.as_dict() # обычный JSON-совместимый dict
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
Неоднозначность не скрывается:
|
|
65
|
+
|
|
66
|
+
```python
|
|
67
|
+
result = parse("Ополченская 5-30")
|
|
68
|
+
|
|
69
|
+
print(result.normalized) # Ополченская, д 5, кв 30
|
|
70
|
+
print(result.warnings) # ("ambiguous_numeric_tail",)
|
|
71
|
+
print(result.alternatives) # среди вариантов есть дом 5-30
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
`confidence` — сила решения внутри парсера, а не вероятность существования
|
|
75
|
+
адреса. Результаты с `warnings`, `alternatives` или `unparsed` стоит проверять.
|
|
76
|
+
|
|
77
|
+
### Поиск адреса в сообщении
|
|
78
|
+
|
|
79
|
+
```python
|
|
80
|
+
from address_normalizer import detect_addresses
|
|
81
|
+
|
|
82
|
+
message = "Доставить по адресу: Москва, ул. Тверская, д. 13. Позвоните."
|
|
83
|
+
|
|
84
|
+
for item in detect_addresses(message):
|
|
85
|
+
print(item.text) # Москва, ул. Тверская, д. 13
|
|
86
|
+
print(item.span) # смещение в исходном сообщении
|
|
87
|
+
print(item.parsed) # ParsedAddress
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
Детектор консервативный: лучше пропустить слабый кандидат, чем принять номер
|
|
91
|
+
заказа или дату за адрес.
|
|
92
|
+
|
|
93
|
+
### Несколько адресов и CLI
|
|
94
|
+
|
|
95
|
+
```python
|
|
96
|
+
from address_normalizer import parse_many
|
|
97
|
+
|
|
98
|
+
results = parse_many(["Тверская 1", "Невский проспект 10"])
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
```bash
|
|
102
|
+
address-normalizer "СПб, Невский проспект 10, корп. 2"
|
|
103
|
+
printf '%s\n' "Тверская 1" "Ополченская 5-30" |
|
|
104
|
+
address-normalizer --jsonl
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
## Граница ответственности
|
|
108
|
+
|
|
109
|
+
Библиотека извлекает:
|
|
110
|
+
|
|
111
|
+
- индекс, регион, район, город и населённый пункт;
|
|
112
|
+
- улицу и тип улицы;
|
|
113
|
+
- дом, корпус, строение и квартиру;
|
|
114
|
+
- исходные смещения, неразобранный остаток, предупреждения и альтернативы.
|
|
115
|
+
|
|
116
|
+
Она не проверяет адрес по ФИАС/ГАР, не возвращает ID реестра, не исправляет
|
|
117
|
+
официальное написание и не геокодирует. После парсинга передайте поля в свой
|
|
118
|
+
актуальный resolver ФИАС/ГАР.
|
|
119
|
+
|
|
120
|
+
## Как это работает
|
|
121
|
+
|
|
122
|
+
Runtime — простой гибрид: токенизатор со смещениями, правила адресных маркеров и
|
|
123
|
+
чисел, компактный линейный sequence tagger для слов без маркеров, затем
|
|
124
|
+
детерминированная постобработка. Это не LLM и не нейросеть. Модель занимает
|
|
125
|
+
37 КБ; сетевых запросов и скрытых загрузок нет.
|
|
126
|
+
|
|
127
|
+
## Качество
|
|
128
|
+
|
|
129
|
+
Одна цифра «accuracy» здесь вводит в заблуждение, поэтому разные наборы
|
|
130
|
+
публикуются отдельно:
|
|
131
|
+
|
|
132
|
+
| Набор | Размер | Метрика | Результат |
|
|
133
|
+
| --- | ---: | --- | ---: |
|
|
134
|
+
| Историческая адресная выборка | 500 | exact component micro F1 | 95,9% |
|
|
135
|
+
| Шумные адресные фрагменты | 578 | span-overlap F1 | 58,7% |
|
|
136
|
+
| Чистые адреса по России | 100 000 | character-overlap F1 | 66,2% |
|
|
137
|
+
| Здания Москвы | 15 196 | exact component micro F1 | 85,4% |
|
|
138
|
+
|
|
139
|
+
Подробные определения, результаты по полям и все 500 строк с причинами ошибок:
|
|
140
|
+
[`benchmarks/README.md`](https://github.com/shigabeev/address-normalizer/blob/master/benchmarks/README.md).
|
|
141
|
+
|
|
142
|
+
Сильные поля — дом, корпус и строение. Слабее — административные уровни, точная
|
|
143
|
+
граница улицы, редкие сокращения и числовые хвосты без маркеров.
|
|
144
|
+
|
|
145
|
+
## Разработка
|
|
146
|
+
|
|
147
|
+
```bash
|
|
148
|
+
python -m pip install -e .
|
|
149
|
+
python -m pip install pytest
|
|
150
|
+
pytest
|
|
151
|
+
python tools/benchmark.py --check
|
|
152
|
+
```
|
|
153
|
+
|
|
154
|
+
Публичный API находится в `src/address_normalizer`, основные проверки — в
|
|
155
|
+
`tests`, воспроизводимый набор ошибок — в `benchmarks`.
|
|
156
|
+
|
|
157
|
+
## Лицензия
|
|
158
|
+
|
|
159
|
+
GNU GPL v3.0 only. Полный текст — в
|
|
160
|
+
[`LICENSE`](https://github.com/shigabeev/address-normalizer/blob/master/LICENSE).
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
address_normalizer/__init__.py,sha256=ROFSadrlA5nLMevxmoLV8K-_CCcLwgDL1HrjQNU4etk,591
|
|
2
|
+
address_normalizer/api.py,sha256=NgwgfI0EDBCTqMmwAmhUmKqxIizfbBfdyaYoop15wAE,2674
|
|
3
|
+
address_normalizer/cli.py,sha256=rrsR5p3nF4Y168Nc5x_JZcZ6dXWI7ma30qvLTytJs5U,1063
|
|
4
|
+
address_normalizer/detection.py,sha256=maLiGJ5aUcfMRwTxK-P3kHnMkLYIzv6UYbPJ2aKHC0U,16415
|
|
5
|
+
address_normalizer/normalization.py,sha256=cndOv9oBycwnX-cpLW4hn1w46xWQoUGf27VyID3fRqk,1721
|
|
6
|
+
address_normalizer/parser.py,sha256=DlbU_DYD4V7ZbleFWOqk6rF4dsBUilrSd4ArRwR9unk,24348
|
|
7
|
+
address_normalizer/py.typed,sha256=AbpHGcgLb-kRsJGnwFEktk7uzpZOCcBY74-YBdrKVGs,1
|
|
8
|
+
address_normalizer/tagger.py,sha256=52tnrxE9v01BLx4qwMr6RqSBgMFyKQJGrHFeMBL87Hs,5083
|
|
9
|
+
address_normalizer/tokenizer.py,sha256=dG2iOOFdPU9BhH_dy_URVixQLZ_Js8RbuK0sqq1FtJ0,851
|
|
10
|
+
address_normalizer/types.py,sha256=1fMhQOoUB4TTflIPP_ux_3_4hNHqVgoOT5SGJ9lestc,7014
|
|
11
|
+
address_normalizer/data/model.json,sha256=h1YxKwoU_an5HyGA6UUC0GyC4mN1jd_BQw0G1oAllfI,37120
|
|
12
|
+
address_normalizer-2.0.0a2.dist-info/licenses/LICENSE,sha256=5X8cMguM-HmKfS_4Om-eBqM6A1hfbgZf6pfx2G24QFI,35150
|
|
13
|
+
address_normalizer-2.0.0a2.dist-info/METADATA,sha256=VWel8PDf6gS5G42JujdDC_CEIKrCnF737kUyo47dwjg,6932
|
|
14
|
+
address_normalizer-2.0.0a2.dist-info/WHEEL,sha256=K260EYznzXsJYBQGqmI8VTxEdiZYNvDZwW9cBh9-_MA,91
|
|
15
|
+
address_normalizer-2.0.0a2.dist-info/entry_points.txt,sha256=-GmZ3_eT_BZJJ5eg6yljHk3ovXAUmVLP9SR_GFfFXmc,67
|
|
16
|
+
address_normalizer-2.0.0a2.dist-info/top_level.txt,sha256=IydqeSbEW7sw5jVAkGYfhu6ExhhJOcOtqaeesp5nu_g,19
|
|
17
|
+
address_normalizer-2.0.0a2.dist-info/RECORD,,
|