Model/backend/OrdnanceSurvey.py
2023-12-30 20:48:40 +00:00

77 lines
2.8 KiB
Python

from functools import lru_cache
import urllib.parse
import requests
from utils.logger import setup_logger
logger = setup_logger()
class OrdnanceSuveyClient:
def __init__(self, address, postcode, api_key):
"""
This class is tasked with interaction with the ordnance survey API.
:param address: The address for the property to search for
:param postcode: The postcode for the property to search for
"""
self.address = address
self.postcode = postcode
self.full_address = ", ".join([self.address, self.postcode])
self.api_key = api_key
self.results = None
@lru_cache(maxsize=128)
def get_places_api(self):
"""
This method is tasked with getting the places api from the Ordnance Survey.
"""
if not self.api_key:
raise ValueError("Ordnance Survey API key not specified")
encoded_address_query = urllib.parse.quote(self.full_address)
url = (f"https://api.os.uk/search/places/v1/find?query={encoded_address_query}&key="
f"{self.api_key}")
response = requests.get(url)
if response.status_code == 200:
data = response.json()
# Extract the UPRN from the data
# Note: This example assumes that the first result is the correct one, which might not always be the case.
results = data['results']
self.results = results
else:
logger.info("Could not find any results for the provided address and postcode")
return
@staticmethod
def parse_classification_code(classification_code: str):
"""
This function will convert the classification code, returned by the OS places api, to a property type that is
compatible with the EPC database.
The various classifications cane be found here:
https://osdatahub.os.uk/docs/places/technicalSpecification
Under LPI Output, CLASSIFICATION_CODE is described, and a link is provided to the full table of classifications
For these purposes, we do not need the full classification as this includes non-residential properties. We only
parse the ones of interest to us
:return:
"""
value_map = {
# In the OS api, "RD" is a "Dwelling" however this is not valid property type in the EPC database
'RD': {},
'RD02': {'property_type': 'House', 'built_form': 'Detatched'},
'RD03': {'property_type': 'House', 'built_form': 'Semi-Detatched'},
'RD04': {'property_type': 'House', 'built_form': 'Mid-Terrace'},
'RD06': {'property_type': 'Flat'},
}
mapped = value_map.get(classification_code, {})
property_type = mapped.get("property_type", "")
built_form = mapped.get("built_form", "")
return property_type, built_form