Add types and docstrings + upgrade to SQLAlchmey 2

This commit is contained in:
Edward Betts 2023-11-01 20:54:19 +00:00
parent 82671959bb
commit 5e8d1a99b0
8 changed files with 248 additions and 125 deletions

View file

@ -1,17 +1,24 @@
from collections import OrderedDict
"""Nominatim."""
import json
import typing
from collections import OrderedDict
import requests
from . import CallParams
Hit = dict[str, typing.Any]
class SearchError(Exception):
pass
"""Search error."""
def lookup_with_params(**kwargs):
def lookup_with_params(**kwargs: str) -> list[Hit]:
url = "http://nominatim.openstreetmap.org/search"
params = {
params: CallParams = {
"format": "jsonv2",
"addressdetails": 1,
"extratags": 1,
@ -26,21 +33,24 @@ def lookup_with_params(**kwargs):
raise SearchError
try:
return json.loads(r.text, object_pairs_hook=OrderedDict)
reply: list[Hit] = json.loads(r.text, object_pairs_hook=OrderedDict)
return reply
except json.decoder.JSONDecodeError:
raise SearchError(r)
def lookup(q):
def lookup(q: str) -> list[Hit]:
"""Nominatim search."""
return lookup_with_params(q=q)
def get_us_county(county, state):
def get_us_county(county: str, state: str) -> Hit | None:
"""Search for US county and return resulting hit."""
if " " not in county and "county" not in county:
county += " county"
results = lookup(q="{}, {}".format(county, state))
def pred(hit):
def pred(hit: Hit) -> typing.TypeGuard[Hit]:
return (
"osm_type" in hit
and hit["osm_type"] != "node"
@ -50,7 +60,8 @@ def get_us_county(county, state):
return next(filter(pred, results), None)
def get_us_city(name, state):
def get_us_city(name: str, state: str) -> Hit | None:
"""Search for US city and return resulting hit."""
results = lookup_with_params(city=name, state=state)
if len(results) != 1:
results = [
@ -58,29 +69,32 @@ def get_us_city(name, state):
]
if len(results) != 1:
print("more than one")
return
return None
hit = results[0]
if hit["type"] not in ("administrative", "city"):
print("not a city")
return
return None
if hit["osm_type"] == "node":
print("node")
return
return None
if not hit["display_name"].startswith(name):
print("wrong name")
return
return None
assert "osm_type" in hit and "osm_id" in hit and "geotext" in hit
return hit
def get_hit_name(hit):
def get_hit_name(hit: Hit) -> str:
"""Get name from hit."""
address = hit.get("address")
if not address:
assert isinstance(hit["display_name"], str)
return hit["display_name"]
address_values = list(address.values())
n1 = address_values[0]
if len(address) == 1:
assert isinstance(n1, str)
return n1
country = address.pop("country", None)
@ -102,13 +116,15 @@ def get_hit_name(hit):
return f"{n1}, {n2}, {country}"
def get_hit_label(hit):
def get_hit_label(hit: Hit) -> str:
"""Parse hit and generate label."""
tags = hit["extratags"]
designation = tags.get("designation")
category = hit["category"]
hit_type = hit["type"]
if designation:
assert isinstance(designation, str)
return designation.replace("_", " ")
if category == "boundary" and hit_type == "administrative":