repostal 0.1.0__tar.gz
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.
- repostal-0.1.0/LICENSE +21 -0
- repostal-0.1.0/PKG-INFO +102 -0
- repostal-0.1.0/README.md +80 -0
- repostal-0.1.0/pyproject.toml +40 -0
- repostal-0.1.0/src/repostal/__init__.py +24 -0
- repostal-0.1.0/src/repostal/bundle.py +61 -0
- repostal-0.1.0/src/repostal/cli.py +47 -0
- repostal-0.1.0/src/repostal/encode.py +60 -0
- repostal-0.1.0/src/repostal/parser.py +94 -0
- repostal-0.1.0/src/repostal/results.py +37 -0
- repostal-0.1.0/tests/test_parse.py +42 -0
repostal-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 brightertiger
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
repostal-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: repostal
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Address parser: text in, labelled address parts out (ONNX Runtime on CPU)
|
|
5
|
+
Project-URL: Repository, https://github.com/brightertiger/repostal
|
|
6
|
+
Project-URL: Model, https://huggingface.co/brightertiger/repostal-small
|
|
7
|
+
Project-URL: Large model, https://huggingface.co/brightertiger/repostal-large
|
|
8
|
+
Author: Ujjwal Singh Rao
|
|
9
|
+
License-Expression: MIT
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
Keywords: address,geocoding,multilingual,onnx,parser
|
|
12
|
+
Classifier: Development Status :: 3 - Alpha
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Topic :: Text Processing :: Linguistic
|
|
16
|
+
Requires-Python: >=3.9
|
|
17
|
+
Requires-Dist: huggingface-hub>=0.20
|
|
18
|
+
Requires-Dist: numpy>=1.21
|
|
19
|
+
Requires-Dist: onnxruntime>=1.16
|
|
20
|
+
Requires-Dist: tokenizers>=0.21.2
|
|
21
|
+
Description-Content-Type: text/markdown
|
|
22
|
+
|
|
23
|
+
# repostal
|
|
24
|
+
|
|
25
|
+
Address parser: text in, labelled address parts out (house number, road, unit, postcode,
|
|
26
|
+
city, state, country, ...), in many languages and scripts, robust to typos and missing
|
|
27
|
+
commas. A small transformer runs on CPU with ONNX Runtime; no torch. The weights are
|
|
28
|
+
downloaded from the Hugging Face Hub on first use and cached.
|
|
29
|
+
|
|
30
|
+
## Install
|
|
31
|
+
|
|
32
|
+
```
|
|
33
|
+
pip install repostal
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
## Quickstart
|
|
37
|
+
|
|
38
|
+
```python
|
|
39
|
+
import repostal
|
|
40
|
+
|
|
41
|
+
parser = repostal.Parser() # repostal-small, downloaded once
|
|
42
|
+
r = parser.parse("221B Baker Street, London NW1 6XE, UK")
|
|
43
|
+
r.to_dict() # {"house_number": "221B", "road": "Baker Street", "city": "London", ...}
|
|
44
|
+
r.get("city") # "London", or None
|
|
45
|
+
r.components # Component(label, value, start, end, score), in text order
|
|
46
|
+
r.truncated # True if the text was longer than the model reads
|
|
47
|
+
parser.labels # label names, from the model
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
`value` is always `text[start:end]`; a component is a run of words with the same label,
|
|
51
|
+
including the separators between them; `score` is the lowest label probability among its
|
|
52
|
+
words. `repostal.parse(text)` is a shortcut on a shared default parser.
|
|
53
|
+
|
|
54
|
+
Models: `Parser("small")` (default, 82 MB), `Parser("large")` (more accurate, slower), or
|
|
55
|
+
`Parser("/path/to/bundle")` for a local model directory. Options are keyword-only:
|
|
56
|
+
`Parser(model, revision=None, threads=None, cache_dir=None)`.
|
|
57
|
+
|
|
58
|
+
## Batches and threads
|
|
59
|
+
|
|
60
|
+
```python
|
|
61
|
+
results = parser.parse_batch(texts) # same order as texts
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
`parse_batch` runs the addresses in parallel on `threads` threads (None: all cores
|
|
65
|
+
available to the process). Each address runs alone, so a result never depends on the
|
|
66
|
+
rest of the list, and `parse_batch(texts)` equals `[parse(t) for t in texts]`. One
|
|
67
|
+
`Parser` can be shared across threads.
|
|
68
|
+
|
|
69
|
+
## Command line
|
|
70
|
+
|
|
71
|
+
```
|
|
72
|
+
repostal parse "221B Baker Street, London"
|
|
73
|
+
repostal parse --model large < addresses.txt # one address per line in, JSON lines out
|
|
74
|
+
repostal download [small|large] # prints the cached model directory
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
## Results
|
|
78
|
+
|
|
79
|
+
Four-field accuracy (city, state, country and postcode all right), %, through this
|
|
80
|
+
package, beside libpostal on the same rows. noisy3: typing noise training never saw;
|
|
81
|
+
fresh: generated addresses from held-out regions; real: 5,000 real places in six text
|
|
82
|
+
forms. Details and the rest of the numbers: the model cards and
|
|
83
|
+
[docs/results.md](https://github.com/brightertiger/repostal/blob/main/docs/results.md).
|
|
84
|
+
|
|
85
|
+
<!-- training.score_bundle on each released bundle (small: 20,000 rows per set, large:
|
|
86
|
+
5,000; real: all 30,000); libpostal on the small model's rows. Sources in the model cards. -->
|
|
87
|
+
|
|
88
|
+
| Model | clean | noisy3 | fresh | real (strict / lenient) | ms per address | download |
|
|
89
|
+
|---|---:|---:|---:|---:|---:|---:|
|
|
90
|
+
| repostal-small (default) | 97.20 | 75.21 | 93.38 | 81.89 / 83.79 | 6.7 | 82 MB |
|
|
91
|
+
| repostal-large | 97.94 | 79.86 | 94.34 | 84.19 / 85.77 | 78 | 524 MB |
|
|
92
|
+
| libpostal (Senzing model) | 98.66 | 51.84 | 81.92 | 73.31 / 74.45 | 0.18 | |
|
|
93
|
+
|
|
94
|
+
Median time on one core. libpostal is far faster and better on clean text in its own
|
|
95
|
+
training format; repostal is ahead on noisy, generated and real addresses. Japanese real
|
|
96
|
+
addresses are a known weak spot (see the model cards).
|
|
97
|
+
|
|
98
|
+
## Licence
|
|
99
|
+
|
|
100
|
+
Code: MIT. Weights: CC-BY-4.0, with attribution to OpenStreetMap contributors,
|
|
101
|
+
OpenAddresses, GeoNames, libpostal and Senzing (the training data's sources; see the model
|
|
102
|
+
cards on the Hub).
|
repostal-0.1.0/README.md
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
# repostal
|
|
2
|
+
|
|
3
|
+
Address parser: text in, labelled address parts out (house number, road, unit, postcode,
|
|
4
|
+
city, state, country, ...), in many languages and scripts, robust to typos and missing
|
|
5
|
+
commas. A small transformer runs on CPU with ONNX Runtime; no torch. The weights are
|
|
6
|
+
downloaded from the Hugging Face Hub on first use and cached.
|
|
7
|
+
|
|
8
|
+
## Install
|
|
9
|
+
|
|
10
|
+
```
|
|
11
|
+
pip install repostal
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
## Quickstart
|
|
15
|
+
|
|
16
|
+
```python
|
|
17
|
+
import repostal
|
|
18
|
+
|
|
19
|
+
parser = repostal.Parser() # repostal-small, downloaded once
|
|
20
|
+
r = parser.parse("221B Baker Street, London NW1 6XE, UK")
|
|
21
|
+
r.to_dict() # {"house_number": "221B", "road": "Baker Street", "city": "London", ...}
|
|
22
|
+
r.get("city") # "London", or None
|
|
23
|
+
r.components # Component(label, value, start, end, score), in text order
|
|
24
|
+
r.truncated # True if the text was longer than the model reads
|
|
25
|
+
parser.labels # label names, from the model
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
`value` is always `text[start:end]`; a component is a run of words with the same label,
|
|
29
|
+
including the separators between them; `score` is the lowest label probability among its
|
|
30
|
+
words. `repostal.parse(text)` is a shortcut on a shared default parser.
|
|
31
|
+
|
|
32
|
+
Models: `Parser("small")` (default, 82 MB), `Parser("large")` (more accurate, slower), or
|
|
33
|
+
`Parser("/path/to/bundle")` for a local model directory. Options are keyword-only:
|
|
34
|
+
`Parser(model, revision=None, threads=None, cache_dir=None)`.
|
|
35
|
+
|
|
36
|
+
## Batches and threads
|
|
37
|
+
|
|
38
|
+
```python
|
|
39
|
+
results = parser.parse_batch(texts) # same order as texts
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
`parse_batch` runs the addresses in parallel on `threads` threads (None: all cores
|
|
43
|
+
available to the process). Each address runs alone, so a result never depends on the
|
|
44
|
+
rest of the list, and `parse_batch(texts)` equals `[parse(t) for t in texts]`. One
|
|
45
|
+
`Parser` can be shared across threads.
|
|
46
|
+
|
|
47
|
+
## Command line
|
|
48
|
+
|
|
49
|
+
```
|
|
50
|
+
repostal parse "221B Baker Street, London"
|
|
51
|
+
repostal parse --model large < addresses.txt # one address per line in, JSON lines out
|
|
52
|
+
repostal download [small|large] # prints the cached model directory
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
## Results
|
|
56
|
+
|
|
57
|
+
Four-field accuracy (city, state, country and postcode all right), %, through this
|
|
58
|
+
package, beside libpostal on the same rows. noisy3: typing noise training never saw;
|
|
59
|
+
fresh: generated addresses from held-out regions; real: 5,000 real places in six text
|
|
60
|
+
forms. Details and the rest of the numbers: the model cards and
|
|
61
|
+
[docs/results.md](https://github.com/brightertiger/repostal/blob/main/docs/results.md).
|
|
62
|
+
|
|
63
|
+
<!-- training.score_bundle on each released bundle (small: 20,000 rows per set, large:
|
|
64
|
+
5,000; real: all 30,000); libpostal on the small model's rows. Sources in the model cards. -->
|
|
65
|
+
|
|
66
|
+
| Model | clean | noisy3 | fresh | real (strict / lenient) | ms per address | download |
|
|
67
|
+
|---|---:|---:|---:|---:|---:|---:|
|
|
68
|
+
| repostal-small (default) | 97.20 | 75.21 | 93.38 | 81.89 / 83.79 | 6.7 | 82 MB |
|
|
69
|
+
| repostal-large | 97.94 | 79.86 | 94.34 | 84.19 / 85.77 | 78 | 524 MB |
|
|
70
|
+
| libpostal (Senzing model) | 98.66 | 51.84 | 81.92 | 73.31 / 74.45 | 0.18 | |
|
|
71
|
+
|
|
72
|
+
Median time on one core. libpostal is far faster and better on clean text in its own
|
|
73
|
+
training format; repostal is ahead on noisy, generated and real addresses. Japanese real
|
|
74
|
+
addresses are a known weak spot (see the model cards).
|
|
75
|
+
|
|
76
|
+
## Licence
|
|
77
|
+
|
|
78
|
+
Code: MIT. Weights: CC-BY-4.0, with attribution to OpenStreetMap contributors,
|
|
79
|
+
OpenAddresses, GeoNames, libpostal and Senzing (the training data's sources; see the model
|
|
80
|
+
cards on the Hub).
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "repostal"
|
|
7
|
+
dynamic = ["version"]
|
|
8
|
+
description = "Address parser: text in, labelled address parts out (ONNX Runtime on CPU)"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = "MIT"
|
|
11
|
+
license-files = ["LICENSE"]
|
|
12
|
+
authors = [{name = "Ujjwal Singh Rao"}]
|
|
13
|
+
keywords = ["address", "parser", "geocoding", "multilingual", "onnx"]
|
|
14
|
+
classifiers = [
|
|
15
|
+
"Development Status :: 3 - Alpha",
|
|
16
|
+
"Intended Audience :: Developers",
|
|
17
|
+
"Programming Language :: Python :: 3",
|
|
18
|
+
"Topic :: Text Processing :: Linguistic",
|
|
19
|
+
]
|
|
20
|
+
requires-python = ">=3.9"
|
|
21
|
+
dependencies = [
|
|
22
|
+
"huggingface_hub>=0.20",
|
|
23
|
+
"numpy>=1.21",
|
|
24
|
+
"onnxruntime>=1.16",
|
|
25
|
+
"tokenizers>=0.21.2",
|
|
26
|
+
]
|
|
27
|
+
|
|
28
|
+
[project.urls]
|
|
29
|
+
Repository = "https://github.com/brightertiger/repostal"
|
|
30
|
+
Model = "https://huggingface.co/brightertiger/repostal-small"
|
|
31
|
+
"Large model" = "https://huggingface.co/brightertiger/repostal-large"
|
|
32
|
+
|
|
33
|
+
[project.scripts]
|
|
34
|
+
repostal = "repostal.cli:main"
|
|
35
|
+
|
|
36
|
+
[tool.hatch.version]
|
|
37
|
+
path = "src/repostal/__init__.py"
|
|
38
|
+
|
|
39
|
+
[tool.hatch.build.targets.wheel]
|
|
40
|
+
packages = ["src/repostal"]
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
"""repostal: address text in, labelled address parts out.
|
|
2
|
+
|
|
3
|
+
>>> import repostal
|
|
4
|
+
>>> repostal.Parser().parse("221B Baker Street, London").to_dict()
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
from functools import lru_cache
|
|
9
|
+
|
|
10
|
+
from .parser import Parser
|
|
11
|
+
from .results import Component, Parsed
|
|
12
|
+
|
|
13
|
+
__all__ = ["Component", "Parsed", "Parser", "parse"]
|
|
14
|
+
__version__ = "0.1.0"
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
@lru_cache(maxsize=None)
|
|
18
|
+
def _default() -> Parser:
|
|
19
|
+
return Parser()
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def parse(text: str) -> Parsed:
|
|
23
|
+
"""Parse one address with the default model, loaded on first use."""
|
|
24
|
+
return _default().parse(text)
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
"""Find and open a model bundle: a local directory, or a Hugging Face Hub repository that
|
|
2
|
+
huggingface_hub downloads once and caches.
|
|
3
|
+
|
|
4
|
+
A bundle (format 1) holds `model.onnx`, `tokenizer.json` and `repostal.json`; everything
|
|
5
|
+
model-specific (labels, word pattern, length limit) is read from it, never from code.
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import json
|
|
10
|
+
import os
|
|
11
|
+
|
|
12
|
+
FORMAT = 1
|
|
13
|
+
FILES = ["model.onnx", "tokenizer.json", "repostal.json"]
|
|
14
|
+
|
|
15
|
+
# Model name -> (Hub repository, pinned commit), so an installed version always runs the
|
|
16
|
+
# same weights.
|
|
17
|
+
MODELS: dict[str, tuple[str, str]] = {
|
|
18
|
+
"small": ("brightertiger/repostal-small", "5173ecdb70cec3887913b828df8000a1a34dbd53"),
|
|
19
|
+
"large": ("brightertiger/repostal-large", "7eb0313a81fd16b14ec45a723c96a344713df5fd"),
|
|
20
|
+
}
|
|
21
|
+
DEFAULT = "small"
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _is_path(model: str) -> bool:
|
|
25
|
+
"""True for anything that can only be meant as a directory, never a Hub repo id."""
|
|
26
|
+
return (os.path.isabs(model) or model.startswith((".", "~")) or model.count("/") > 1
|
|
27
|
+
or "\\" in model)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def resolve(model: str | None = None, *, revision: str | None = None,
|
|
31
|
+
cache_dir: str | None = None) -> str:
|
|
32
|
+
"""Local directory of `model`: a bundle directory, a name in MODELS or a Hub repo id."""
|
|
33
|
+
model = model or DEFAULT
|
|
34
|
+
if os.path.isdir(os.path.expanduser(model)):
|
|
35
|
+
return os.path.expanduser(model)
|
|
36
|
+
if _is_path(model):
|
|
37
|
+
raise FileNotFoundError(f"no bundle directory at {model}")
|
|
38
|
+
repo, pinned = MODELS.get(model, (model, None))
|
|
39
|
+
if "/" not in repo:
|
|
40
|
+
raise ValueError(f"{model!r} is not a bundle directory or a known model "
|
|
41
|
+
f"({', '.join(MODELS)})")
|
|
42
|
+
from huggingface_hub import snapshot_download # only needed for Hub models
|
|
43
|
+
|
|
44
|
+
kw = dict(revision=revision or pinned, cache_dir=cache_dir, allow_patterns=FILES)
|
|
45
|
+
try: # a complete cached snapshot needs no network
|
|
46
|
+
path = snapshot_download(repo, local_files_only=True, **kw)
|
|
47
|
+
if all(os.path.isfile(os.path.join(path, f)) for f in FILES):
|
|
48
|
+
return path
|
|
49
|
+
except OSError: # not cached (LocalEntryNotFoundError)
|
|
50
|
+
pass
|
|
51
|
+
return snapshot_download(repo, **kw) # downloads, or repairs a partial snapshot
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def read_meta(path: str) -> dict:
|
|
55
|
+
"""The bundle's repostal.json, after checking its format number."""
|
|
56
|
+
with open(os.path.join(path, "repostal.json"), encoding="utf-8") as f:
|
|
57
|
+
meta = json.load(f)
|
|
58
|
+
if meta.get("format") != FORMAT:
|
|
59
|
+
raise ValueError(f"{path}: bundle format {meta.get('format')!r}, this repostal reads "
|
|
60
|
+
f"format {FORMAT}; upgrade repostal or use a matching bundle")
|
|
61
|
+
return meta
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
"""Command line.
|
|
2
|
+
|
|
3
|
+
repostal parse "221B Baker Street, London" # or one address per line on stdin
|
|
4
|
+
repostal download [model] # fetch a bundle, print its directory
|
|
5
|
+
|
|
6
|
+
`parse` prints one JSON object per address: text, components, truncated.
|
|
7
|
+
"""
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import argparse
|
|
11
|
+
import dataclasses
|
|
12
|
+
import json
|
|
13
|
+
import sys
|
|
14
|
+
from itertools import islice
|
|
15
|
+
|
|
16
|
+
from .bundle import resolve
|
|
17
|
+
from .parser import Parser
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def main(argv: list[str] | None = None) -> None:
|
|
21
|
+
ap = argparse.ArgumentParser(prog="repostal", description=__doc__.split("\n\n")[0])
|
|
22
|
+
sub = ap.add_subparsers(dest="command", required=True)
|
|
23
|
+
p = sub.add_parser("parse", help="parse addresses to JSON lines")
|
|
24
|
+
p.add_argument("text", nargs="*", help="addresses (default: lines on stdin)")
|
|
25
|
+
p.add_argument("--model", help="bundle directory, model name or Hub repo id")
|
|
26
|
+
p.add_argument("--threads", type=int, help="default: all available cores")
|
|
27
|
+
d = sub.add_parser("download", help="download a model bundle and print its directory")
|
|
28
|
+
d.add_argument("model", nargs="?")
|
|
29
|
+
for q in (p, d):
|
|
30
|
+
q.add_argument("--revision")
|
|
31
|
+
q.add_argument("--cache-dir")
|
|
32
|
+
a = ap.parse_args(argv)
|
|
33
|
+
try:
|
|
34
|
+
if a.command == "download":
|
|
35
|
+
print(resolve(a.model, revision=a.revision, cache_dir=a.cache_dir))
|
|
36
|
+
return
|
|
37
|
+
parser = Parser(a.model, revision=a.revision, threads=a.threads, cache_dir=a.cache_dir)
|
|
38
|
+
except (OSError, ValueError) as e: # no bundle: a message, not a traceback
|
|
39
|
+
ap.exit(1, f"repostal: {e}\n")
|
|
40
|
+
lines = iter(a.text) if a.text else (line.rstrip("\r\n") for line in sys.stdin)
|
|
41
|
+
while chunk := list(islice(lines, 1024)):
|
|
42
|
+
for r in parser.parse_batch(chunk):
|
|
43
|
+
print(json.dumps(dataclasses.asdict(r), ensure_ascii=False))
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
if __name__ == "__main__":
|
|
47
|
+
main()
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
"""Text to model input, exactly as the trainer built it.
|
|
2
|
+
|
|
3
|
+
The trainer splits text into repostal's words and separators, then encodes those as
|
|
4
|
+
pre-tokenized input with the model's tokenizer. Here the split is the bundle's word
|
|
5
|
+
pattern run by a tokenizers `Split` pre-tokenizer on the raw text (so no splitting code
|
|
6
|
+
of our own), and the encoding is the bundle's unchanged tokenizer. The bundle step checks
|
|
7
|
+
that ids and word spans equal the trainer's on the test sets.
|
|
8
|
+
"""
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import os
|
|
12
|
+
import unicodedata
|
|
13
|
+
from dataclasses import dataclass
|
|
14
|
+
|
|
15
|
+
from tokenizers import Regex, Tokenizer, pre_tokenizers
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@dataclass(frozen=True)
|
|
19
|
+
class Encoded:
|
|
20
|
+
"""Model input for one text: piece ids, then per word its character span and the
|
|
21
|
+
index of its first piece (the piece whose prediction is the word's label)."""
|
|
22
|
+
|
|
23
|
+
ids: list[int]
|
|
24
|
+
spans: list[tuple[int, int]]
|
|
25
|
+
first: list[int]
|
|
26
|
+
truncated: bool
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def is_word(token: str) -> bool:
|
|
30
|
+
"""False for separators. The split yields a separator only as a single character that
|
|
31
|
+
is not a letter, mark or digit; words never are such a character."""
|
|
32
|
+
return len(token) > 1 or unicodedata.category(token)[0] in "LMN"
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class Encoder:
|
|
36
|
+
"""Encodes texts with a bundle's word pattern and tokenizer."""
|
|
37
|
+
|
|
38
|
+
def __init__(self, path: str, meta: dict):
|
|
39
|
+
self.tokenizer = Tokenizer.from_file(os.path.join(path, "tokenizer.json"))
|
|
40
|
+
self.tokenizer.no_padding() # a tokenizer.json may carry padding; rows run unpadded
|
|
41
|
+
words = meta["words"]
|
|
42
|
+
self.split = pre_tokenizers.Sequence([
|
|
43
|
+
pre_tokenizers.Split(Regex(words["space"]), "removed"),
|
|
44
|
+
pre_tokenizers.Split(Regex(words["token"]), "isolated"),
|
|
45
|
+
])
|
|
46
|
+
|
|
47
|
+
def encode_batch(self, texts: list[str]) -> list[Encoded]:
|
|
48
|
+
tokens = [self.split.pre_tokenize_str(t) for t in texts]
|
|
49
|
+
encs = self.tokenizer.encode_batch([[s for s, _ in ts] for ts in tokens],
|
|
50
|
+
is_pretokenized=True)
|
|
51
|
+
out = []
|
|
52
|
+
for ts, e in zip(tokens, encs):
|
|
53
|
+
spans, first, prev = [], [], None
|
|
54
|
+
for i, w in enumerate(e.word_ids):
|
|
55
|
+
if w is not None and w != prev and is_word(ts[w][0]):
|
|
56
|
+
spans.append(ts[w][1])
|
|
57
|
+
first.append(i)
|
|
58
|
+
prev = w
|
|
59
|
+
out.append(Encoded(e.ids, spans, first, bool(e.overflowing)))
|
|
60
|
+
return out
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
"""The parser: a bundle's tokenizer and ONNX model on CPU, word labels to components."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import os
|
|
5
|
+
import threading
|
|
6
|
+
from concurrent.futures import ThreadPoolExecutor
|
|
7
|
+
|
|
8
|
+
import numpy as np
|
|
9
|
+
|
|
10
|
+
from .bundle import read_meta, resolve
|
|
11
|
+
from .encode import Encoded, Encoder
|
|
12
|
+
from .results import Component, Parsed
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def _cores() -> int:
|
|
16
|
+
"""Cores this process may run on."""
|
|
17
|
+
if hasattr(os, "sched_getaffinity"):
|
|
18
|
+
return len(os.sched_getaffinity(0))
|
|
19
|
+
return os.cpu_count() or 1
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class Parser:
|
|
23
|
+
"""Labels the parts of address texts. One Parser is safe to share across threads.
|
|
24
|
+
|
|
25
|
+
model: a bundle directory, a model name, or a Hugging Face Hub repo id (None: the
|
|
26
|
+
default model). threads: how many addresses `parse_batch` runs at once (None: all
|
|
27
|
+
cores available to the process).
|
|
28
|
+
|
|
29
|
+
Every address runs through the model alone, unpadded, so its result never depends on
|
|
30
|
+
what else is in the list (int8 models quantise activations with one scale per run).
|
|
31
|
+
"""
|
|
32
|
+
|
|
33
|
+
def __init__(self, model: str | None = None, *, revision: str | None = None,
|
|
34
|
+
threads: int | None = None, cache_dir: str | None = None):
|
|
35
|
+
path = resolve(model, revision=revision, cache_dir=cache_dir)
|
|
36
|
+
meta = read_meta(path)
|
|
37
|
+
self.labels: tuple[str, ...] = tuple(meta["labels"])
|
|
38
|
+
self.model = f"{meta['name']} {meta['version']}"
|
|
39
|
+
self._encoder = Encoder(path, meta)
|
|
40
|
+
import onnxruntime as ort # here, not at the top: `import repostal` stays light
|
|
41
|
+
|
|
42
|
+
options = ort.SessionOptions()
|
|
43
|
+
options.intra_op_num_threads = options.inter_op_num_threads = 1
|
|
44
|
+
self._session = ort.InferenceSession(os.path.join(path, "model.onnx"), options,
|
|
45
|
+
providers=["CPUExecutionProvider"])
|
|
46
|
+
self._inputs = [i.name for i in self._session.get_inputs()]
|
|
47
|
+
self._threads = threads or _cores()
|
|
48
|
+
self._pool: ThreadPoolExecutor | None = None # made by the first parse_batch
|
|
49
|
+
self._lock = threading.Lock()
|
|
50
|
+
|
|
51
|
+
def parse(self, text: str) -> Parsed:
|
|
52
|
+
"""Parse one address."""
|
|
53
|
+
return self._row(text, self._encoder.encode_batch([_checked(text)])[0])
|
|
54
|
+
|
|
55
|
+
def parse_batch(self, texts: list[str]) -> list[Parsed]:
|
|
56
|
+
"""Parse many addresses on the parser's threads; results are in input order and
|
|
57
|
+
equal to `parse` of each text."""
|
|
58
|
+
texts = [_checked(t) for t in texts]
|
|
59
|
+
with self._lock:
|
|
60
|
+
if self._pool is None:
|
|
61
|
+
self._pool = ThreadPoolExecutor(self._threads, thread_name_prefix="repostal")
|
|
62
|
+
return list(self._pool.map(self._row, texts, self._encoder.encode_batch(texts)))
|
|
63
|
+
|
|
64
|
+
def _row(self, text: str, enc: Encoded) -> Parsed:
|
|
65
|
+
if not enc.spans:
|
|
66
|
+
return Parsed(text, (), enc.truncated)
|
|
67
|
+
ids = np.array([enc.ids], np.int64)
|
|
68
|
+
feed = {"input_ids": ids, "attention_mask": np.ones_like(ids),
|
|
69
|
+
"token_type_ids": np.zeros_like(ids)}
|
|
70
|
+
logits = self._session.run(["logits"], {n: feed[n] for n in self._inputs})[0][0]
|
|
71
|
+
z = np.exp(logits - logits.max(-1, keepdims=True))
|
|
72
|
+
return _parsed(text, enc, z / z.sum(-1, keepdims=True), self.labels)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _checked(text) -> str:
|
|
76
|
+
if not isinstance(text, str):
|
|
77
|
+
raise TypeError(f"expected str, got {type(text).__name__}")
|
|
78
|
+
return text
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _parsed(text: str, enc: Encoded, probs: np.ndarray, labels: tuple[str, ...]) -> Parsed:
|
|
82
|
+
"""Join adjacent words with the same label into components. A component runs from its
|
|
83
|
+
first word's start to its last word's end, so separators between its words stay in it."""
|
|
84
|
+
p = probs[enc.first]
|
|
85
|
+
best = p.argmax(-1)
|
|
86
|
+
runs: list[list] = [] # [label id, start, end, score]
|
|
87
|
+
for (start, end), lab, score in zip(enc.spans, best, p[np.arange(len(best)), best]):
|
|
88
|
+
if runs and runs[-1][0] == lab:
|
|
89
|
+
runs[-1][2] = end
|
|
90
|
+
runs[-1][3] = min(runs[-1][3], score)
|
|
91
|
+
else:
|
|
92
|
+
runs.append([lab, start, end, score])
|
|
93
|
+
comps = tuple(Component(labels[lab], text[s:e], s, e, float(sc)) for lab, s, e, sc in runs)
|
|
94
|
+
return Parsed(text, comps, enc.truncated)
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
"""Result types. Frozen dataclasses, so fields can be added without breaking callers."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from dataclasses import dataclass
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
@dataclass(frozen=True)
|
|
8
|
+
class Component:
|
|
9
|
+
"""One labelled part of an address; `value` is exactly `text[start:end]` of the input.
|
|
10
|
+
`score` is the lowest label probability among the component's words."""
|
|
11
|
+
|
|
12
|
+
label: str
|
|
13
|
+
value: str
|
|
14
|
+
start: int
|
|
15
|
+
end: int
|
|
16
|
+
score: float
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@dataclass(frozen=True)
|
|
20
|
+
class Parsed:
|
|
21
|
+
"""A parsed address: the input text, its components in text order, and whether the
|
|
22
|
+
text was longer than the model reads (words past that point get no label)."""
|
|
23
|
+
|
|
24
|
+
text: str
|
|
25
|
+
components: tuple[Component, ...]
|
|
26
|
+
truncated: bool = False
|
|
27
|
+
|
|
28
|
+
def to_dict(self) -> dict[str, str]:
|
|
29
|
+
"""Label to value, keeping the first component of each label."""
|
|
30
|
+
out: dict[str, str] = {}
|
|
31
|
+
for c in self.components:
|
|
32
|
+
out.setdefault(c.label, c.value)
|
|
33
|
+
return out
|
|
34
|
+
|
|
35
|
+
def get(self, label: str) -> str | None:
|
|
36
|
+
"""Value of the first component with this label, or None."""
|
|
37
|
+
return self.to_dict().get(label)
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
"""Behaviour test against a real model: the default model (downloaded on first use), or a
|
|
2
|
+
local bundle given as REPOSTAL_TEST_BUNDLE=/path/to/bundle pytest"""
|
|
3
|
+
import os
|
|
4
|
+
from concurrent.futures import ThreadPoolExecutor
|
|
5
|
+
|
|
6
|
+
import pytest
|
|
7
|
+
|
|
8
|
+
import repostal
|
|
9
|
+
|
|
10
|
+
BUNDLE = os.environ.get("REPOSTAL_TEST_BUNDLE") # None: the default model
|
|
11
|
+
|
|
12
|
+
TEXTS = [
|
|
13
|
+
"221B Baker Street, London NW1 6XE, UK",
|
|
14
|
+
"Lerchenrain 20, 8046 Zürich, ZH",
|
|
15
|
+
"ул.Ленина 12, кв. 5, Москва, 101000",
|
|
16
|
+
"東京都新宿区西新宿2-8-1",
|
|
17
|
+
"100 Main St.,Suite #4B , Springfield IL 62701 , USA",
|
|
18
|
+
"วัดช่องเขาเทพประสิทธิ์, ระนอง, Thailand",
|
|
19
|
+
"شارع الملك فهد، الرياض 12271",
|
|
20
|
+
"",
|
|
21
|
+
" ",
|
|
22
|
+
"Hauptstraße 5 " * 300, # longer than the model reads
|
|
23
|
+
]
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def test_parse():
|
|
27
|
+
parser = repostal.Parser(BUNDLE)
|
|
28
|
+
single = [parser.parse(t) for t in TEXTS]
|
|
29
|
+
for t, r in zip(TEXTS, single):
|
|
30
|
+
assert r.text == t
|
|
31
|
+
assert [c.start for c in r.components] == sorted(c.start for c in r.components)
|
|
32
|
+
for c in r.components:
|
|
33
|
+
assert c.value == t[c.start:c.end] == c.value.strip()
|
|
34
|
+
assert c.label in parser.labels and 0 < c.score <= 1
|
|
35
|
+
assert single[7].components == single[8].components == ()
|
|
36
|
+
assert single[-1].truncated and not single[0].truncated
|
|
37
|
+
|
|
38
|
+
assert parser.parse_batch(TEXTS) == single
|
|
39
|
+
with ThreadPoolExecutor(4) as pool:
|
|
40
|
+
assert list(pool.map(parser.parse, TEXTS * 4)) == single * 4
|
|
41
|
+
with pytest.raises(TypeError):
|
|
42
|
+
parser.parse(None)
|