repostal 0.1.0.dev0__tar.gz → 0.2.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.
@@ -0,0 +1,23 @@
1
+ # package
2
+ /dist/
3
+ /build/
4
+ *.egg-info/
5
+ __pycache__/
6
+ *.pyc
7
+ .venv/
8
+ .pytest_cache/
9
+ .ruff_cache/
10
+
11
+ # JavaScript package
12
+ node_modules/
13
+ *.tgz
14
+
15
+ # training: data, runs, bundles and the Rust build stay out of git
16
+ /training/data
17
+ /training/runs*/
18
+ /training/bundles/
19
+ /training/release/
20
+ /training/native/target/
21
+ *.onnx
22
+ *.ckpt
23
+ *.pt
@@ -0,0 +1,55 @@
1
+ # Changelog
2
+
3
+ All notable changes to the `repostal` package. The format follows
4
+ [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and the project uses
5
+ [Semantic Versioning](https://semver.org/).
6
+
7
+ ## [0.2.0] - 2026-12-04
8
+
9
+ ### Added
10
+
11
+ - The JavaScript package `repostal` on npm (folder `js/`, Node.js 22 or later, on Linux
12
+ x64 and arm64 with glibc, macOS arm64, Windows x64 and arm64): `Parser.load`, the
13
+ top-level `parse(text)`, `parser.parse`, `parser.parseBatch`, `parser.close` and the
14
+ `repostal` command, on the same models at the same pinned revisions. Components, spans (in code points) and labels
15
+ are identical to the Python package's; scores agree to 1e-4. Models are cached in the
16
+ standard Hugging Face Hub folder that Python uses. `parseBatch` runs on worker threads
17
+ (default: the cores, at most 4), each holding its own copy of the model.
18
+ - `local_files_only` (Python, `Parser(..., local_files_only=True)`) and `localFilesOnly`
19
+ (JavaScript, `Parser.load(model, {localFilesOnly: true})`): never download; a model that
20
+ is not fully cached raises `huggingface_hub`'s `LocalEntryNotFoundError` in Python and
21
+ rejects with an Error whose `code` is `"MODEL_NOT_CACHED"` in JavaScript.
22
+ - CI tests the JavaScript package on Node.js 22 and 24; the publish workflow can publish it
23
+ to npm with provenance.
24
+
25
+ No change to parsing: the same models at the same pinned revisions give the same results
26
+ as 0.1.1.
27
+
28
+ ## [0.1.1] - 2026-12-04
29
+
30
+ ### Changed
31
+
32
+ - The repository has a standard package layout: the package at the root (`src/`,
33
+ `tests/`, `pyproject.toml`), the training pipeline under `training/`.
34
+ - One README for the package and its PyPI page; training instructions moved to
35
+ `training/README.md`.
36
+
37
+ ### Added
38
+
39
+ - `py.typed`: the package ships its type hints.
40
+ - Classifiers for Python 3.9 to 3.13, a `dev` extra (pytest, ruff) and a Changelog link.
41
+
42
+ No change to parsing: the same models at the same pinned revisions give the same results
43
+ as 0.1.0.
44
+
45
+ ## [0.1.0] - 2026-12-04
46
+
47
+ ### Added
48
+
49
+ - First release: `repostal.Parser` with `parse` and `parse_batch`, the `repostal`
50
+ command line (`parse`, `download`), and two models on the Hugging Face Hub,
51
+ `repostal-small` (default) and `repostal-large`, at pinned revisions.
52
+
53
+ [0.2.0]: https://github.com/brightertiger/repostal/compare/v0.1.1...v0.2.0
54
+ [0.1.1]: https://github.com/brightertiger/repostal/compare/v0.1.0...v0.1.1
55
+ [0.1.0]: https://github.com/brightertiger/repostal/releases/tag/v0.1.0
@@ -0,0 +1,168 @@
1
+ Metadata-Version: 2.5
2
+ Name: repostal
3
+ Version: 0.2.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: Changelog, https://github.com/brightertiger/repostal/blob/main/CHANGELOG.md
7
+ Project-URL: Model, https://huggingface.co/brightertiger/repostal-small
8
+ Project-URL: Large model, https://huggingface.co/brightertiger/repostal-large
9
+ Author: Ujjwal Singh Rao
10
+ License-Expression: MIT
11
+ License-File: LICENSE
12
+ Keywords: address,geocoding,multilingual,onnx,parser
13
+ Classifier: Development Status :: 3 - Alpha
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3 :: Only
18
+ Classifier: Programming Language :: Python :: 3.9
19
+ Classifier: Programming Language :: Python :: 3.10
20
+ Classifier: Programming Language :: Python :: 3.11
21
+ Classifier: Programming Language :: Python :: 3.12
22
+ Classifier: Programming Language :: Python :: 3.13
23
+ Classifier: Topic :: Text Processing :: Linguistic
24
+ Classifier: Typing :: Typed
25
+ Requires-Python: >=3.9
26
+ Requires-Dist: huggingface-hub>=0.20
27
+ Requires-Dist: numpy>=1.21
28
+ Requires-Dist: onnxruntime>=1.16
29
+ Requires-Dist: tokenizers>=0.21.2
30
+ Provides-Extra: dev
31
+ Requires-Dist: pytest; extra == 'dev'
32
+ Requires-Dist: ruff; extra == 'dev'
33
+ Description-Content-Type: text/markdown
34
+
35
+ # repostal
36
+
37
+ [![PyPI](https://img.shields.io/pypi/v/repostal)](https://pypi.org/project/repostal/)
38
+ [![npm](https://img.shields.io/npm/v/repostal)](https://www.npmjs.com/package/repostal)
39
+ [![test](https://github.com/brightertiger/repostal/actions/workflows/test.yml/badge.svg)](https://github.com/brightertiger/repostal/actions/workflows/test.yml)
40
+ [![License: MIT](https://img.shields.io/badge/license-MIT-blue)](https://github.com/brightertiger/repostal/blob/main/LICENSE)
41
+ [![repostal-small](https://img.shields.io/badge/Hugging%20Face-repostal--small-yellow)](https://huggingface.co/brightertiger/repostal-small)
42
+ [![repostal-large](https://img.shields.io/badge/Hugging%20Face-repostal--large-yellow)](https://huggingface.co/brightertiger/repostal-large)
43
+
44
+ Address parser: text in, labelled address parts out (house number, road, unit, postcode,
45
+ city, state, country, ...), in many languages and scripts, robust to typos and missing
46
+ commas. A small transformer runs on CPU with ONNX Runtime; no torch. The weights are
47
+ downloaded from the Hugging Face Hub on first use and cached.
48
+
49
+ ## Install
50
+
51
+ ```
52
+ pip install repostal
53
+ ```
54
+
55
+ ## Quickstart
56
+
57
+ ```python
58
+ import repostal
59
+
60
+ parser = repostal.Parser() # repostal-small, downloaded once
61
+ r = parser.parse("221B Baker Street, London NW1 6XE, UK")
62
+ r.to_dict() # {"house_number": "221B", "road": "Baker Street", "city": "London", ...}
63
+ r.get("city") # "London", or None
64
+ r.components # Component(label, value, start, end, score), in text order
65
+ r.truncated # True if the text was longer than the model reads
66
+ parser.labels # label names, from the model
67
+ ```
68
+
69
+ `value` is always `text[start:end]`; a component is a run of words with the same label,
70
+ including the separators between them; `score` is the lowest label probability among its
71
+ words. `repostal.parse(text)` is a shortcut on a shared default parser.
72
+
73
+ ## Batches and threads
74
+
75
+ ```python
76
+ results = parser.parse_batch(texts) # same order as texts
77
+ ```
78
+
79
+ `parse_batch` runs the addresses in parallel on `threads` threads (None: all cores
80
+ available to the process). Each address runs alone, so a result never depends on the
81
+ rest of the list, and `parse_batch(texts)` equals `[parse(t) for t in texts]`. One
82
+ `Parser` can be shared across threads.
83
+
84
+ ## Command line
85
+
86
+ ```
87
+ repostal parse "221B Baker Street, London"
88
+ repostal parse --model large < addresses.txt # one address per line in, JSON lines out
89
+ repostal download [small|large] # prints the cached model directory
90
+ ```
91
+
92
+ ## JavaScript
93
+
94
+ ```
95
+ npm install repostal
96
+ ```
97
+
98
+ ```js
99
+ import { Parser } from "repostal";
100
+
101
+ const parser = await Parser.load(); // or Parser.load("large"), or a bundle directory
102
+ const r = await parser.parse("221B Baker Street, London NW1 6XE, UK");
103
+ r.toDict(); // { house_number: "221B", road: "Baker Street", city: "London", ... }
104
+ await parser.parseBatch(texts);
105
+ ```
106
+
107
+ The npm package (Node.js 22 or later, source in [js/](https://github.com/brightertiger/repostal/tree/main/js))
108
+ runs the same models at the same pinned revisions and gives the same components, with
109
+ `start` and `end` in code points as in Python. It uses the same Hugging Face Hub cache, so
110
+ Python and JavaScript share one copy of a model. `npx repostal parse ...` and
111
+ `npx repostal download ...` work as the Python command does. It runs where both of its
112
+ native dependencies have builds (Linux x64 and arm64 with glibc, macOS arm64, Windows x64
113
+ and arm64) and installs about 650 MB of `node_modules`; see
114
+ [js/README.md](https://github.com/brightertiger/repostal/blob/main/js/README.md).
115
+
116
+ ## Results
117
+
118
+ Four-field accuracy (city, state, country and postcode all right), %, through this
119
+ package, beside libpostal on the same rows. noisy3: typing noise training never saw;
120
+ fresh: generated addresses from held-out regions; real: 5,000 real places in six text
121
+ forms. Details and the rest of the numbers: the model cards and
122
+ [docs/results.md](https://github.com/brightertiger/repostal/blob/main/docs/results.md).
123
+
124
+ <!-- repostal_training.score_bundle on each released bundle (small: 20,000 rows per set,
125
+ large: 5,000; real: all 30,000); libpostal on the small model's rows. Sources in the model
126
+ cards. -->
127
+
128
+ | Model | clean | noisy3 | fresh | real (strict / lenient) | ms per address | download |
129
+ |---|---:|---:|---:|---:|---:|---:|
130
+ | repostal-small (default) | 97.20 | 75.21 | 93.38 | 81.89 / 83.79 | 6.7 | 82 MB |
131
+ | repostal-large | 97.94 | 79.86 | 94.34 | 84.19 / 85.77 | 78 | 524 MB |
132
+ | libpostal (Senzing model) | 98.66 | 51.84 | 81.92 | 73.31 / 74.45 | 0.18 | |
133
+
134
+ Median time on one core. libpostal is far faster and better on clean text in its own
135
+ training format; repostal is ahead on noisy, generated and real addresses.
136
+
137
+ ## Models
138
+
139
+ `Parser("small")` (default, 82 MB), `Parser("large")` (more accurate, slower), or
140
+ `Parser("/path/to/bundle")` for a local model directory. Options are keyword-only:
141
+ `Parser(model, revision=None, threads=None, cache_dir=None, local_files_only=False)`. With
142
+ `local_files_only=True` nothing is downloaded, and a model that is not fully cached raises
143
+ `huggingface_hub`'s `LocalEntryNotFoundError` (a `FileNotFoundError`). Each package version pins
144
+ the Hub revision of both models, so an installed version always runs the same weights.
145
+
146
+ ## Known weak spots
147
+
148
+ - Japanese real addresses: repostal-small scores 24.9 strict / 59.9 lenient against
149
+ libpostal's 57.5 / 68.8.
150
+ - Clean lines in Senzing's own format, which libpostal's Senzing model was trained on:
151
+ 97.4 against 99.4.
152
+ - Real addresses in South Africa, the Netherlands, the United Kingdom and Italy score low
153
+ for every parser compared.
154
+
155
+ The model cards on the Hub have the full list and the numbers behind it.
156
+
157
+ ## Licence
158
+
159
+ Code: MIT. Weights: CC-BY-4.0, with attribution to OpenStreetMap contributors,
160
+ OpenAddresses, GeoNames, libpostal and Senzing (the training data's sources; see the model
161
+ cards on the Hub).
162
+
163
+ ## Training and documentation
164
+
165
+ Everything that makes the models (data preparation, training, export, pruning, bundling
166
+ and scoring) is in [training/](https://github.com/brightertiger/repostal/tree/main/training);
167
+ start with its README. [docs/](https://github.com/brightertiger/repostal/tree/main/docs)
168
+ has the full results, the project's history and the models' Hub cards.
@@ -0,0 +1,134 @@
1
+ # repostal
2
+
3
+ [![PyPI](https://img.shields.io/pypi/v/repostal)](https://pypi.org/project/repostal/)
4
+ [![npm](https://img.shields.io/npm/v/repostal)](https://www.npmjs.com/package/repostal)
5
+ [![test](https://github.com/brightertiger/repostal/actions/workflows/test.yml/badge.svg)](https://github.com/brightertiger/repostal/actions/workflows/test.yml)
6
+ [![License: MIT](https://img.shields.io/badge/license-MIT-blue)](https://github.com/brightertiger/repostal/blob/main/LICENSE)
7
+ [![repostal-small](https://img.shields.io/badge/Hugging%20Face-repostal--small-yellow)](https://huggingface.co/brightertiger/repostal-small)
8
+ [![repostal-large](https://img.shields.io/badge/Hugging%20Face-repostal--large-yellow)](https://huggingface.co/brightertiger/repostal-large)
9
+
10
+ Address parser: text in, labelled address parts out (house number, road, unit, postcode,
11
+ city, state, country, ...), in many languages and scripts, robust to typos and missing
12
+ commas. A small transformer runs on CPU with ONNX Runtime; no torch. The weights are
13
+ downloaded from the Hugging Face Hub on first use and cached.
14
+
15
+ ## Install
16
+
17
+ ```
18
+ pip install repostal
19
+ ```
20
+
21
+ ## Quickstart
22
+
23
+ ```python
24
+ import repostal
25
+
26
+ parser = repostal.Parser() # repostal-small, downloaded once
27
+ r = parser.parse("221B Baker Street, London NW1 6XE, UK")
28
+ r.to_dict() # {"house_number": "221B", "road": "Baker Street", "city": "London", ...}
29
+ r.get("city") # "London", or None
30
+ r.components # Component(label, value, start, end, score), in text order
31
+ r.truncated # True if the text was longer than the model reads
32
+ parser.labels # label names, from the model
33
+ ```
34
+
35
+ `value` is always `text[start:end]`; a component is a run of words with the same label,
36
+ including the separators between them; `score` is the lowest label probability among its
37
+ words. `repostal.parse(text)` is a shortcut on a shared default parser.
38
+
39
+ ## Batches and threads
40
+
41
+ ```python
42
+ results = parser.parse_batch(texts) # same order as texts
43
+ ```
44
+
45
+ `parse_batch` runs the addresses in parallel on `threads` threads (None: all cores
46
+ available to the process). Each address runs alone, so a result never depends on the
47
+ rest of the list, and `parse_batch(texts)` equals `[parse(t) for t in texts]`. One
48
+ `Parser` can be shared across threads.
49
+
50
+ ## Command line
51
+
52
+ ```
53
+ repostal parse "221B Baker Street, London"
54
+ repostal parse --model large < addresses.txt # one address per line in, JSON lines out
55
+ repostal download [small|large] # prints the cached model directory
56
+ ```
57
+
58
+ ## JavaScript
59
+
60
+ ```
61
+ npm install repostal
62
+ ```
63
+
64
+ ```js
65
+ import { Parser } from "repostal";
66
+
67
+ const parser = await Parser.load(); // or Parser.load("large"), or a bundle directory
68
+ const r = await parser.parse("221B Baker Street, London NW1 6XE, UK");
69
+ r.toDict(); // { house_number: "221B", road: "Baker Street", city: "London", ... }
70
+ await parser.parseBatch(texts);
71
+ ```
72
+
73
+ The npm package (Node.js 22 or later, source in [js/](https://github.com/brightertiger/repostal/tree/main/js))
74
+ runs the same models at the same pinned revisions and gives the same components, with
75
+ `start` and `end` in code points as in Python. It uses the same Hugging Face Hub cache, so
76
+ Python and JavaScript share one copy of a model. `npx repostal parse ...` and
77
+ `npx repostal download ...` work as the Python command does. It runs where both of its
78
+ native dependencies have builds (Linux x64 and arm64 with glibc, macOS arm64, Windows x64
79
+ and arm64) and installs about 650 MB of `node_modules`; see
80
+ [js/README.md](https://github.com/brightertiger/repostal/blob/main/js/README.md).
81
+
82
+ ## Results
83
+
84
+ Four-field accuracy (city, state, country and postcode all right), %, through this
85
+ package, beside libpostal on the same rows. noisy3: typing noise training never saw;
86
+ fresh: generated addresses from held-out regions; real: 5,000 real places in six text
87
+ forms. Details and the rest of the numbers: the model cards and
88
+ [docs/results.md](https://github.com/brightertiger/repostal/blob/main/docs/results.md).
89
+
90
+ <!-- repostal_training.score_bundle on each released bundle (small: 20,000 rows per set,
91
+ large: 5,000; real: all 30,000); libpostal on the small model's rows. Sources in the model
92
+ cards. -->
93
+
94
+ | Model | clean | noisy3 | fresh | real (strict / lenient) | ms per address | download |
95
+ |---|---:|---:|---:|---:|---:|---:|
96
+ | repostal-small (default) | 97.20 | 75.21 | 93.38 | 81.89 / 83.79 | 6.7 | 82 MB |
97
+ | repostal-large | 97.94 | 79.86 | 94.34 | 84.19 / 85.77 | 78 | 524 MB |
98
+ | libpostal (Senzing model) | 98.66 | 51.84 | 81.92 | 73.31 / 74.45 | 0.18 | |
99
+
100
+ Median time on one core. libpostal is far faster and better on clean text in its own
101
+ training format; repostal is ahead on noisy, generated and real addresses.
102
+
103
+ ## Models
104
+
105
+ `Parser("small")` (default, 82 MB), `Parser("large")` (more accurate, slower), or
106
+ `Parser("/path/to/bundle")` for a local model directory. Options are keyword-only:
107
+ `Parser(model, revision=None, threads=None, cache_dir=None, local_files_only=False)`. With
108
+ `local_files_only=True` nothing is downloaded, and a model that is not fully cached raises
109
+ `huggingface_hub`'s `LocalEntryNotFoundError` (a `FileNotFoundError`). Each package version pins
110
+ the Hub revision of both models, so an installed version always runs the same weights.
111
+
112
+ ## Known weak spots
113
+
114
+ - Japanese real addresses: repostal-small scores 24.9 strict / 59.9 lenient against
115
+ libpostal's 57.5 / 68.8.
116
+ - Clean lines in Senzing's own format, which libpostal's Senzing model was trained on:
117
+ 97.4 against 99.4.
118
+ - Real addresses in South Africa, the Netherlands, the United Kingdom and Italy score low
119
+ for every parser compared.
120
+
121
+ The model cards on the Hub have the full list and the numbers behind it.
122
+
123
+ ## Licence
124
+
125
+ Code: MIT. Weights: CC-BY-4.0, with attribution to OpenStreetMap contributors,
126
+ OpenAddresses, GeoNames, libpostal and Senzing (the training data's sources; see the model
127
+ cards on the Hub).
128
+
129
+ ## Training and documentation
130
+
131
+ Everything that makes the models (data preparation, training, export, pruning, bundling
132
+ and scoring) is in [training/](https://github.com/brightertiger/repostal/tree/main/training);
133
+ start with its README. [docs/](https://github.com/brightertiger/repostal/tree/main/docs)
134
+ has the full results, the project's history and the models' Hub cards.
@@ -0,0 +1,68 @@
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
+ "Operating System :: OS Independent",
18
+ "Programming Language :: Python :: 3",
19
+ "Programming Language :: Python :: 3 :: Only",
20
+ "Programming Language :: Python :: 3.9",
21
+ "Programming Language :: Python :: 3.10",
22
+ "Programming Language :: Python :: 3.11",
23
+ "Programming Language :: Python :: 3.12",
24
+ "Programming Language :: Python :: 3.13",
25
+ "Topic :: Text Processing :: Linguistic",
26
+ "Typing :: Typed",
27
+ ]
28
+ requires-python = ">=3.9"
29
+ dependencies = [
30
+ "huggingface_hub>=0.20",
31
+ "numpy>=1.21",
32
+ "onnxruntime>=1.16",
33
+ "tokenizers>=0.21.2",
34
+ ]
35
+
36
+ [project.optional-dependencies]
37
+ dev = ["pytest", "ruff"]
38
+
39
+ [project.urls]
40
+ Repository = "https://github.com/brightertiger/repostal"
41
+ Changelog = "https://github.com/brightertiger/repostal/blob/main/CHANGELOG.md"
42
+ Model = "https://huggingface.co/brightertiger/repostal-small"
43
+ "Large model" = "https://huggingface.co/brightertiger/repostal-large"
44
+
45
+ [project.scripts]
46
+ repostal = "repostal.cli:main"
47
+
48
+ [tool.hatch.version]
49
+ path = "src/repostal/__init__.py"
50
+
51
+ [tool.hatch.build.targets.wheel]
52
+ packages = ["src/repostal"]
53
+
54
+ [tool.hatch.build.targets.sdist]
55
+ # the package only; training/ and docs/ stay in the repository
56
+ include = ["/src/repostal", "/tests", "/README.md", "/CHANGELOG.md", "/LICENSE"]
57
+
58
+ [tool.pytest.ini_options]
59
+ testpaths = ["tests"]
60
+
61
+ [tool.ruff]
62
+ line-length = 100
63
+ target-version = "py39"
64
+ src = ["src"]
65
+ extend-exclude = ["training"]
66
+
67
+ [tool.ruff.lint]
68
+ select = ["E", "F", "W", "I", "B", "UP"]
@@ -1,20 +1,20 @@
1
1
  """repostal: address text in, labelled address parts out.
2
2
 
3
3
  >>> import repostal
4
- >>> repostal.Parser("/path/to/bundle").parse("221B Baker Street, London").to_dict()
4
+ >>> repostal.Parser().parse("221B Baker Street, London").to_dict()
5
5
  """
6
6
  from __future__ import annotations
7
7
 
8
- from functools import lru_cache
8
+ from functools import cache
9
9
 
10
10
  from .parser import Parser
11
11
  from .results import Component, Parsed
12
12
 
13
13
  __all__ = ["Component", "Parsed", "Parser", "parse"]
14
- __version__ = "0.1.0.dev0"
14
+ __version__ = "0.2.0"
15
15
 
16
16
 
17
- @lru_cache(maxsize=None)
17
+ @cache
18
18
  def _default() -> Parser:
19
19
  return Parser()
20
20
 
@@ -0,0 +1,68 @@
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, local_files_only: bool = False) -> str:
32
+ """Local directory of `model`: a bundle directory, a name in MODELS or a Hub repo id.
33
+
34
+ local_files_only: never download; a Hub model that is not fully cached raises
35
+ huggingface_hub's LocalEntryNotFoundError (a FileNotFoundError)."""
36
+ model = model or DEFAULT
37
+ if os.path.isdir(os.path.expanduser(model)):
38
+ return os.path.expanduser(model)
39
+ if _is_path(model):
40
+ raise FileNotFoundError(f"no bundle directory at {model}")
41
+ repo, pinned = MODELS.get(model, (model, None))
42
+ if "/" not in repo:
43
+ raise ValueError(f"{model!r} is not a bundle directory or a known model "
44
+ f"({', '.join(MODELS)})")
45
+ from huggingface_hub import snapshot_download # only needed for Hub models
46
+ from huggingface_hub.utils import LocalEntryNotFoundError
47
+
48
+ kw = dict(revision=revision or pinned, cache_dir=cache_dir, allow_patterns=FILES)
49
+ try: # a complete cached snapshot needs no network
50
+ path = snapshot_download(repo, local_files_only=True, **kw)
51
+ if all(os.path.isfile(os.path.join(path, f)) for f in FILES):
52
+ return path
53
+ except OSError: # not cached (LocalEntryNotFoundError)
54
+ pass
55
+ if local_files_only:
56
+ raise LocalEntryNotFoundError(f"{repo} at revision {kw['revision'] or 'main'} is not "
57
+ "fully cached and local_files_only is set")
58
+ return snapshot_download(repo, **kw) # downloads, or repairs a partial snapshot
59
+
60
+
61
+ def read_meta(path: str) -> dict:
62
+ """The bundle's repostal.json, after checking its format number."""
63
+ with open(os.path.join(path, "repostal.json"), encoding="utf-8") as f:
64
+ meta = json.load(f)
65
+ if meta.get("format") != FORMAT:
66
+ raise ValueError(f"{path}: bundle format {meta.get('format')!r}, this repostal reads "
67
+ f"format {FORMAT}; upgrade repostal or use a matching bundle")
68
+ return meta
@@ -2,10 +2,10 @@
2
2
  from __future__ import annotations
3
3
 
4
4
  import os
5
+ import threading
5
6
  from concurrent.futures import ThreadPoolExecutor
6
7
 
7
8
  import numpy as np
8
- import onnxruntime as ort
9
9
 
10
10
  from .bundle import read_meta, resolve
11
11
  from .encode import Encoded, Encoder
@@ -24,25 +24,32 @@ class Parser:
24
24
 
25
25
  model: a bundle directory, a model name, or a Hugging Face Hub repo id (None: the
26
26
  default model). threads: how many addresses `parse_batch` runs at once (None: all
27
- cores available to the process).
27
+ cores available to the process). local_files_only: never download; a Hub model that is
28
+ not fully cached raises huggingface_hub's LocalEntryNotFoundError.
28
29
 
29
30
  Every address runs through the model alone, unpadded, so its result never depends on
30
31
  what else is in the list (int8 models quantise activations with one scale per run).
31
32
  """
32
33
 
33
34
  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)
35
+ threads: int | None = None, cache_dir: str | None = None,
36
+ local_files_only: bool = False):
37
+ path = resolve(model, revision=revision, cache_dir=cache_dir,
38
+ local_files_only=local_files_only)
36
39
  meta = read_meta(path)
37
40
  self.labels: tuple[str, ...] = tuple(meta["labels"])
38
41
  self.model = f"{meta['name']} {meta['version']}"
39
42
  self._encoder = Encoder(path, meta)
43
+ import onnxruntime as ort # here, not at the top: `import repostal` stays light
44
+
40
45
  options = ort.SessionOptions()
41
46
  options.intra_op_num_threads = options.inter_op_num_threads = 1
42
47
  self._session = ort.InferenceSession(os.path.join(path, "model.onnx"), options,
43
48
  providers=["CPUExecutionProvider"])
44
49
  self._inputs = [i.name for i in self._session.get_inputs()]
45
- self._pool = ThreadPoolExecutor(threads or _cores(), thread_name_prefix="repostal")
50
+ self._threads = threads or _cores()
51
+ self._pool: ThreadPoolExecutor | None = None # made by the first parse_batch
52
+ self._lock = threading.Lock()
46
53
 
47
54
  def parse(self, text: str) -> Parsed:
48
55
  """Parse one address."""
@@ -52,6 +59,9 @@ class Parser:
52
59
  """Parse many addresses on the parser's threads; results are in input order and
53
60
  equal to `parse` of each text."""
54
61
  texts = [_checked(t) for t in texts]
62
+ with self._lock:
63
+ if self._pool is None:
64
+ self._pool = ThreadPoolExecutor(self._threads, thread_name_prefix="repostal")
55
65
  return list(self._pool.map(self._row, texts, self._encoder.encode_batch(texts)))
56
66
 
57
67
  def _row(self, text: str, enc: Encoded) -> Parsed:
File without changes
@@ -1,13 +1,14 @@
1
- """Behaviour test against a real bundle: REPOSTAL_TEST_BUNDLE=/path/to/bundle pytest"""
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"""
2
3
  import os
3
4
  from concurrent.futures import ThreadPoolExecutor
4
5
 
5
6
  import pytest
7
+ from huggingface_hub.utils import LocalEntryNotFoundError
6
8
 
7
9
  import repostal
8
10
 
9
- BUNDLE = os.environ.get("REPOSTAL_TEST_BUNDLE")
10
- pytestmark = pytest.mark.skipif(not BUNDLE, reason="REPOSTAL_TEST_BUNDLE is not set")
11
+ BUNDLE = os.environ.get("REPOSTAL_TEST_BUNDLE") # None: the default model
11
12
 
12
13
  TEXTS = [
13
14
  "221B Baker Street, London NW1 6XE, UK",
@@ -23,7 +24,7 @@ TEXTS = [
23
24
  ]
24
25
 
25
26
 
26
- def test_parse():
27
+ def test_parse(tmp_path):
27
28
  parser = repostal.Parser(BUNDLE)
28
29
  single = [parser.parse(t) for t in TEXTS]
29
30
  for t, r in zip(TEXTS, single):
@@ -40,3 +41,5 @@ def test_parse():
40
41
  assert list(pool.map(parser.parse, TEXTS * 4)) == single * 4
41
42
  with pytest.raises(TypeError):
42
43
  parser.parse(None)
44
+ with pytest.raises(LocalEntryNotFoundError): # an empty cache, and no download allowed
45
+ repostal.Parser("small", cache_dir=str(tmp_path), local_files_only=True)
@@ -1,10 +0,0 @@
1
- /data/
2
- /runs*/
3
- /bundles/
4
- /target/
5
- /.venv/
6
- __pycache__/
7
- *.pyc
8
- *.onnx
9
- *.ckpt
10
- *.pt
@@ -1,67 +0,0 @@
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
- ```
@@ -1,48 +0,0 @@
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
- ```
@@ -1,32 +0,0 @@
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"]
@@ -1,46 +0,0 @@
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
File without changes