sarlinpe commited on
Commit
d65ffc8
·
1 Parent(s): b5a5180

Better handle errors in OSM queries, require urllib3>=2

Browse files
maploc/osm/download.py CHANGED
@@ -2,41 +2,34 @@
2
 
3
  import json
4
  from pathlib import Path
5
- from typing import Dict, Optional
 
6
 
7
  import urllib3
8
 
9
  from .. import logger
10
  from ..utils.geo import BoundaryBox
11
 
 
 
12
 
13
  def get_osm(
14
  boundary_box: BoundaryBox,
15
  cache_path: Optional[Path] = None,
16
  overwrite: bool = False,
17
- ) -> str:
18
  if not overwrite and cache_path is not None and cache_path.is_file():
19
- with cache_path.open() as fp:
20
- return json.load(fp)
21
 
22
  (bottom, left), (top, right) = boundary_box.min_, boundary_box.max_
23
- content: bytes = get_web_data(
24
- "https://api.openstreetmap.org/api/0.6/map.json",
25
- {"bbox": f"{left},{bottom},{right},{top}"},
26
- )
27
 
28
- content_str = content.decode("utf-8")
29
- if content_str.startswith("You requested too many nodes"):
30
- raise ValueError(content_str)
 
 
31
 
32
  if cache_path is not None:
33
- with cache_path.open("bw+") as fp:
34
- fp.write(content)
35
- return json.loads(content_str)
36
-
37
-
38
- def get_web_data(address: str, parameters: Dict[str, str]) -> bytes:
39
- logger.info("Getting %s...", address)
40
- http = urllib3.PoolManager()
41
- result = http.request("GET", address, parameters, timeout=10)
42
- return result.data
 
2
 
3
  import json
4
  from pathlib import Path
5
+ from typing import Any, Dict, Optional
6
+ from http.client import responses
7
 
8
  import urllib3
9
 
10
  from .. import logger
11
  from ..utils.geo import BoundaryBox
12
 
13
+ OSM_URL = "https://api.openstreetmap.org/api/0.6/map.json"
14
+
15
 
16
  def get_osm(
17
  boundary_box: BoundaryBox,
18
  cache_path: Optional[Path] = None,
19
  overwrite: bool = False,
20
+ ) -> Dict[str, Any]:
21
  if not overwrite and cache_path is not None and cache_path.is_file():
22
+ return json.loads(cache_path.read_text())
 
23
 
24
  (bottom, left), (top, right) = boundary_box.min_, boundary_box.max_
25
+ query = {"bbox": f"{left},{bottom},{right},{top}"}
 
 
 
26
 
27
+ logger.info("Calling the OpenStreetMap API...")
28
+ result = urllib3.request("GET", OSM_URL, fields=query, timeout=10)
29
+ if result.status != 200:
30
+ error = result.info()['error']
31
+ raise ValueError(f"{result.status} {responses[result.status]}: {error}")
32
 
33
  if cache_path is not None:
34
+ cache_path.write_bytes(result.data)
35
+ return result.json()
 
 
 
 
 
 
 
 
requirements/demo.txt CHANGED
@@ -17,3 +17,4 @@ scikit-learn
17
  geopy
18
  exifread
19
  gradio_client
 
 
17
  geopy
18
  exifread
19
  gradio_client
20
+ urllib3>=2
requirements/full.txt CHANGED
@@ -18,3 +18,4 @@ git+https://github.com/mapillary/OpenSfM
18
  httpx
19
  aiolimiter
20
  scikit-learn
 
 
18
  httpx
19
  aiolimiter
20
  scikit-learn
21
+ urllib3>=2