overturemaps 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Overture Maps
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,20 @@
1
+ Metadata-Version: 2.1
2
+ Name: overturemaps
3
+ Version: 0.1.0
4
+ Summary: Python tools for interacting with Overture Maps (overturemaps.org) data.
5
+ License: MIT
6
+ Author: Jacob Wasserman
7
+ Author-email: jwasserman@meta.com
8
+ Requires-Python: >=3.11,<4.0
9
+ Classifier: License :: OSI Approved :: MIT License
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Programming Language :: Python :: 3.11
12
+ Classifier: Programming Language :: Python :: 3.12
13
+ Requires-Dist: click (>=8.1.7,<9.0.0)
14
+ Requires-Dist: pyarrow (>=15.0.2,<16.0.0)
15
+ Requires-Dist: shapely (>=2.0.3,<3.0.0)
16
+ Description-Content-Type: text/markdown
17
+
18
+ # overture-py
19
+ overture-py
20
+
@@ -0,0 +1,2 @@
1
+ # overture-py
2
+ overture-py
@@ -0,0 +1,212 @@
1
+ """
2
+ Extract features from a Parquet dataset in a specified bounding box
3
+
4
+ With a parquet dataset that has the per-row bounding boxes, we can quickly
5
+ sub-select within a known region
6
+
7
+ """
8
+
9
+ import itertools
10
+ import json
11
+ import os
12
+ import sys
13
+ from typing import Optional
14
+
15
+ import click
16
+ import pyarrow as pa
17
+ import pyarrow.dataset as ds
18
+ import pyarrow.compute as pc
19
+ import pyarrow.fs as fs
20
+ import pyarrow.parquet as pq
21
+ import shapely.wkb
22
+
23
+
24
+ _theme_type_mapping = {
25
+ "locality": "admins",
26
+ "locality_area": "admins",
27
+ "administrative_boundary": "admins",
28
+ "building": "buildings",
29
+ "part": "buildings",
30
+ "place": "places",
31
+ "segment": "transportation",
32
+ "connector": "transportation",
33
+ "land": "base",
34
+ "land_use": "base",
35
+ "water": "base",
36
+ }
37
+
38
+
39
+ def _dataset_path(overture_type: str) -> str:
40
+ """
41
+ Returns the s3 path of the Overture dataset to use. This assumes overture_type has
42
+ been validated, e.g. by the CLI
43
+
44
+ """
45
+ theme = _theme_type_mapping[overture_type]
46
+ return f"overturemaps-us-west-2/release/2024-03-12-alpha.0/theme={theme}/type={overture_type}/"
47
+
48
+
49
+ def record_batch_reader(path, bbox=None) -> Optional[pa.RecordBatchReader]:
50
+ if bbox:
51
+ xmin, ymin, xmax, ymax = bbox
52
+ filter = (
53
+ (pc.field("bbox", "minx") < xmax)
54
+ & (pc.field("bbox", "maxx") > xmin)
55
+ & (pc.field("bbox", "miny") < ymax)
56
+ & (pc.field("bbox", "maxy") > ymin)
57
+ )
58
+ else:
59
+ filter = None
60
+
61
+ dataset = ds.dataset(
62
+ path, filesystem=fs.S3FileSystem(anonymous=True, region="us-west-2")
63
+ )
64
+ batches = dataset.to_batches(filter=filter)
65
+
66
+ reader = pa.RecordBatchReader.from_batches(dataset.schema, batches)
67
+ return reader
68
+
69
+
70
+ def get_writer(output_format, path, schema):
71
+ if output_format == "geojson":
72
+ writer = GeoJSONWriter(path)
73
+ elif output_format == "geojsonseq":
74
+ writer = GeoJSONSeqWriter(path)
75
+ elif output_format == "parquet":
76
+ writer = pq.ParquetWriter(path, schema)
77
+ return writer
78
+
79
+
80
+ class BboxParamType(click.ParamType):
81
+ name = "bbox"
82
+
83
+ def convert(self, value, param, ctx):
84
+ try:
85
+ bbox = [float(x.strip()) for x in value.split(",")]
86
+ fail = False
87
+ except ValueError: # ValueError raised when passing non-numbers to float()
88
+ fail = True
89
+
90
+ if fail or len(bbox) != 4:
91
+ self.fail(f"bbox must be 4 floating point numbers separated by commas. Got '{value}'")
92
+
93
+ return bbox
94
+
95
+
96
+ @click.group()
97
+ def cli():
98
+ pass
99
+
100
+
101
+ @cli.command()
102
+ @click.option("--bbox", required=False, type=BboxParamType())
103
+ @click.option("-f", "output_format", type=click.Choice(["geojson", "geojsonseq", "parquet"]), required=True)
104
+ @click.option("-o", "--output", required=False, type=click.Path())
105
+ @click.option(
106
+ "-t",
107
+ "--type",
108
+ "type_",
109
+ type=click.Choice(list(_theme_type_mapping.keys())),
110
+ required=True,
111
+ )
112
+ def download(bbox, output_format, output, type_):
113
+ if output is None:
114
+ output = sys.stdout
115
+
116
+ path = _dataset_path(type_)
117
+ reader = record_batch_reader(path, bbox)
118
+ if reader is None:
119
+ return
120
+
121
+ with get_writer(output_format, output, schema=reader.schema) as writer:
122
+ copy(reader, writer)
123
+
124
+
125
+ def copy(reader, writer, limit: int = None):
126
+ while True:
127
+ try:
128
+ batch = reader.read_next_batch()
129
+ except StopIteration:
130
+ break
131
+ writer.write_batch(batch)
132
+
133
+
134
+ class BaseGeoJSONWriter:
135
+ """
136
+ """
137
+ def __init__(self, where):
138
+ self.file_handle = None
139
+ if isinstance(where, str):
140
+ self.file_handle = open(os.path.expanduser(where), "w")
141
+ self.writer = self.file_handle
142
+ else:
143
+ self.writer = where
144
+ self.is_open = True
145
+
146
+ def __enter__(self):
147
+ return self
148
+
149
+ def __exit__(self, exc_type, value, traceback):
150
+ self.close()
151
+
152
+ def close(self):
153
+ if not self.is_open:
154
+ return
155
+ self.finalize()
156
+ if self.file_handle:
157
+ self.file_handle.close()
158
+ self.is_open = False
159
+
160
+ def write_batch(self, batch):
161
+ if batch.num_rows == 0:
162
+ return
163
+
164
+ for row in batch.to_pylist():
165
+ feature = self.row_to_feature(row)
166
+ self.write_feature(feature)
167
+
168
+ def write_feature(self, feature):
169
+ pass
170
+
171
+ def finalize(self):
172
+ pass
173
+
174
+ def row_to_feature(self, row):
175
+ geometry = shapely.wkb.loads(row.pop("geometry"))
176
+ row.pop("bbox")
177
+
178
+ # This only removes null values in the top-level dictionary but will leave in
179
+ # nulls in sub-properties
180
+ properties = {k: v for k, v in row.items() if k != "bbox" and v is not None}
181
+ return {
182
+ "type": "Feature",
183
+ "geometry": geometry.__geo_interface__,
184
+ "properties": properties,
185
+ }
186
+
187
+
188
+ class GeoJSONSeqWriter(BaseGeoJSONWriter):
189
+ def write_feature(self, feature):
190
+ self.writer.write(json.dumps(feature, separators=(",", ":")))
191
+ self.writer.write("\n")
192
+
193
+
194
+ class GeoJSONWriter(BaseGeoJSONWriter):
195
+ def __init__(self, *args, **kwargs):
196
+ super().__init__(*args, **kwargs)
197
+ self._has_written_feature = False
198
+
199
+ self.writer.write('{"type": "FeatureCollection", "features": [\n')
200
+
201
+ def write_feature(self, feature):
202
+ if self._has_written_feature:
203
+ self.writer.write(",\n")
204
+ self.writer.write(json.dumps(feature, separators=(",", ":")))
205
+ self._has_written_feature = True
206
+
207
+ def finalize(self):
208
+ self.writer.write("]}")
209
+
210
+
211
+ if __name__ == "__main__":
212
+ cli()
@@ -0,0 +1,21 @@
1
+ [tool.poetry]
2
+ name = "overturemaps"
3
+ version = "0.1.0"
4
+ description = "Python tools for interacting with Overture Maps (overturemaps.org) data."
5
+ authors = ["Jacob Wasserman <jwasserman@meta.com>"]
6
+ license = "MIT"
7
+ readme = "README.md"
8
+
9
+ [tool.poetry.dependencies]
10
+ python = "^3.11"
11
+ click = "^8.1.7"
12
+ pyarrow = "^15.0.2"
13
+ shapely = "^2.0.3"
14
+
15
+ [tool.poetry.scripts]
16
+ overturemaps = 'overturemaps.cli:cli'
17
+
18
+
19
+ [build-system]
20
+ requires = ["poetry-core"]
21
+ build-backend = "poetry.core.masonry.api"