repostal 0.1.0.dev0__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.dev0/.gitignore +10 -0
- repostal-0.1.0.dev0/LICENSE +21 -0
- repostal-0.1.0.dev0/PKG-INFO +67 -0
- repostal-0.1.0.dev0/README.md +48 -0
- repostal-0.1.0.dev0/pyproject.toml +32 -0
- repostal-0.1.0.dev0/src/repostal/__init__.py +24 -0
- repostal-0.1.0.dev0/src/repostal/bundle.py +46 -0
- repostal-0.1.0.dev0/src/repostal/cli.py +47 -0
- repostal-0.1.0.dev0/src/repostal/encode.py +60 -0
- repostal-0.1.0.dev0/src/repostal/parser.py +87 -0
- repostal-0.1.0.dev0/src/repostal/results.py +37 -0
- repostal-0.1.0.dev0/tests/test_parse.py +42 -0
|
@@ -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.
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: repostal
|
|
3
|
+
Version: 0.1.0.dev0
|
|
4
|
+
Summary: Address parser: text in, labelled address parts out (ONNX Runtime on CPU)
|
|
5
|
+
Author: Ujjwal Singh Rao
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
License-File: LICENSE
|
|
8
|
+
Keywords: address,geocoding,multilingual,onnx,parser
|
|
9
|
+
Classifier: Development Status :: 2 - Pre-Alpha
|
|
10
|
+
Classifier: Intended Audience :: Developers
|
|
11
|
+
Classifier: Programming Language :: Python :: 3
|
|
12
|
+
Classifier: Topic :: Text Processing :: Linguistic
|
|
13
|
+
Requires-Python: >=3.9
|
|
14
|
+
Requires-Dist: huggingface-hub>=0.20
|
|
15
|
+
Requires-Dist: numpy>=1.21
|
|
16
|
+
Requires-Dist: onnxruntime>=1.16
|
|
17
|
+
Requires-Dist: tokenizers>=0.15
|
|
18
|
+
Description-Content-Type: text/markdown
|
|
19
|
+
|
|
20
|
+
# repostal
|
|
21
|
+
|
|
22
|
+
Address parser: text in, labelled address parts out. Runs on CPU with ONNX Runtime; no
|
|
23
|
+
torch. The package holds no weights: it loads a model bundle from a local directory or
|
|
24
|
+
downloads one from the Hugging Face Hub once and caches it.
|
|
25
|
+
|
|
26
|
+
## Install
|
|
27
|
+
|
|
28
|
+
```
|
|
29
|
+
pip install repostal
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
This is a pre-release: no model is published yet, so `Parser()` needs a local bundle
|
|
33
|
+
directory (made by `python -m training.bundle` in the repository). The first full
|
|
34
|
+
release will download its model on first use.
|
|
35
|
+
|
|
36
|
+
## Python
|
|
37
|
+
|
|
38
|
+
```python
|
|
39
|
+
import repostal
|
|
40
|
+
|
|
41
|
+
parser = repostal.Parser("/path/to/bundle") # or a model name / Hub repo id
|
|
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
|
+
|
|
48
|
+
results = parser.parse_batch(texts) # same order as texts, on the parser's threads
|
|
49
|
+
parser.labels # label names, from the bundle
|
|
50
|
+
parser.model # bundle name and version
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
`value` is always `text[start:end]`; a component is a run of words with the same label,
|
|
54
|
+
including the separators between them. `score` is the lowest label probability among its
|
|
55
|
+
words. Options are keyword-only: `Parser(model, revision=None, threads=None,
|
|
56
|
+
cache_dir=None)`. `threads` is how many addresses `parse_batch` runs at once; None means
|
|
57
|
+
all cores available to the process. Each address runs alone, so its result never depends
|
|
58
|
+
on the rest of the list. One `Parser` can be shared across threads. `repostal.parse(text)`
|
|
59
|
+
uses the default model.
|
|
60
|
+
|
|
61
|
+
## Command line
|
|
62
|
+
|
|
63
|
+
```
|
|
64
|
+
repostal parse --model /path/to/bundle "221B Baker Street, London"
|
|
65
|
+
repostal parse --model /path/to/bundle < addresses.txt # JSON lines out
|
|
66
|
+
repostal download [model] # prints the bundle directory
|
|
67
|
+
```
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
# repostal
|
|
2
|
+
|
|
3
|
+
Address parser: text in, labelled address parts out. Runs on CPU with ONNX Runtime; no
|
|
4
|
+
torch. The package holds no weights: it loads a model bundle from a local directory or
|
|
5
|
+
downloads one from the Hugging Face Hub once and caches it.
|
|
6
|
+
|
|
7
|
+
## Install
|
|
8
|
+
|
|
9
|
+
```
|
|
10
|
+
pip install repostal
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
This is a pre-release: no model is published yet, so `Parser()` needs a local bundle
|
|
14
|
+
directory (made by `python -m training.bundle` in the repository). The first full
|
|
15
|
+
release will download its model on first use.
|
|
16
|
+
|
|
17
|
+
## Python
|
|
18
|
+
|
|
19
|
+
```python
|
|
20
|
+
import repostal
|
|
21
|
+
|
|
22
|
+
parser = repostal.Parser("/path/to/bundle") # or a model name / Hub repo id
|
|
23
|
+
r = parser.parse("221B Baker Street, London NW1 6XE, UK")
|
|
24
|
+
r.to_dict() # {"house_number": "221B", "road": "Baker Street", "city": "London", ...}
|
|
25
|
+
r.get("city") # "London", or None
|
|
26
|
+
r.components # Component(label, value, start, end, score), in text order
|
|
27
|
+
r.truncated # True if the text was longer than the model reads
|
|
28
|
+
|
|
29
|
+
results = parser.parse_batch(texts) # same order as texts, on the parser's threads
|
|
30
|
+
parser.labels # label names, from the bundle
|
|
31
|
+
parser.model # bundle name and version
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
`value` is always `text[start:end]`; a component is a run of words with the same label,
|
|
35
|
+
including the separators between them. `score` is the lowest label probability among its
|
|
36
|
+
words. Options are keyword-only: `Parser(model, revision=None, threads=None,
|
|
37
|
+
cache_dir=None)`. `threads` is how many addresses `parse_batch` runs at once; None means
|
|
38
|
+
all cores available to the process. Each address runs alone, so its result never depends
|
|
39
|
+
on the rest of the list. One `Parser` can be shared across threads. `repostal.parse(text)`
|
|
40
|
+
uses the default model.
|
|
41
|
+
|
|
42
|
+
## Command line
|
|
43
|
+
|
|
44
|
+
```
|
|
45
|
+
repostal parse --model /path/to/bundle "221B Baker Street, London"
|
|
46
|
+
repostal parse --model /path/to/bundle < addresses.txt # JSON lines out
|
|
47
|
+
repostal download [model] # prints the bundle directory
|
|
48
|
+
```
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "repostal"
|
|
7
|
+
version = "0.1.0.dev0"
|
|
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 :: 2 - Pre-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.15",
|
|
26
|
+
]
|
|
27
|
+
|
|
28
|
+
[project.scripts]
|
|
29
|
+
repostal = "repostal.cli:main"
|
|
30
|
+
|
|
31
|
+
[tool.hatch.build.targets.wheel]
|
|
32
|
+
packages = ["src/repostal"]
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
"""repostal: address text in, labelled address parts out.
|
|
2
|
+
|
|
3
|
+
>>> import repostal
|
|
4
|
+
>>> repostal.Parser("/path/to/bundle").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.dev0"
|
|
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,46 @@
|
|
|
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 revision). Empty until weights are published.
|
|
16
|
+
MODELS: dict[str, tuple[str, str]] = {}
|
|
17
|
+
DEFAULT: str | None = None
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def resolve(model: str | None = None, *, revision: str | None = None,
|
|
21
|
+
cache_dir: str | None = None) -> str:
|
|
22
|
+
"""Local directory of `model`: a bundle directory, a name in MODELS or a Hub repo id."""
|
|
23
|
+
model = model or DEFAULT
|
|
24
|
+
if model is None:
|
|
25
|
+
raise ValueError("no default model is published yet; pass a local bundle directory: "
|
|
26
|
+
"repostal.Parser('/path/to/bundle')")
|
|
27
|
+
if os.path.isdir(model):
|
|
28
|
+
return model
|
|
29
|
+
repo, pinned = MODELS.get(model, (model, None))
|
|
30
|
+
if "/" not in repo:
|
|
31
|
+
known = ", ".join(MODELS) or "none published yet"
|
|
32
|
+
raise ValueError(f"{model!r} is not a bundle directory or a known model ({known})")
|
|
33
|
+
from huggingface_hub import snapshot_download # only needed for Hub models
|
|
34
|
+
|
|
35
|
+
return snapshot_download(repo, revision=revision or pinned, cache_dir=cache_dir,
|
|
36
|
+
allow_patterns=FILES)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def read_meta(path: str) -> dict:
|
|
40
|
+
"""The bundle's repostal.json, after checking its format number."""
|
|
41
|
+
with open(os.path.join(path, "repostal.json"), encoding="utf-8") as f:
|
|
42
|
+
meta = json.load(f)
|
|
43
|
+
if meta.get("format") != FORMAT:
|
|
44
|
+
raise ValueError(f"{path}: bundle format {meta.get('format')!r}, this repostal reads "
|
|
45
|
+
f"format {FORMAT}; upgrade repostal or use a matching bundle")
|
|
46
|
+
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,87 @@
|
|
|
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
|
+
from concurrent.futures import ThreadPoolExecutor
|
|
6
|
+
|
|
7
|
+
import numpy as np
|
|
8
|
+
import onnxruntime as ort
|
|
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
|
+
options = ort.SessionOptions()
|
|
41
|
+
options.intra_op_num_threads = options.inter_op_num_threads = 1
|
|
42
|
+
self._session = ort.InferenceSession(os.path.join(path, "model.onnx"), options,
|
|
43
|
+
providers=["CPUExecutionProvider"])
|
|
44
|
+
self._inputs = [i.name for i in self._session.get_inputs()]
|
|
45
|
+
self._pool = ThreadPoolExecutor(threads or _cores(), thread_name_prefix="repostal")
|
|
46
|
+
|
|
47
|
+
def parse(self, text: str) -> Parsed:
|
|
48
|
+
"""Parse one address."""
|
|
49
|
+
return self._row(text, self._encoder.encode_batch([_checked(text)])[0])
|
|
50
|
+
|
|
51
|
+
def parse_batch(self, texts: list[str]) -> list[Parsed]:
|
|
52
|
+
"""Parse many addresses on the parser's threads; results are in input order and
|
|
53
|
+
equal to `parse` of each text."""
|
|
54
|
+
texts = [_checked(t) for t in texts]
|
|
55
|
+
return list(self._pool.map(self._row, texts, self._encoder.encode_batch(texts)))
|
|
56
|
+
|
|
57
|
+
def _row(self, text: str, enc: Encoded) -> Parsed:
|
|
58
|
+
if not enc.spans:
|
|
59
|
+
return Parsed(text, (), enc.truncated)
|
|
60
|
+
ids = np.array([enc.ids], np.int64)
|
|
61
|
+
feed = {"input_ids": ids, "attention_mask": np.ones_like(ids),
|
|
62
|
+
"token_type_ids": np.zeros_like(ids)}
|
|
63
|
+
logits = self._session.run(["logits"], {n: feed[n] for n in self._inputs})[0][0]
|
|
64
|
+
z = np.exp(logits - logits.max(-1, keepdims=True))
|
|
65
|
+
return _parsed(text, enc, z / z.sum(-1, keepdims=True), self.labels)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _checked(text) -> str:
|
|
69
|
+
if not isinstance(text, str):
|
|
70
|
+
raise TypeError(f"expected str, got {type(text).__name__}")
|
|
71
|
+
return text
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _parsed(text: str, enc: Encoded, probs: np.ndarray, labels: tuple[str, ...]) -> Parsed:
|
|
75
|
+
"""Join adjacent words with the same label into components. A component runs from its
|
|
76
|
+
first word's start to its last word's end, so separators between its words stay in it."""
|
|
77
|
+
p = probs[enc.first]
|
|
78
|
+
best = p.argmax(-1)
|
|
79
|
+
runs: list[list] = [] # [label id, start, end, score]
|
|
80
|
+
for (start, end), lab, score in zip(enc.spans, best, p[np.arange(len(best)), best]):
|
|
81
|
+
if runs and runs[-1][0] == lab:
|
|
82
|
+
runs[-1][2] = end
|
|
83
|
+
runs[-1][3] = min(runs[-1][3], score)
|
|
84
|
+
else:
|
|
85
|
+
runs.append([lab, start, end, score])
|
|
86
|
+
comps = tuple(Component(labels[lab], text[s:e], s, e, float(sc)) for lab, s, e, sc in runs)
|
|
87
|
+
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 bundle: REPOSTAL_TEST_BUNDLE=/path/to/bundle pytest"""
|
|
2
|
+
import os
|
|
3
|
+
from concurrent.futures import ThreadPoolExecutor
|
|
4
|
+
|
|
5
|
+
import pytest
|
|
6
|
+
|
|
7
|
+
import repostal
|
|
8
|
+
|
|
9
|
+
BUNDLE = os.environ.get("REPOSTAL_TEST_BUNDLE")
|
|
10
|
+
pytestmark = pytest.mark.skipif(not BUNDLE, reason="REPOSTAL_TEST_BUNDLE is not set")
|
|
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)
|