-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathosm_async_download.py
164 lines (150 loc) · 4.74 KB
/
osm_async_download.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
"""
CLI tool to downloads OSM data asynchronously
"""
import os
import time
import json
import asyncio
import aiohttp
import numpy as np
import pandas as pd
from tqdm import tqdm
from argparse import ArgumentParser
from osm_tools import _bbox_from_point, DEFAULT_OVERPASS_URL, DEFAULT_QUERY_TEMPLATE
async def fetch(session, index, query, contact, retry_limit=5):
url = DEFAULT_OVERPASS_URL
headers = {"user-agent": "capstone-geodome/0.2", "from": contact}
async with session.get(url, params={"data": query}, headers=headers) as response:
retries = 0
data = np.nan
while retries < retry_limit:
try:
response_content = await response.read()
data = json.loads(response_content)
if response.status == 200:
break
except Exception:
retries += 1
# TODO: does the response status carry the same info?
if "The server is probably too busy to handle your request" in str(
response_content
):
await asyncio.sleep(2)
pass
pass
pass
return index, data
async def osm_async_download(bbox_list, template, contact):
async with aiohttp.ClientSession() as session:
tasks = [
fetch(session, index, template.format(bbox), contact)
for (index, bbox) in bbox_list
]
responses = [
await t
for t in tqdm(
asyncio.as_completed(tasks),
total=len(tasks),
desc="download",
leave=False,
)
]
return responses
def get_tags_col(df, distance, lat_col, lon_col, contact):
bbox_list = [
_bbox_from_point((lat, lon), dist=distance)
for (lat, lon) in zip(df[lat_col], df[lon_col])
]
bbox_list = [(i, bbox) for (i, bbox) in enumerate(bbox_list)]
indexed_response = asyncio.run(
osm_async_download(bbox_list, DEFAULT_QUERY_TEMPLATE, contact)
)
indexed_response.sort(key=lambda tup: tup[0])
assert len(indexed_response) == len(df)
return [r for (_, r) in indexed_response]
if __name__ == "__main__":
parser = ArgumentParser()
parser.add_argument("-i", "--input", help="path to csv input file", type=str)
parser.add_argument(
"-o",
"--outfile",
help="path to csv output file",
default="osm_out.csv",
type=str,
)
parser.add_argument(
"-ce",
"--contact_email",
help="contact email to include in the request header",
default="TBD",
type=str,
)
parser.add_argument(
"-d",
"--distance",
help="side length for area of interest",
default=550,
type=int,
)
parser.add_argument(
"-lat",
"--lat_col",
help="name of the column that contains the latitude",
default="lat",
type=str,
)
parser.add_argument(
"-lon",
"--lon_col",
help="name of the column that contains the longitude",
default="lon",
type=str,
)
parser.add_argument(
"-s",
"--splits",
help="number of splits to make to the input file",
default=10,
type=int,
)
parser.add_argument(
"-t",
"--pause_time",
help="number of seconds to wait between request batches",
default=60,
type=int,
)
args = parser.parse_args()
input_df = pd.read_csv(args.input)
df_parts = np.array_split(input_df, args.splits)
for i, part in enumerate(tqdm(df_parts, desc="splits")):
tmpfname = "{}_p{}.csv".format(args.outfile.split(".")[0], i)
if os.path.exists(tmpfname):
continue
part["tags"] = get_tags_col(
part, args.distance, args.lat_col, args.lon_col, args.contact_email
)
part.to_csv(tmpfname, index=False)
time.sleep(args.pause_time)
outfile = pd.concat(
[
pd.read_csv("{}_p{}.csv".format(args.outfile.split(".")[0], i))
for i in range(args.splits)
],
ignore_index=True,
)
# if some of the requests are missed, retry one more time with a new connection
if outfile["tags"].isna().sum() > 0:
print(
"second pass for requests that the surver was too busy to fulfill the first time"
)
na_index = outfile[outfile["tags"].isna()].index
outfile.loc[na_index, ["tags"]] = get_tags_col(
outfile[outfile["tags"].isna()],
args.distance,
args.lat_col,
args.lon_col,
args.contact_email,
)
pass
outfile.to_csv(args.outfile, index=False)