adres-tr 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,32 @@
1
+ # Python
2
+ __pycache__/
3
+ *.py[cod]
4
+ *.egg-info/
5
+ .eggs/
6
+
7
+ # Build
8
+ build/
9
+ dist/
10
+
11
+ # Virtual environments
12
+ .venv/
13
+ venv/
14
+ env/
15
+
16
+ # Secrets
17
+ .env
18
+ .env.*
19
+ *.pem
20
+ .pypirc
21
+
22
+ # Test / tool output
23
+ .pytest_cache/
24
+ .ruff_cache/
25
+ .coverage
26
+ htmlcov/
27
+
28
+ # Editor / OS
29
+ .vscode/
30
+ .idea/
31
+ .DS_Store
32
+ Thumbs.db
adres_tr-0.1.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Arda Zeybek
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,199 @@
1
+ Metadata-Version: 2.5
2
+ Name: adres-tr
3
+ Version: 0.1.0
4
+ Summary: Split free-form Turkish addresses into province, district, neighbourhood, street, building number, floor and flat. Official list of 81 provinces and 973 districts with postal ranges, no dependencies.
5
+ Project-URL: Homepage, https://github.com/ardazeybek-dev/adres
6
+ Project-URL: Repository, https://github.com/ardazeybek-dev/adres
7
+ Project-URL: Issues, https://github.com/ardazeybek-dev/adres/issues
8
+ Author-email: Arda Zeybek <179981861+ardazeybek-dev@users.noreply.github.com>
9
+ License-Expression: MIT
10
+ License-File: LICENSE
11
+ Keywords: address,address parser,adres,il,ilce,mahalle,posta kodu,postal code,turkey,turkish
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Environment :: Console
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Natural Language :: Turkish
16
+ Classifier: Operating System :: OS Independent
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3.10
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Classifier: Programming Language :: Python :: 3.13
22
+ Classifier: Topic :: Text Processing :: Linguistic
23
+ Classifier: Typing :: Typed
24
+ Requires-Python: >=3.10
25
+ Provides-Extra: dev
26
+ Requires-Dist: pytest>=8; extra == 'dev'
27
+ Requires-Dist: ruff>=0.6; extra == 'dev'
28
+ Description-Content-Type: text/markdown
29
+
30
+ # adres
31
+
32
+ [![CI](https://github.com/ardazeybek-dev/adres/actions/workflows/ci.yml/badge.svg)](https://github.com/ardazeybek-dev/adres/actions/workflows/ci.yml)
33
+ [![PyPI](https://img.shields.io/pypi/v/adres-tr.svg)](https://pypi.org/project/adres-tr/)
34
+
35
+ Split free-form Turkish addresses into their parts: province, district,
36
+ neighbourhood, avenue, street, building number, floor, flat and postal code.
37
+
38
+ Addresses typed into checkout forms, CRMs and spreadsheets come in every shape:
39
+ `KADIKÖY/İST.`, `kadikoy istanbul`, `No:12/3`, `D:3`, `Kat 2`, `1453 Sk.`,
40
+ `Mah.Moda Cad.` with no space. `adres` reads them all and checks the province
41
+ and district against the official list of **81 provinces and 973 districts**.
42
+ No dependencies, no network calls.
43
+
44
+ ```bash
45
+ pip install adres-tr
46
+ ```
47
+
48
+ ```python
49
+ >>> from adres import parse
50
+ >>> a = parse("Caferağa Mah. Moda Cad. No:12/3 34710 Kadıköy/İSTANBUL")
51
+ >>> a.neighbourhood, a.avenue, a.building_no, a.apartment
52
+ ('Caferağa', 'Moda', '12', '3')
53
+ >>> a.district, a.province, a.plate
54
+ ('Kadıköy', 'İstanbul', 34)
55
+ >>> parse("bostanci mh. bagdat cd no 21 kadikoy istanbul").format()
56
+ 'Bostanci Mah. Bagdat Cad. No:21 Kadıköy/İstanbul'
57
+ ```
58
+
59
+ ## What it handles
60
+
61
+ | Input | Result |
62
+ | --- | --- |
63
+ | `Kadıköy/İstanbul`, `Bornova - İzmir`, `ÇANKAYA ANKARA` | district + province, official spelling |
64
+ | `kagithane istanbul`, `IĞDIR`, `Hakkari` | `Kâğıthane`, `Iğdır`, `Hakkâri` (Turkish I/İ handled) |
65
+ | `Mah.` `Mh.` `Mahallesi` · `Cad.` `Cd.` · `Sk.` `Sok.` · `Blv.` · `Sitesi` · `Apt.` · `Köyü` | neighbourhood, avenue, street, boulevard, site, building, village |
66
+ | `No:12/3`, `No 12`, `Atatürk Cad. 36/1` | building number 12/36, flat 3/1 |
67
+ | `Kat:2`, `2. Kat`, `Zemin Kat`, `D:3`, `Daire 4`, `İç Kapı No:5` | floor, flat |
68
+ | `B Blok`, `Blok A`, `5. Blok` | block |
69
+ | `12. Sokak`, `1453 Sk.`, `372/8 Sokak` | numbered streets (not taken for door numbers) |
70
+ | `Merkez/Kütahya`, `Hakkari merkez` | the central district |
71
+ | `Afyon`, `Antep`, `Urfa`, `K.Maraş`, `İçel`, `İST.`, `Eyüp`, `Kazan` | current official names |
72
+ | `Haliliye`, `Bodrum`, `Atakum` alone | province filled in from the district |
73
+ | `16000` alone | province from the postal code (first two digits = plate number) |
74
+
75
+ When it is not sure, it says so instead of guessing:
76
+
77
+ ```python
78
+ >>> a = parse("Selimiye Mah. Ereğli") # Ereğli is in Konya and in Zonguldak
79
+ >>> a.district, a.province
80
+ (None, None)
81
+ >>> a.warnings
82
+ ["district 'Ereğli' exists in Konya, Zonguldak; province needed"]
83
+ >>> parse("Moda Cad. No:5 Kahve Dünyası yanı Kadıköy").rest
84
+ 'Kahve Dünyası yanı'
85
+ ```
86
+
87
+ Text it does not recognise goes to `rest`, so nothing is silently dropped. A
88
+ postal code that belongs to another province than the one written adds a warning.
89
+
90
+ ## Fields
91
+
92
+ `parse()` returns an `Address`. Every field is a string or `None`.
93
+
94
+ | Field | Turkish | Example |
95
+ | --- | --- | --- |
96
+ | `province` | il | `İstanbul` |
97
+ | `district` | ilçe | `Kadıköy` |
98
+ | `neighbourhood` | mahalle | `Caferağa` |
99
+ | `village` | köy | `Karaağaç` |
100
+ | `boulevard` | bulvar | `Atatürk` |
101
+ | `avenue` | cadde | `Moda` |
102
+ | `street` | sokak | `1453` |
103
+ | `site` | site | `Ihlamur` |
104
+ | `building` | apartman | `Gül` |
105
+ | `block` | blok | `B` |
106
+ | `building_no` | kapı no | `12` |
107
+ | `floor` | kat | `2` (`0` ground, `-1` basement) |
108
+ | `apartment` | daire / iç kapı | `3` |
109
+ | `postal_code` | posta kodu | `34710` |
110
+ | `plate` | plaka (int) | `34` |
111
+ | `rest` | | unrecognised text |
112
+ | `warnings` | | list of doubts |
113
+
114
+ `a.to_dict()` gives a plain dict, `a.format()` the cleaned one-line address.
115
+
116
+ ## Lookups
117
+
118
+ ```python
119
+ >>> from adres import districts, plate_of, provinces, lookup_postal_code
120
+ >>> len(provinces()), len(districts("istanbul"))
121
+ (81, 39)
122
+ >>> plate_of("K.Maraş"), plate_of("IĞDIR")
123
+ (46, 76)
124
+ >>> lookup_postal_code("34710")
125
+ ('İstanbul', 'Kadıköy')
126
+ >>> lookup_postal_code("06830") # two district ranges overlap: no guess
127
+ ('Ankara', None)
128
+ ```
129
+
130
+ ## Command line
131
+
132
+ ```bash
133
+ adres "Caferağa Mah. Moda Cad. No:12/3 Kadıköy/İstanbul" # JSON
134
+ adres --line < addresses.txt # one cleaned address per line
135
+ adres --csv < addresses.txt > addresses.csv # one column per part
136
+ ```
137
+
138
+ Without `--line` or `--csv`, several input lines are printed as JSON Lines.
139
+
140
+ ## Limits
141
+
142
+ - Neighbourhood, street and site names are taken from the text as written
143
+ (title-cased), not checked against a list: `bostanci` stays `Bostanci`.
144
+ - A district written without its province is resolved only when the name is
145
+ unique in Turkey (23 names such as Ereğli, Gölbaşı and Yenişehir are not).
146
+ - Postal ranges come from the district list and overlap in places, so a postal
147
+ code alone gives the district only when exactly one range holds it.
148
+
149
+ ## Data
150
+
151
+ `src/adres/_data.py` is generated by `scripts/build_data.py` from the table in
152
+ the Turkish Wikipedia article
153
+ [Türkiye'nin ilçeleri](https://tr.wikipedia.org/w/index.php?oldid=37373921),
154
+ pinned to one revision (CC BY-SA 4.0). The script checks for 81 provinces and
155
+ 973 districts and that every postal range starts with its province's plate
156
+ number. Five ranges in the source failed that check: two obvious typos are
157
+ corrected, three are left empty (see `POSTAL_FIXES` in the script).
158
+
159
+ ```bash
160
+ python scripts/build_data.py # regenerate from the pinned revision
161
+ ```
162
+
163
+ ## Development
164
+
165
+ ```bash
166
+ python -m venv .venv
167
+ .venv/bin/pip install -e ".[dev]" # Windows: .venv\Scripts\pip
168
+ pytest
169
+ ruff check . && ruff format --check .
170
+ ```
171
+
172
+ ```
173
+ src/adres/
174
+ address.py parse() and Address
175
+ places.py province/district lookups, aliases, postal codes
176
+ text.py Turkish-aware lower/upper/fold/title
177
+ _data.py generated official list (do not edit)
178
+ cli.py the adres command
179
+ scripts/build_data.py
180
+ tests/test_golden.py real-world style addresses and their expected parts
181
+ ```
182
+
183
+ ## Pitfalls
184
+
185
+ - `"İSTANBUL".lower()` in Python is `"i̇stanbul"` (with a combining dot), and
186
+ `"ISPARTA".lower()` is `"isparta"` instead of `"ısparta"` → compare with
187
+ `adres.fold()`, never with `str.lower()`.
188
+ - Wikipedia lists Zonguldak's district as "Karadeniz Ereğli" to tell it apart
189
+ from Konya's; the official name is Ereğli → keep the rename in `DISTRICT_NAMES`
190
+ when regenerating the data.
191
+
192
+ ## Related
193
+
194
+ - [trkit](https://github.com/ardazeybek-dev/trkit) / [trkit-js](https://github.com/ardazeybek-dev/trkit-js): TC kimlik, VKN, IBAN, phone numbers, Turkish casing
195
+ - [ekstre](https://github.com/ardazeybek-dev/ekstre): Turkish bank statement exports into typed transactions
196
+
197
+ ## License
198
+
199
+ MIT
@@ -0,0 +1,170 @@
1
+ # adres
2
+
3
+ [![CI](https://github.com/ardazeybek-dev/adres/actions/workflows/ci.yml/badge.svg)](https://github.com/ardazeybek-dev/adres/actions/workflows/ci.yml)
4
+ [![PyPI](https://img.shields.io/pypi/v/adres-tr.svg)](https://pypi.org/project/adres-tr/)
5
+
6
+ Split free-form Turkish addresses into their parts: province, district,
7
+ neighbourhood, avenue, street, building number, floor, flat and postal code.
8
+
9
+ Addresses typed into checkout forms, CRMs and spreadsheets come in every shape:
10
+ `KADIKÖY/İST.`, `kadikoy istanbul`, `No:12/3`, `D:3`, `Kat 2`, `1453 Sk.`,
11
+ `Mah.Moda Cad.` with no space. `adres` reads them all and checks the province
12
+ and district against the official list of **81 provinces and 973 districts**.
13
+ No dependencies, no network calls.
14
+
15
+ ```bash
16
+ pip install adres-tr
17
+ ```
18
+
19
+ ```python
20
+ >>> from adres import parse
21
+ >>> a = parse("Caferağa Mah. Moda Cad. No:12/3 34710 Kadıköy/İSTANBUL")
22
+ >>> a.neighbourhood, a.avenue, a.building_no, a.apartment
23
+ ('Caferağa', 'Moda', '12', '3')
24
+ >>> a.district, a.province, a.plate
25
+ ('Kadıköy', 'İstanbul', 34)
26
+ >>> parse("bostanci mh. bagdat cd no 21 kadikoy istanbul").format()
27
+ 'Bostanci Mah. Bagdat Cad. No:21 Kadıköy/İstanbul'
28
+ ```
29
+
30
+ ## What it handles
31
+
32
+ | Input | Result |
33
+ | --- | --- |
34
+ | `Kadıköy/İstanbul`, `Bornova - İzmir`, `ÇANKAYA ANKARA` | district + province, official spelling |
35
+ | `kagithane istanbul`, `IĞDIR`, `Hakkari` | `Kâğıthane`, `Iğdır`, `Hakkâri` (Turkish I/İ handled) |
36
+ | `Mah.` `Mh.` `Mahallesi` · `Cad.` `Cd.` · `Sk.` `Sok.` · `Blv.` · `Sitesi` · `Apt.` · `Köyü` | neighbourhood, avenue, street, boulevard, site, building, village |
37
+ | `No:12/3`, `No 12`, `Atatürk Cad. 36/1` | building number 12/36, flat 3/1 |
38
+ | `Kat:2`, `2. Kat`, `Zemin Kat`, `D:3`, `Daire 4`, `İç Kapı No:5` | floor, flat |
39
+ | `B Blok`, `Blok A`, `5. Blok` | block |
40
+ | `12. Sokak`, `1453 Sk.`, `372/8 Sokak` | numbered streets (not taken for door numbers) |
41
+ | `Merkez/Kütahya`, `Hakkari merkez` | the central district |
42
+ | `Afyon`, `Antep`, `Urfa`, `K.Maraş`, `İçel`, `İST.`, `Eyüp`, `Kazan` | current official names |
43
+ | `Haliliye`, `Bodrum`, `Atakum` alone | province filled in from the district |
44
+ | `16000` alone | province from the postal code (first two digits = plate number) |
45
+
46
+ When it is not sure, it says so instead of guessing:
47
+
48
+ ```python
49
+ >>> a = parse("Selimiye Mah. Ereğli") # Ereğli is in Konya and in Zonguldak
50
+ >>> a.district, a.province
51
+ (None, None)
52
+ >>> a.warnings
53
+ ["district 'Ereğli' exists in Konya, Zonguldak; province needed"]
54
+ >>> parse("Moda Cad. No:5 Kahve Dünyası yanı Kadıköy").rest
55
+ 'Kahve Dünyası yanı'
56
+ ```
57
+
58
+ Text it does not recognise goes to `rest`, so nothing is silently dropped. A
59
+ postal code that belongs to another province than the one written adds a warning.
60
+
61
+ ## Fields
62
+
63
+ `parse()` returns an `Address`. Every field is a string or `None`.
64
+
65
+ | Field | Turkish | Example |
66
+ | --- | --- | --- |
67
+ | `province` | il | `İstanbul` |
68
+ | `district` | ilçe | `Kadıköy` |
69
+ | `neighbourhood` | mahalle | `Caferağa` |
70
+ | `village` | köy | `Karaağaç` |
71
+ | `boulevard` | bulvar | `Atatürk` |
72
+ | `avenue` | cadde | `Moda` |
73
+ | `street` | sokak | `1453` |
74
+ | `site` | site | `Ihlamur` |
75
+ | `building` | apartman | `Gül` |
76
+ | `block` | blok | `B` |
77
+ | `building_no` | kapı no | `12` |
78
+ | `floor` | kat | `2` (`0` ground, `-1` basement) |
79
+ | `apartment` | daire / iç kapı | `3` |
80
+ | `postal_code` | posta kodu | `34710` |
81
+ | `plate` | plaka (int) | `34` |
82
+ | `rest` | | unrecognised text |
83
+ | `warnings` | | list of doubts |
84
+
85
+ `a.to_dict()` gives a plain dict, `a.format()` the cleaned one-line address.
86
+
87
+ ## Lookups
88
+
89
+ ```python
90
+ >>> from adres import districts, plate_of, provinces, lookup_postal_code
91
+ >>> len(provinces()), len(districts("istanbul"))
92
+ (81, 39)
93
+ >>> plate_of("K.Maraş"), plate_of("IĞDIR")
94
+ (46, 76)
95
+ >>> lookup_postal_code("34710")
96
+ ('İstanbul', 'Kadıköy')
97
+ >>> lookup_postal_code("06830") # two district ranges overlap: no guess
98
+ ('Ankara', None)
99
+ ```
100
+
101
+ ## Command line
102
+
103
+ ```bash
104
+ adres "Caferağa Mah. Moda Cad. No:12/3 Kadıköy/İstanbul" # JSON
105
+ adres --line < addresses.txt # one cleaned address per line
106
+ adres --csv < addresses.txt > addresses.csv # one column per part
107
+ ```
108
+
109
+ Without `--line` or `--csv`, several input lines are printed as JSON Lines.
110
+
111
+ ## Limits
112
+
113
+ - Neighbourhood, street and site names are taken from the text as written
114
+ (title-cased), not checked against a list: `bostanci` stays `Bostanci`.
115
+ - A district written without its province is resolved only when the name is
116
+ unique in Turkey (23 names such as Ereğli, Gölbaşı and Yenişehir are not).
117
+ - Postal ranges come from the district list and overlap in places, so a postal
118
+ code alone gives the district only when exactly one range holds it.
119
+
120
+ ## Data
121
+
122
+ `src/adres/_data.py` is generated by `scripts/build_data.py` from the table in
123
+ the Turkish Wikipedia article
124
+ [Türkiye'nin ilçeleri](https://tr.wikipedia.org/w/index.php?oldid=37373921),
125
+ pinned to one revision (CC BY-SA 4.0). The script checks for 81 provinces and
126
+ 973 districts and that every postal range starts with its province's plate
127
+ number. Five ranges in the source failed that check: two obvious typos are
128
+ corrected, three are left empty (see `POSTAL_FIXES` in the script).
129
+
130
+ ```bash
131
+ python scripts/build_data.py # regenerate from the pinned revision
132
+ ```
133
+
134
+ ## Development
135
+
136
+ ```bash
137
+ python -m venv .venv
138
+ .venv/bin/pip install -e ".[dev]" # Windows: .venv\Scripts\pip
139
+ pytest
140
+ ruff check . && ruff format --check .
141
+ ```
142
+
143
+ ```
144
+ src/adres/
145
+ address.py parse() and Address
146
+ places.py province/district lookups, aliases, postal codes
147
+ text.py Turkish-aware lower/upper/fold/title
148
+ _data.py generated official list (do not edit)
149
+ cli.py the adres command
150
+ scripts/build_data.py
151
+ tests/test_golden.py real-world style addresses and their expected parts
152
+ ```
153
+
154
+ ## Pitfalls
155
+
156
+ - `"İSTANBUL".lower()` in Python is `"i̇stanbul"` (with a combining dot), and
157
+ `"ISPARTA".lower()` is `"isparta"` instead of `"ısparta"` → compare with
158
+ `adres.fold()`, never with `str.lower()`.
159
+ - Wikipedia lists Zonguldak's district as "Karadeniz Ereğli" to tell it apart
160
+ from Konya's; the official name is Ereğli → keep the rename in `DISTRICT_NAMES`
161
+ when regenerating the data.
162
+
163
+ ## Related
164
+
165
+ - [trkit](https://github.com/ardazeybek-dev/trkit) / [trkit-js](https://github.com/ardazeybek-dev/trkit-js): TC kimlik, VKN, IBAN, phone numbers, Turkish casing
166
+ - [ekstre](https://github.com/ardazeybek-dev/ekstre): Turkish bank statement exports into typed transactions
167
+
168
+ ## License
169
+
170
+ MIT
@@ -0,0 +1,66 @@
1
+ [build-system]
2
+ requires = ["hatchling>=1.27"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "adres-tr"
7
+ dynamic = ["version"]
8
+ description = "Split free-form Turkish addresses into province, district, neighbourhood, street, building number, floor and flat. Official list of 81 provinces and 973 districts with postal ranges, no dependencies."
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ license-files = ["LICENSE"]
12
+ requires-python = ">=3.10"
13
+ authors = [
14
+ { name = "Arda Zeybek", email = "179981861+ardazeybek-dev@users.noreply.github.com" },
15
+ ]
16
+ keywords = ["turkish", "turkey", "address", "adres", "address parser", "il", "ilce", "mahalle", "postal code", "posta kodu"]
17
+ classifiers = [
18
+ "Development Status :: 4 - Beta",
19
+ "Environment :: Console",
20
+ "Intended Audience :: Developers",
21
+ "Natural Language :: Turkish",
22
+ "Operating System :: OS Independent",
23
+ "Programming Language :: Python :: 3",
24
+ "Programming Language :: Python :: 3.10",
25
+ "Programming Language :: Python :: 3.11",
26
+ "Programming Language :: Python :: 3.12",
27
+ "Programming Language :: Python :: 3.13",
28
+ "Topic :: Text Processing :: Linguistic",
29
+ "Typing :: Typed",
30
+ ]
31
+ dependencies = []
32
+
33
+ [project.optional-dependencies]
34
+ dev = ["pytest>=8", "ruff>=0.6"]
35
+
36
+ [project.urls]
37
+ Homepage = "https://github.com/ardazeybek-dev/adres"
38
+ Repository = "https://github.com/ardazeybek-dev/adres"
39
+ Issues = "https://github.com/ardazeybek-dev/adres/issues"
40
+
41
+ [project.scripts]
42
+ adres = "adres.cli:main"
43
+
44
+ [tool.hatch.version]
45
+ path = "src/adres/__init__.py"
46
+
47
+ [tool.hatch.build.targets.wheel]
48
+ packages = ["src/adres"]
49
+
50
+ [tool.hatch.build.targets.sdist]
51
+ include = ["src/adres", "tests", "scripts", "README.md", "LICENSE"]
52
+
53
+ [tool.ruff]
54
+ line-length = 100
55
+ target-version = "py310"
56
+
57
+ [tool.ruff.lint]
58
+ select = ["E", "F", "I", "UP", "B", "SIM"]
59
+
60
+ [tool.ruff.format]
61
+ exclude = ["*.md"]
62
+
63
+ [tool.pytest.ini_options]
64
+ testpaths = ["tests", "src"]
65
+ pythonpath = ["tests"]
66
+ addopts = "-q --doctest-modules --import-mode=importlib"
@@ -0,0 +1,140 @@
1
+ """Regenerate ``src/adres/_data.py`` from Turkish Wikipedia.
2
+
3
+ The source is the table in "Türkiye'nin ilçeleri" (list of districts of
4
+ Turkey), pinned to one revision so the output is reproducible. Place names and
5
+ postal codes are facts; the table itself is CC BY-SA, credited in the README.
6
+
7
+ python scripts/build_data.py # download the pinned revision
8
+ python scripts/build_data.py page.json # or use a saved API response
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import json
14
+ import re
15
+ import sys
16
+ import urllib.request
17
+ from collections import Counter
18
+ from pathlib import Path
19
+
20
+ REVISION = 37373921 # 2026-06-23
21
+ API = (
22
+ "https://tr.wikipedia.org/w/api.php?action=parse&oldid={rev}"
23
+ "&prop=wikitext&format=json&formatversion=2"
24
+ )
25
+ OUT = Path(__file__).resolve().parent.parent / "src" / "adres" / "_data.py"
26
+
27
+ # Postal ranges in the source whose prefix does not match the province.
28
+ # Obvious one-digit typos are corrected; the rest are dropped rather than guessed.
29
+ POSTAL_FIXES = {
30
+ ("Giresun", "Yağlıdere"): "28610–28612",
31
+ ("Kars", "Arpaçay"): "36730–36732",
32
+ ("Artvin", "Kemalpaşa"): "",
33
+ ("Denizli", "Baklan"): "",
34
+ ("İzmir", "Menderes"): "",
35
+ }
36
+
37
+ # The article disambiguates two districts by name; use the official names.
38
+ DISTRICT_NAMES = {
39
+ ("Zonguldak", "Karadeniz Ereğli"): "Ereğli",
40
+ }
41
+
42
+
43
+ def fetch(source: str | None) -> str:
44
+ if source:
45
+ raw = Path(source).read_text(encoding="utf-8")
46
+ else:
47
+ req = urllib.request.Request(
48
+ API.format(rev=REVISION), headers={"User-Agent": "adres-build-data/1.0"}
49
+ )
50
+ with urllib.request.urlopen(req, timeout=30) as resp:
51
+ raw = resp.read().decode("utf-8")
52
+ return json.loads(raw)["parse"]["wikitext"]
53
+
54
+
55
+ def _cell(text: str) -> str:
56
+ text = re.sub(r'^\s*style="[^"]*"\s*\|', "", text)
57
+ text = re.sub(r'^\s*rowspan="\d+"\s*\|', "", text)
58
+ text = re.sub(r"<ref[^>]*/>|<ref.*?</ref>", "", text)
59
+ text = re.sub(r"\{\{[^}]*\}\}", "", text).replace("'''", "")
60
+ link = re.search(r"\[\[(?:[^|\]]*\|)?([^\]]*)\]\]", text)
61
+ return (link.group(1) if link else text).strip()
62
+
63
+
64
+ def parse_table(wikitext: str) -> list[tuple[str, str, str]]:
65
+ table = wikitext[wikitext.index("{|") :]
66
+ table = table[: table.index("\n|}")]
67
+ rows = []
68
+ for block in table.split("\n|-")[1:]:
69
+ cells = [_cell(line[1:]) for line in block.strip().split("\n") if line.startswith("|")]
70
+ if len(cells) >= 9:
71
+ rows.append((cells[0], cells[1], cells[8]))
72
+ return rows
73
+
74
+
75
+ def ranges(text: str) -> list[tuple[int, int]]:
76
+ out = []
77
+ for part in text.split(","):
78
+ codes = re.findall(r"\d{5}", part)
79
+ if codes:
80
+ out.append((int(codes[0]), int(codes[-1])))
81
+ return out
82
+
83
+
84
+ def build(rows: list[tuple[str, str, str]]) -> str:
85
+ provinces = sorted({il for il, _, _ in rows})
86
+ if len(provinces) != 81 or len(rows) != 973:
87
+ raise SystemExit(f"expected 81 provinces / 973 districts, got {len(provinces)}/{len(rows)}")
88
+
89
+ fixed = [
90
+ (il, DISTRICT_NAMES.get((il, ilce), ilce), POSTAL_FIXES.get((il, ilce), posta))
91
+ for il, ilce, posta in rows
92
+ ]
93
+
94
+ # The first two digits of a postal code are the province's plate number.
95
+ prefixes: dict[str, Counter[int]] = {il: Counter() for il in provinces}
96
+ for il, _, posta in fixed:
97
+ for lo, hi in ranges(posta):
98
+ prefixes[il].update([lo // 1000, hi // 1000])
99
+ plate = {il: prefixes[il].most_common(1)[0][0] for il in provinces}
100
+ if sorted(plate.values()) != list(range(1, 82)):
101
+ raise SystemExit("plate numbers derived from postal codes are not 1..81")
102
+ for il, ilce, posta in fixed:
103
+ for lo, hi in ranges(posta):
104
+ if lo // 1000 != plate[il] or hi // 1000 != plate[il]:
105
+ raise SystemExit(f"postal range {posta} does not belong to {il} ({ilce})")
106
+
107
+ lines = [
108
+ '"""Provinces, districts and postal ranges of Turkey.',
109
+ "",
110
+ "Generated by scripts/build_data.py from Turkish Wikipedia, article",
111
+ f'"Türkiye\'nin ilçeleri", revision {REVISION} (CC BY-SA). Do not edit by hand.',
112
+ '"""',
113
+ "",
114
+ "# plate number -> province",
115
+ "PROVINCES: dict[int, str] = {",
116
+ ]
117
+ for il in sorted(provinces, key=plate.__getitem__):
118
+ lines.append(f" {plate[il]}: {json.dumps(il, ensure_ascii=False)},")
119
+ lines += [
120
+ "}",
121
+ "",
122
+ "# (plate number, district, ((first postal code, last postal code), ...))",
123
+ "DISTRICTS: tuple[tuple[int, str, tuple[tuple[int, int], ...]], ...] = (",
124
+ ]
125
+ for il, ilce, posta in sorted(fixed, key=lambda r: (plate[r[0]], r[1])):
126
+ rng = "".join(f"({lo}, {hi}), " for lo, hi in ranges(posta)).rstrip(", ")
127
+ rng = f"({rng},)" if rng else "()"
128
+ lines.append(f" ({plate[il]}, {json.dumps(ilce, ensure_ascii=False)}, {rng}),")
129
+ lines += [")", ""]
130
+ return "\n".join(lines)
131
+
132
+
133
+ def main() -> None:
134
+ rows = parse_table(fetch(sys.argv[1] if len(sys.argv) > 1 else None))
135
+ OUT.write_text(build(rows), encoding="utf-8", newline="\n")
136
+ print(f"wrote {OUT} ({len(rows)} districts)")
137
+
138
+
139
+ if __name__ == "__main__":
140
+ main()
@@ -0,0 +1,17 @@
1
+ """Split free-form Turkish addresses into province, district, neighbourhood, street and number."""
2
+
3
+ from .address import Address, parse
4
+ from .places import districts, lookup_postal_code, plate_of, provinces
5
+ from .text import fold
6
+
7
+ __version__ = "0.1.0"
8
+
9
+ __all__ = [
10
+ "Address",
11
+ "districts",
12
+ "fold",
13
+ "lookup_postal_code",
14
+ "parse",
15
+ "plate_of",
16
+ "provinces",
17
+ ]
@@ -0,0 +1,3 @@
1
+ from .cli import main
2
+
3
+ raise SystemExit(main())