Better logging + cleanup.
[python_utils.git] / geocode.py
1 #!/usr/bin/env python3
2
3 # © Copyright 2022, Scott Gasch
4
5 """Wrapper around US Census address geocoder API described here:
6 https://www2.census.gov/geo/pdfs/maps-data/data/Census_Geocoder_User_Guide.pdf
7 https://geocoding.geo.census.gov/geocoder/Geocoding_Services_API.pdf
8 """
9
10 import json
11 import logging
12 from typing import Any, Dict, List, Optional
13
14 import requests
15 from requests.utils import requote_uri
16
17 import list_utils
18
19 logger = logging.getLogger(__name__)
20
21
22 def geocode_address(address: str) -> Optional[Dict[str, Any]]:
23     """Send a single address to the US Census geocoding API.  The response
24     is a parsed JSON chunk of data with N addressMatches in the result
25     section and the details of each match within it.  Returns None on error.
26
27     >>> json = geocode_address('4600 Silver Hill Rd,, 20233')
28     >>> json['result']['addressMatches'][0]['matchedAddress']
29     '4600 SILVER HILL RD, WASHINGTON, DC, 20233'
30
31     >>> json['result']['addressMatches'][0]['coordinates']
32     {'x': -76.92743, 'y': 38.84599}
33
34     """
35     url = 'https://geocoding.geo.census.gov/geocoder/geographies/onelineaddress'
36     url += f'?address={address}'
37     url += '&returntype=geographies&layers=all&benchmark=4&vintage=4&format=json'
38     url = requote_uri(url)
39     logger.debug('GET: %s', url)
40     try:
41         r = requests.get(url)
42     except Exception as e:
43         logger.exception(e)
44         return None
45
46     if r.status_code != 200:
47         logger.debug(r.text)
48         logger.error('Unexpected response code %d, wanted 200.  Fail.', r.status_code)
49         return None
50     logger.debug('Response: %s', json.dumps(r.json(), indent=4, sort_keys=True))
51     return r.json()
52
53
54 def batch_geocode_addresses(addresses: List[str]):
55     """Send up to addresses for batch geocoding.  Each line of the input
56     list should be a single address of the form: STREET ADDRESS, CITY,
57     STATE, ZIP.  Components may be omitted but the commas may not be.
58     Result is an array of the same size as the input array with one
59     answer record per line.  Returns None on error.
60
61     This code will deal with requests >10k addresses by chunking them
62     internally because the census website disallows requests > 10k lines.
63
64     >>> batch_geocode_addresses(
65     ...     [
66     ...         '4600 Silver Hill Rd, Washington, DC, 20233',
67     ...         '935 Pennsylvania Avenue, NW, Washington, DC, 20535-0001',
68     ...         '1600 Pennsylvania Avenue NW, Washington, DC, 20500',
69     ...         '700 Pennsylvania Avenue NW, Washington, DC, 20408',
70     ...     ]
71     ... )
72     ['"1"," 4600 Silver Hill Rd,  Washington,  DC,  20233","Match","Exact","4600 SILVER HILL RD, WASHINGTON, DC, 20233","-76.92743,38.84599","76355984","L","24","033","802405","2004"', '"2"," 935 Pennsylvania Avenue,  NW,  Washington,  DC","No_Match"', '"3"," 1600 Pennsylvania Avenue NW,  Washington,  DC,  20500","Match","Exact","1600 PENNSYLVANIA AVE NW, WASHINGTON, DC, 20500","-77.03534,38.898754","76225813","L","11","001","980000","1034"', '"4"," 700 Pennsylvania Avenue NW,  Washington,  DC,  20408","Match","Exact","700 PENNSYLVANIA AVE NW, WASHINGTON, DC, 20408","-77.02304,38.89362","76226346","L","11","001","980000","1025"']
73     """
74
75     n = 1
76     url = 'https://geocoding.geo.census.gov/geocoder/geographies/addressbatch'
77     payload = {'benchmark': '4', 'vintage': '4'}
78     out = []
79     for chunk in list_utils.shard(addresses, 9999):
80         raw_file = ''
81         for address in chunk:
82             raw_file += f'{n}, {address}\n'
83             n += 1
84         files = {'addressFile': ('input.csv', raw_file)}
85         logger.debug('POST: %s', url)
86         try:
87             r = requests.post(url, files=files, data=payload)
88         except Exception as e:
89             logger.exception(e)
90             return None
91
92         if r.status_code != 200:
93             logger.debug(r.text)
94             logger.error('Unexpected response code %d, wanted 200.  Fail.', r.status_code)
95             return None
96         logger.debug('Response: %s', r.text)
97         for line in r.text.split('\n'):
98             line = line.strip()
99             if len(line) > 0:
100                 out.append(line)
101     return out
102
103
104 if __name__ == '__main__':
105     import doctest
106
107     doctest.testmod()