offline-address-check 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.
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,92 @@
1
+ Metadata-Version: 2.4
2
+ Name: offline-address-check
3
+ Version: 0.1.0
4
+ Summary: Check whether a street address exists, offline: yes, maybe or no with a reason, from one file per country (no API key, no network call)
5
+ License-Expression: Apache-2.0
6
+ Project-URL: Homepage, https://gridpin.dev
7
+ Project-URL: Documentation, https://gridpin.dev/docs
8
+ Project-URL: Repository, https://github.com/gridpin/gridpin
9
+ Project-URL: Issues, https://github.com/gridpin/gridpin/issues
10
+ Keywords: address,address-validation,address-verification,address-check,offline,geocoding,data-quality
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Topic :: Scientific/Engineering :: GIS
14
+ Requires-Python: >=3.10
15
+ Description-Content-Type: text/markdown
16
+ License-File: LICENSE
17
+ Requires-Dist: gridpin<0.12,>=0.11
18
+ Dynamic: license-file
19
+
20
+ # offline-address-check
21
+
22
+ Check whether a street address exists, offline. You get `yes`, `maybe` or `no` with a reason, and the spelling of the
23
+ address as the country's data holds it. There is no API key, and the address is never sent anywhere: it is checked against one file per country on
24
+ your machine.
25
+
26
+ Built on [GridPin](https://github.com/gridpin/gridpin), an offline geocoder.
27
+
28
+ ```bash
29
+ pip install offline-address-check
30
+ offline-address-check "8 rue de Rivoli, Paris" --country fr
31
+ ```
32
+
33
+ ```text
34
+ first use: downloading the France file once, 365 MB, from https://dl.gridpin.dev/…
35
+ yes house_found 8 Rue de Rivoli, 75004 Paris 4e Arrondissement
36
+ ```
37
+
38
+ The exit code is 0 for `yes` and 1 otherwise, so a script can branch on it.
39
+
40
+ ## What it says, and what it does not
41
+
42
+ | Verdict | Reasons |
43
+ |---|---|
44
+ | `yes` | `house_found`: the house with this number is in the data, in the town or postcode the line names |
45
+ | `maybe` | `no_place` (found, but the line names no town or postcode), `street_corrected` (found on a street spelled differently), `number_interpolated`, `no_number`, `postcode_differs`, `town_not_on_sheet`, `weak_answer` |
46
+ | `no` | `street_unknown`, `number_not_on_street`, `wrong_city`, `empty` |
47
+
48
+ `offline-address-check --reasons` prints what each reason means.
49
+
50
+ It checks the address against the country's address data. Some things it does not check:
51
+
52
+ - **Delivery.** It does not tell you whether the post delivers there.
53
+ - **Flats and floors.** It knows houses, not units inside them.
54
+ - **Recent addresses.** A house built after the data was published is not there.
55
+
56
+ Which countries have a file, and what each covers, is on the
57
+ [GridPin countries page](https://gridpin.dev/docs#sheets).
58
+
59
+ A line without a town or postcode is never `yes`. "8 rue de Rivoli" exists in Paris, but a street of the same name may
60
+ exist in another town too, and the line does not say which one is meant.
61
+
62
+ ## Many addresses
63
+
64
+ ```bash
65
+ offline-address-check --country de --file customers.csv --column address --out checked.csv
66
+ ```
67
+
68
+ A plain text file (one address per line) works without `--column`. The output CSV has the columns `address`, `exists`,
69
+ `reason`, `street`, `housenumber`, `place`, `postcode`, `lat`, `lon`.
70
+
71
+ ## From Python
72
+
73
+ ```python
74
+ from offline_address_check import Checker
75
+
76
+ checker = Checker("fr") # downloads the France file once; Checker("fr", download=False) refuses to
77
+ row = checker.check("8 rue de Rivoli, Paris")
78
+ row["exists"], row["reason"] # ('yes', 'house_found')
79
+ ```
80
+
81
+ `Checker("/path/to/france.bin")` opens a file you already have.
82
+
83
+ ## Files
84
+
85
+ The country file is downloaded once into the GridPin cache (`~/.cache/gridpin/`). It is checked against its published
86
+ SHA-256 and then read locally. The files are tens to hundreds of megabytes, and the size is printed before a download.
87
+ `offline-address-check --download fr` fetches one ahead of time. `--no-download` stops instead of downloading.
88
+
89
+ ## Licence
90
+
91
+ This package is licensed under Apache-2.0. The country files carry the licences of their sources, which are listed in
92
+ [ATTRIBUTIONS](https://github.com/gridpin/gridpin/blob/main/ATTRIBUTIONS.md).
@@ -0,0 +1,73 @@
1
+ # offline-address-check
2
+
3
+ Check whether a street address exists, offline. You get `yes`, `maybe` or `no` with a reason, and the spelling of the
4
+ address as the country's data holds it. There is no API key, and the address is never sent anywhere: it is checked against one file per country on
5
+ your machine.
6
+
7
+ Built on [GridPin](https://github.com/gridpin/gridpin), an offline geocoder.
8
+
9
+ ```bash
10
+ pip install offline-address-check
11
+ offline-address-check "8 rue de Rivoli, Paris" --country fr
12
+ ```
13
+
14
+ ```text
15
+ first use: downloading the France file once, 365 MB, from https://dl.gridpin.dev/…
16
+ yes house_found 8 Rue de Rivoli, 75004 Paris 4e Arrondissement
17
+ ```
18
+
19
+ The exit code is 0 for `yes` and 1 otherwise, so a script can branch on it.
20
+
21
+ ## What it says, and what it does not
22
+
23
+ | Verdict | Reasons |
24
+ |---|---|
25
+ | `yes` | `house_found`: the house with this number is in the data, in the town or postcode the line names |
26
+ | `maybe` | `no_place` (found, but the line names no town or postcode), `street_corrected` (found on a street spelled differently), `number_interpolated`, `no_number`, `postcode_differs`, `town_not_on_sheet`, `weak_answer` |
27
+ | `no` | `street_unknown`, `number_not_on_street`, `wrong_city`, `empty` |
28
+
29
+ `offline-address-check --reasons` prints what each reason means.
30
+
31
+ It checks the address against the country's address data. Some things it does not check:
32
+
33
+ - **Delivery.** It does not tell you whether the post delivers there.
34
+ - **Flats and floors.** It knows houses, not units inside them.
35
+ - **Recent addresses.** A house built after the data was published is not there.
36
+
37
+ Which countries have a file, and what each covers, is on the
38
+ [GridPin countries page](https://gridpin.dev/docs#sheets).
39
+
40
+ A line without a town or postcode is never `yes`. "8 rue de Rivoli" exists in Paris, but a street of the same name may
41
+ exist in another town too, and the line does not say which one is meant.
42
+
43
+ ## Many addresses
44
+
45
+ ```bash
46
+ offline-address-check --country de --file customers.csv --column address --out checked.csv
47
+ ```
48
+
49
+ A plain text file (one address per line) works without `--column`. The output CSV has the columns `address`, `exists`,
50
+ `reason`, `street`, `housenumber`, `place`, `postcode`, `lat`, `lon`.
51
+
52
+ ## From Python
53
+
54
+ ```python
55
+ from offline_address_check import Checker
56
+
57
+ checker = Checker("fr") # downloads the France file once; Checker("fr", download=False) refuses to
58
+ row = checker.check("8 rue de Rivoli, Paris")
59
+ row["exists"], row["reason"] # ('yes', 'house_found')
60
+ ```
61
+
62
+ `Checker("/path/to/france.bin")` opens a file you already have.
63
+
64
+ ## Files
65
+
66
+ The country file is downloaded once into the GridPin cache (`~/.cache/gridpin/`). It is checked against its published
67
+ SHA-256 and then read locally. The files are tens to hundreds of megabytes, and the size is printed before a download.
68
+ `offline-address-check --download fr` fetches one ahead of time. `--no-download` stops instead of downloading.
69
+
70
+ ## Licence
71
+
72
+ This package is licensed under Apache-2.0. The country files carry the licences of their sources, which are listed in
73
+ [ATTRIBUTIONS](https://github.com/gridpin/gridpin/blob/main/ATTRIBUTIONS.md).
@@ -0,0 +1,31 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "offline-address-check"
7
+ version = "0.1.0"
8
+ description = "Check whether a street address exists, offline: yes, maybe or no with a reason, from one file per country (no API key, no network call)"
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = "Apache-2.0"
12
+ license-files = ["LICENSE"]
13
+ keywords = ["address", "address-validation", "address-verification", "address-check", "offline", "geocoding", "data-quality"]
14
+ classifiers = ["Development Status :: 4 - Beta", "Programming Language :: Python :: 3", "Topic :: Scientific/Engineering :: GIS"]
15
+ # The verdict is gridpin.Geocoder.exists of the engine wheel; this package adds the "no place named" rule and a CLI.
16
+ dependencies = ["gridpin>=0.11,<0.12"]
17
+
18
+ [project.scripts]
19
+ offline-address-check = "offline_address_check:_entry"
20
+
21
+ [project.urls]
22
+ Homepage = "https://gridpin.dev"
23
+ Documentation = "https://gridpin.dev/docs"
24
+ Repository = "https://github.com/gridpin/gridpin"
25
+ Issues = "https://github.com/gridpin/gridpin/issues"
26
+
27
+ [tool.setuptools.packages.find]
28
+ where = ["src"]
29
+
30
+ [tool.setuptools.package-data]
31
+ offline_address_check = ["py.typed"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,213 @@
1
+ """Does a street address exist? Checked offline against one file per country, with no network call and no API key.
2
+
3
+ offline-address-check "8 rue de Rivoli, Paris" --country fr
4
+ yes house_found 8 Rue de Rivoli, 75004 Paris 4e Arrondissement
5
+
6
+ The verdict is ``yes``, ``maybe`` or ``no`` with a reason, and the spelling the file holds. It says whether the house is
7
+ in the country's address data, not whether mail is delivered there, and it knows no flats or floors. Built on the
8
+ GridPin engine (https://gridpin.dev): the country file is downloaded once (its size is printed first) and read locally.
9
+ """
10
+ from __future__ import annotations
11
+
12
+ import argparse
13
+ import csv
14
+ import os
15
+ import re
16
+ import sys
17
+ import unicodedata
18
+ from collections import Counter
19
+ from pathlib import Path
20
+ from typing import Any, Dict, Iterable, Iterator, List, Optional, Sequence, TextIO, Union
21
+
22
+ import gridpin
23
+
24
+ __all__ = ["COLUMNS", "REASONS", "Checker", "check", "names_place", "main"]
25
+
26
+ __version__ = "0.1.0"
27
+
28
+ COLUMNS = ("address", "exists", "reason", "street", "housenumber", "place", "postcode", "lat", "lon")
29
+
30
+ # The engine's reasons (gridpin exists), plus the one this package adds.
31
+ REASONS = {
32
+ "house_found": "the house with this number is in the file, in the town the line names",
33
+ "postcode_differs": "the house is there, but under another postcode",
34
+ "number_interpolated": "the number falls between known houses of the street",
35
+ "no_number": "the line has no house number",
36
+ "town_not_on_sheet": "the line names a town the file does not know",
37
+ "weak_answer": "the engine is not sure of its answer",
38
+ "no_place": "the house was found, but the line names no town or postcode: a street of that name may exist elsewhere",
39
+ "street_corrected": "a house was found on a street spelled differently: see the street column for the spelling",
40
+ "street_unknown": "no such street",
41
+ "number_not_on_street": "the street is there, the number is not",
42
+ "wrong_city": "the house is in another town than the one named",
43
+ "empty": "nothing in the file matches the line",
44
+ }
45
+
46
+ # Answer flags that say the line's town or postcode matched the answer (the engine sets them, gridpin.dev/docs).
47
+ PLACE_FLAGS = {"commune_exact", "commune_prefix", "pc_exact"}
48
+
49
+ SheetLike = Union[str, "os.PathLike[str]"]
50
+
51
+
52
+ def _fold(text: str) -> str:
53
+ text = unicodedata.normalize("NFKD", text.lower())
54
+ return "".join(c for c in text if not unicodedata.combining(c))
55
+
56
+
57
+ def _words(text: str) -> List[str]:
58
+ return [w for w in re.split(r"[^\w]+", _fold(text)) if w]
59
+
60
+
61
+ def names_place(address: str, hit: Optional[Dict[str, Any]]) -> bool:
62
+ """Does the line name the place of the answer: its town (as written or a part of it) or its postcode?
63
+
64
+ A house found from "8 rue de Rivoli" alone is not a confirmed address: the same street and number exist in other
65
+ towns, and the line does not say which one is meant.
66
+ """
67
+ if not hit:
68
+ return False
69
+ if PLACE_FLAGS & set(hit.get("flags") or ()):
70
+ return True
71
+ # a word of the answer's town in the line, other than a word of the street itself ("12 Avenue de Paris" names
72
+ # no town); the postcode is the engine's pc_exact flag above
73
+ line = Counter(_words(address))
74
+ line.subtract(Counter(_words(hit.get("street") or "")))
75
+ town = [w for w in _words(hit.get("commune") or "") if len(w) >= 3 and not w.isdigit()]
76
+ return any(line[w] > 0 for w in town)
77
+
78
+
79
+ def _say(message: str) -> None:
80
+ print(message, file=sys.stderr, flush=True)
81
+
82
+
83
+ def _open_sheet(sheet: SheetLike, download: bool) -> Path:
84
+ """A path to a .bin file as is; a country code or name to its file, downloaded once when allowed."""
85
+ text = os.fspath(sheet)
86
+ candidate = Path(text).expanduser()
87
+ if candidate.suffix == ".bin" or os.sep in text or (os.altsep and os.altsep in text):
88
+ if not candidate.is_file():
89
+ raise FileNotFoundError(f"no such country file: {candidate}")
90
+ return candidate
91
+ found = gridpin.sheets.resolve(text)
92
+ if found.downloaded:
93
+ return found.path
94
+ if not download:
95
+ raise FileNotFoundError(
96
+ f"the {found.name} file is not downloaded ({found.size / 1e6:.0f} MB): run "
97
+ f"`offline-address-check --download {found.code}` once, or pass the path of a .bin file")
98
+ _say(f"first use: downloading the {found.name} file once, {found.size / 1e6:.0f} MB, from {found.url}")
99
+ return gridpin.sheets.fetch(found.code)
100
+
101
+
102
+ class Checker:
103
+ """One country file, opened once; ``check`` answers many lines."""
104
+
105
+ def __init__(self, sheet: SheetLike, *, download: bool = True) -> None:
106
+ self.path = _open_sheet(sheet, download)
107
+ self._g = gridpin.Geocoder(str(self.path))
108
+
109
+ def check(self, address: str) -> Dict[str, Any]:
110
+ """The verdict on one line: a dict with the keys of COLUMNS (empty cells when nothing was found)."""
111
+ row: Dict[str, Any] = {k: "" for k in COLUMNS}
112
+ row["address"] = address
113
+ if not address or not address.strip():
114
+ row.update(exists="no", reason="empty")
115
+ return row
116
+ verdict = self._g.exists(address)
117
+ hits = self._g.geocode(address, 1)
118
+ hit = hits[0] if hits else None
119
+ exists, reason = verdict["exists"], verdict["reason"]
120
+ if exists == "yes" and hit and "street_fuzzy" in (hit.get("flags") or ()):
121
+ # the engine counts a street found with a fix as found ("Avenue 3, Monaco" -> Avenue des Spélugues 3);
122
+ # a check of existence does not: the spelling is shown, the user decides
123
+ exists, reason = "maybe", "street_corrected"
124
+ if exists == "yes" and not names_place(address, hit):
125
+ exists, reason = "maybe", "no_place"
126
+ row.update(exists=exists, reason=reason)
127
+ if hit and reason not in ("street_unknown", "empty"):
128
+ row.update(street=hit.get("street") or "", housenumber=hit.get("housenumber") or "",
129
+ place=hit.get("commune") or "", postcode=hit.get("postcode") or "",
130
+ lat=hit.get("lat", ""), lon=hit.get("lon", ""))
131
+ return row
132
+
133
+ def check_many(self, addresses: Iterable[str]) -> Iterator[Dict[str, Any]]:
134
+ for a in addresses:
135
+ yield self.check(a)
136
+
137
+
138
+ def check(address: str, sheet: SheetLike, *, download: bool = True) -> Dict[str, Any]:
139
+ """``Checker(sheet).check(address)``: for one line; open a Checker for many."""
140
+ return Checker(sheet, download=download).check(address)
141
+
142
+
143
+ def _lines(f: TextIO, column: Optional[str]) -> Iterator[str]:
144
+ if column is None:
145
+ for line in f:
146
+ line = line.rstrip("\r\n")
147
+ if line.strip():
148
+ yield line
149
+ return
150
+ reader = csv.DictReader(f)
151
+ if column not in (reader.fieldnames or ()):
152
+ raise SystemExit(f"no column {column!r} in the file; columns: {', '.join(reader.fieldnames or ())}")
153
+ for rec in reader:
154
+ yield rec.get(column) or ""
155
+
156
+
157
+ def _label(row: Dict[str, Any]) -> str:
158
+ house = " ".join(p for p in (row["housenumber"], row["street"]) if p)
159
+ town = " ".join(p for p in (row["postcode"], row["place"]) if p)
160
+ return ", ".join(p for p in (house, town) if p)
161
+
162
+
163
+ def main(argv: Optional[Sequence[str]] = None) -> int:
164
+ p = argparse.ArgumentParser(
165
+ prog="offline-address-check",
166
+ description="Does a street address exist? yes, maybe or no with a reason, checked offline against one file per "
167
+ "country (GridPin engine). Not a postal deliverability check; flats and floors are not known.")
168
+ p.add_argument("address", nargs="?", help="one address line (or use --file)")
169
+ p.add_argument("--country", "--sheet", dest="sheet",
170
+ help='a country code ("fr"; its file is downloaded once) or the path of a .bin file')
171
+ p.add_argument("--file", type=Path, help="a file of addresses: one per line, or a CSV with --column")
172
+ p.add_argument("--column", help="the address column of a CSV --file")
173
+ p.add_argument("--out", type=Path, help="write the CSV here instead of standard output")
174
+ p.add_argument("--no-download", action="store_true", help="stop instead of downloading a missing country file")
175
+ p.add_argument("--download", metavar="COUNTRY", help="download the country file and exit")
176
+ p.add_argument("--reasons", action="store_true", help="print what each reason means and exit")
177
+ p.add_argument("--version", action="version", version=f"%(prog)s {__version__} (gridpin engine)")
178
+ a = p.parse_args(argv)
179
+ if a.reasons:
180
+ for k, v in REASONS.items():
181
+ print(f"{k:21} {v}")
182
+ return 0
183
+ if a.download:
184
+ print(_open_sheet(a.download, True))
185
+ return 0
186
+ if not a.sheet:
187
+ p.error("--country is required (a country code such as fr, or the path of a .bin file)")
188
+ if (a.address is None) == (a.file is None):
189
+ p.error("give one address, or --file")
190
+ try:
191
+ checker = Checker(a.sheet, download=not a.no_download)
192
+ except (FileNotFoundError, ValueError, KeyError) as e:
193
+ _say(f"offline-address-check: {e}")
194
+ return 2
195
+ if a.address is not None:
196
+ row = checker.check(a.address)
197
+ print(f"{row['exists']}\t{row['reason']}\t{_label(row)}")
198
+ return 0 if row["exists"] == "yes" else 1
199
+ out = a.out.open("w", newline="", encoding="utf-8") if a.out else sys.stdout
200
+ try:
201
+ with a.file.open(newline="", encoding="utf-8-sig") as f:
202
+ w = csv.DictWriter(out, fieldnames=COLUMNS)
203
+ w.writeheader()
204
+ for row in checker.check_many(_lines(f, a.column)):
205
+ w.writerow(row)
206
+ finally:
207
+ if a.out:
208
+ out.close()
209
+ return 0
210
+
211
+
212
+ def _entry() -> None: # console script
213
+ raise SystemExit(main())
@@ -0,0 +1,3 @@
1
+ from offline_address_check import _entry
2
+
3
+ _entry()
@@ -0,0 +1,92 @@
1
+ Metadata-Version: 2.4
2
+ Name: offline-address-check
3
+ Version: 0.1.0
4
+ Summary: Check whether a street address exists, offline: yes, maybe or no with a reason, from one file per country (no API key, no network call)
5
+ License-Expression: Apache-2.0
6
+ Project-URL: Homepage, https://gridpin.dev
7
+ Project-URL: Documentation, https://gridpin.dev/docs
8
+ Project-URL: Repository, https://github.com/gridpin/gridpin
9
+ Project-URL: Issues, https://github.com/gridpin/gridpin/issues
10
+ Keywords: address,address-validation,address-verification,address-check,offline,geocoding,data-quality
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Topic :: Scientific/Engineering :: GIS
14
+ Requires-Python: >=3.10
15
+ Description-Content-Type: text/markdown
16
+ License-File: LICENSE
17
+ Requires-Dist: gridpin<0.12,>=0.11
18
+ Dynamic: license-file
19
+
20
+ # offline-address-check
21
+
22
+ Check whether a street address exists, offline. You get `yes`, `maybe` or `no` with a reason, and the spelling of the
23
+ address as the country's data holds it. There is no API key, and the address is never sent anywhere: it is checked against one file per country on
24
+ your machine.
25
+
26
+ Built on [GridPin](https://github.com/gridpin/gridpin), an offline geocoder.
27
+
28
+ ```bash
29
+ pip install offline-address-check
30
+ offline-address-check "8 rue de Rivoli, Paris" --country fr
31
+ ```
32
+
33
+ ```text
34
+ first use: downloading the France file once, 365 MB, from https://dl.gridpin.dev/…
35
+ yes house_found 8 Rue de Rivoli, 75004 Paris 4e Arrondissement
36
+ ```
37
+
38
+ The exit code is 0 for `yes` and 1 otherwise, so a script can branch on it.
39
+
40
+ ## What it says, and what it does not
41
+
42
+ | Verdict | Reasons |
43
+ |---|---|
44
+ | `yes` | `house_found`: the house with this number is in the data, in the town or postcode the line names |
45
+ | `maybe` | `no_place` (found, but the line names no town or postcode), `street_corrected` (found on a street spelled differently), `number_interpolated`, `no_number`, `postcode_differs`, `town_not_on_sheet`, `weak_answer` |
46
+ | `no` | `street_unknown`, `number_not_on_street`, `wrong_city`, `empty` |
47
+
48
+ `offline-address-check --reasons` prints what each reason means.
49
+
50
+ It checks the address against the country's address data. Some things it does not check:
51
+
52
+ - **Delivery.** It does not tell you whether the post delivers there.
53
+ - **Flats and floors.** It knows houses, not units inside them.
54
+ - **Recent addresses.** A house built after the data was published is not there.
55
+
56
+ Which countries have a file, and what each covers, is on the
57
+ [GridPin countries page](https://gridpin.dev/docs#sheets).
58
+
59
+ A line without a town or postcode is never `yes`. "8 rue de Rivoli" exists in Paris, but a street of the same name may
60
+ exist in another town too, and the line does not say which one is meant.
61
+
62
+ ## Many addresses
63
+
64
+ ```bash
65
+ offline-address-check --country de --file customers.csv --column address --out checked.csv
66
+ ```
67
+
68
+ A plain text file (one address per line) works without `--column`. The output CSV has the columns `address`, `exists`,
69
+ `reason`, `street`, `housenumber`, `place`, `postcode`, `lat`, `lon`.
70
+
71
+ ## From Python
72
+
73
+ ```python
74
+ from offline_address_check import Checker
75
+
76
+ checker = Checker("fr") # downloads the France file once; Checker("fr", download=False) refuses to
77
+ row = checker.check("8 rue de Rivoli, Paris")
78
+ row["exists"], row["reason"] # ('yes', 'house_found')
79
+ ```
80
+
81
+ `Checker("/path/to/france.bin")` opens a file you already have.
82
+
83
+ ## Files
84
+
85
+ The country file is downloaded once into the GridPin cache (`~/.cache/gridpin/`). It is checked against its published
86
+ SHA-256 and then read locally. The files are tens to hundreds of megabytes, and the size is printed before a download.
87
+ `offline-address-check --download fr` fetches one ahead of time. `--no-download` stops instead of downloading.
88
+
89
+ ## Licence
90
+
91
+ This package is licensed under Apache-2.0. The country files carry the licences of their sources, which are listed in
92
+ [ATTRIBUTIONS](https://github.com/gridpin/gridpin/blob/main/ATTRIBUTIONS.md).
@@ -0,0 +1,13 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ src/offline_address_check/__init__.py
5
+ src/offline_address_check/__main__.py
6
+ src/offline_address_check/py.typed
7
+ src/offline_address_check.egg-info/PKG-INFO
8
+ src/offline_address_check.egg-info/SOURCES.txt
9
+ src/offline_address_check.egg-info/dependency_links.txt
10
+ src/offline_address_check.egg-info/entry_points.txt
11
+ src/offline_address_check.egg-info/requires.txt
12
+ src/offline_address_check.egg-info/top_level.txt
13
+ tests/test_check.py
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ offline-address-check = offline_address_check:_entry
@@ -0,0 +1,156 @@
1
+ """offline-address-check against the Monaco smoke sheet: the verdict is the engine's `exists`, except that a house found
2
+ from a line that names no town or postcode is never a `yes`."""
3
+ import csv
4
+ import io
5
+ from pathlib import Path
6
+
7
+ import pytest
8
+
9
+ gridpin = pytest.importorskip("gridpin")
10
+ import offline_address_check as oac # noqa: E402
11
+
12
+ SHEET = Path(__file__).resolve().parents[3] / "data" / "mc.bin"
13
+
14
+
15
+ @pytest.fixture(scope="module")
16
+ def checker():
17
+ if not SHEET.is_file():
18
+ pytest.skip("the Monaco smoke sheet is built by `make mc`")
19
+ return oac.Checker(SHEET)
20
+
21
+
22
+ def test_a_house_in_the_named_town_is_yes_with_the_spelling_of_the_file(checker):
23
+ row = checker.check("2 avenue de la costa, monaco")
24
+ assert (row["exists"], row["reason"]) == ("yes", "house_found")
25
+ assert (row["street"], row["housenumber"], row["place"]) == ("Avenue de la Costa", "2", "Monaco")
26
+ assert row["lat"] and row["lon"]
27
+
28
+
29
+ def test_the_postcode_names_the_place_too(checker):
30
+ assert checker.check("Avenue de la Costa 2, 98000")["exists"] == "yes"
31
+
32
+
33
+ def test_a_house_from_a_line_without_a_town_is_maybe_no_place(checker):
34
+ # the engine alone says yes here; the same street and number may be in another town
35
+ assert gridpin.Geocoder(str(SHEET)).exists("2 Avenue de la Costa")["exists"] == "yes"
36
+ row = checker.check("2 Avenue de la Costa")
37
+ assert (row["exists"], row["reason"]) == ("maybe", "no_place")
38
+ assert row["housenumber"] == "2"
39
+
40
+
41
+ def test_a_number_the_street_does_not_have_is_no(checker):
42
+ row = checker.check("Avenue de la Costa 9999, Monaco")
43
+ assert (row["exists"], row["reason"]) == ("no", "number_not_on_street")
44
+ assert row["street"] == "Avenue de la Costa" # the street is there, the nearest house is not offered as the answer
45
+ assert row["housenumber"] != "9999"
46
+
47
+
48
+ def test_an_invented_street_is_no_and_names_nothing(checker):
49
+ row = checker.check("Rue Quorvalix 3, Monaco")
50
+ assert (row["exists"], row["reason"]) == ("no", "empty")
51
+ assert row["street"] == row["lat"] == ""
52
+
53
+
54
+ def test_a_town_the_file_does_not_know_is_not_yes(checker):
55
+ row = checker.check("2 Avenue de la Costa, Paris")
56
+ assert (row["exists"], row["reason"]) == ("maybe", "town_not_on_sheet")
57
+
58
+
59
+ @pytest.mark.parametrize("line", ["", " "])
60
+ def test_an_empty_line_is_no(checker, line):
61
+ assert (checker.check(line)["exists"], checker.check(line)["reason"]) == ("no", "empty")
62
+
63
+
64
+ def test_names_place_does_not_take_a_word_of_the_street_for_the_town():
65
+ hit = {"street": "Avenue de Paris", "commune": "Paris", "flags": ["street_exact"]}
66
+ assert not oac.names_place("12 Avenue de Paris", hit)
67
+ assert oac.names_place("12 Avenue de Paris, Paris", hit)
68
+ assert oac.names_place("12 Avenue de Paris", dict(hit, flags=["street_exact", "pc_exact"]))
69
+ assert not oac.names_place("12 Avenue de Paris", None)
70
+
71
+
72
+ def test_names_place_reads_a_part_of_the_town_name_without_accents():
73
+ hit = {"street": "Rue de Rivoli", "commune": "Paris 4e Arrondissement", "flags": []}
74
+ assert oac.names_place("8 rue de Rivoli, PARIS", hit)
75
+ hit = {"street": "Hauptstraße", "commune": "Köln", "flags": []}
76
+ assert oac.names_place("Hauptstraße 1, Koln", hit)
77
+
78
+
79
+ def test_every_reason_is_described():
80
+ reasons = {"house_found", "postcode_differs", "number_interpolated", "no_number", "town_not_on_sheet",
81
+ "weak_answer", "no_place", "street_corrected", "street_unknown", "number_not_on_street", "wrong_city", "empty"}
82
+ assert set(oac.REASONS) == reasons
83
+
84
+
85
+ def test_the_cli_answers_one_line_with_its_exit_code(capsys):
86
+ if not SHEET.is_file():
87
+ pytest.skip("no smoke sheet")
88
+ assert oac.main(["2 Avenue de la Costa, Monaco", "--country", str(SHEET)]) == 0
89
+ assert capsys.readouterr().out.startswith("yes\thouse_found\t2 Avenue de la Costa, 98000 Monaco")
90
+ assert oac.main(["Rue Quorvalix 3, Monaco", "--country", str(SHEET)]) == 1
91
+
92
+
93
+ def test_the_cli_checks_a_csv_column(tmp_path):
94
+ if not SHEET.is_file():
95
+ pytest.skip("no smoke sheet")
96
+ src = tmp_path / "in.csv"
97
+ src.write_text("id,addr\n1,\"2 Avenue de la Costa, Monaco\"\n2,2 Avenue de la Costa\n3,\n", encoding="utf-8")
98
+ out = tmp_path / "out.csv"
99
+ assert oac.main(["--file", str(src), "--column", "addr", "--country", str(SHEET), "--out", str(out)]) == 0
100
+ rows = list(csv.DictReader(io.StringIO(out.read_text(encoding="utf-8"))))
101
+ assert [(r["exists"], r["reason"]) for r in rows] == [("yes", "house_found"), ("maybe", "no_place"), ("no", "empty")]
102
+
103
+
104
+ def test_a_missing_country_file_without_download_says_what_to_do(monkeypatch):
105
+ class Sheet:
106
+ name, code, size, url, downloaded = "Poland", "pl", 106_000_000, "https://dl.gridpin.dev/x/pl.bin", False
107
+
108
+ monkeypatch.setattr(gridpin.sheets, "resolve", lambda c: Sheet)
109
+ monkeypatch.setattr(gridpin.sheets, "fetch", lambda c: pytest.fail("must not download"))
110
+ with pytest.raises(FileNotFoundError, match=r"106 MB.*--download pl"):
111
+ oac.Checker("pl", download=False)
112
+
113
+
114
+ def test_a_download_names_its_size_first(monkeypatch, capsys):
115
+ class Sheet:
116
+ name, code, size, url, downloaded = "Poland", "pl", 106_000_000, "https://dl.gridpin.dev/x/pl.bin", False
117
+
118
+ monkeypatch.setattr(gridpin.sheets, "resolve", lambda c: Sheet)
119
+ monkeypatch.setattr(gridpin.sheets, "fetch", lambda c: SHEET)
120
+ if not SHEET.is_file():
121
+ pytest.skip("no smoke sheet")
122
+ oac.Checker("pl")
123
+ assert "106 MB" in capsys.readouterr().err
124
+
125
+
126
+ def test_a_path_that_is_not_there_is_an_error():
127
+ with pytest.raises(FileNotFoundError):
128
+ oac.Checker("/nowhere/xx.bin")
129
+
130
+
131
+ def test_a_street_the_engine_corrected_is_maybe_with_the_spelling_of_the_file(checker):
132
+ # the engine alone says yes: "Avenue" alone is read as Avenue des Spélugues
133
+ assert gridpin.Geocoder(str(SHEET)).exists("Avenue 3, Monaco")["exists"] == "yes"
134
+ row = checker.check("Avenue 3, Monaco")
135
+ assert (row["exists"], row["reason"]) == ("maybe", "street_corrected")
136
+ assert row["street"] == "Avenue des Spélugues"
137
+
138
+
139
+ def test_an_unknown_street_offers_no_place_of_the_town(checker):
140
+ row = checker.check("Monaco") # the engine answers the town; the check names no street and no point
141
+ assert (row["exists"], row["reason"]) == ("no", "street_unknown")
142
+ assert row["place"] == row["lat"] == ""
143
+
144
+
145
+ def test_a_csv_without_the_column_is_an_error_naming_the_columns(tmp_path):
146
+ if not SHEET.is_file():
147
+ pytest.skip("no smoke sheet")
148
+ src = tmp_path / "in.csv"
149
+ src.write_text("id,addr\n1,x\n", encoding="utf-8")
150
+ with pytest.raises(SystemExit, match="columns: id, addr"):
151
+ oac.main(["--file", str(src), "--column", "address", "--country", str(SHEET)])
152
+
153
+
154
+ def test_a_blank_line_is_not_sent_to_the_engine(checker, monkeypatch):
155
+ monkeypatch.setattr(checker, "_g", None) # any call to the engine would fail
156
+ assert checker.check(" ")["reason"] == "empty"