geobox 1.4.2__py3-none-any.whl → 2.0.1__py3-none-any.whl

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.
Files changed (66) hide show
  1. geobox/__init__.py +2 -2
  2. geobox/aio/__init__.py +63 -0
  3. geobox/aio/api.py +2640 -0
  4. geobox/aio/apikey.py +263 -0
  5. geobox/aio/attachment.py +339 -0
  6. geobox/aio/base.py +262 -0
  7. geobox/aio/basemap.py +196 -0
  8. geobox/aio/dashboard.py +342 -0
  9. geobox/aio/feature.py +527 -0
  10. geobox/aio/field.py +321 -0
  11. geobox/aio/file.py +522 -0
  12. geobox/aio/layout.py +341 -0
  13. geobox/aio/log.py +145 -0
  14. geobox/aio/map.py +1034 -0
  15. geobox/aio/model3d.py +415 -0
  16. geobox/aio/mosaic.py +696 -0
  17. geobox/aio/plan.py +315 -0
  18. geobox/aio/query.py +693 -0
  19. geobox/aio/raster.py +869 -0
  20. geobox/aio/route.py +63 -0
  21. geobox/aio/scene.py +342 -0
  22. geobox/aio/settings.py +194 -0
  23. geobox/aio/task.py +402 -0
  24. geobox/aio/tile3d.py +339 -0
  25. geobox/aio/tileset.py +672 -0
  26. geobox/aio/usage.py +243 -0
  27. geobox/aio/user.py +507 -0
  28. geobox/aio/vectorlayer.py +1363 -0
  29. geobox/aio/version.py +273 -0
  30. geobox/aio/view.py +983 -0
  31. geobox/aio/workflow.py +341 -0
  32. geobox/api.py +14 -15
  33. geobox/apikey.py +28 -1
  34. geobox/attachment.py +27 -1
  35. geobox/base.py +4 -4
  36. geobox/basemap.py +30 -1
  37. geobox/dashboard.py +27 -0
  38. geobox/feature.py +33 -13
  39. geobox/field.py +33 -21
  40. geobox/file.py +40 -46
  41. geobox/layout.py +28 -1
  42. geobox/log.py +31 -7
  43. geobox/map.py +34 -2
  44. geobox/model3d.py +31 -37
  45. geobox/mosaic.py +28 -7
  46. geobox/plan.py +29 -3
  47. geobox/query.py +39 -14
  48. geobox/raster.py +26 -13
  49. geobox/scene.py +26 -0
  50. geobox/settings.py +30 -1
  51. geobox/task.py +28 -6
  52. geobox/tile3d.py +27 -1
  53. geobox/tileset.py +26 -5
  54. geobox/usage.py +32 -1
  55. geobox/user.py +62 -6
  56. geobox/utils.py +34 -0
  57. geobox/vectorlayer.py +40 -4
  58. geobox/version.py +25 -1
  59. geobox/view.py +37 -17
  60. geobox/workflow.py +27 -1
  61. {geobox-1.4.2.dist-info → geobox-2.0.1.dist-info}/METADATA +4 -1
  62. geobox-2.0.1.dist-info/RECORD +68 -0
  63. geobox-1.4.2.dist-info/RECORD +0 -38
  64. {geobox-1.4.2.dist-info → geobox-2.0.1.dist-info}/WHEEL +0 -0
  65. {geobox-1.4.2.dist-info → geobox-2.0.1.dist-info}/licenses/LICENSE +0 -0
  66. {geobox-1.4.2.dist-info → geobox-2.0.1.dist-info}/top_level.txt +0 -0
geobox/aio/raster.py ADDED
@@ -0,0 +1,869 @@
1
+ import os
2
+ from urllib.parse import urljoin, urlencode
3
+ from typing import Optional, Dict, List, Optional, Union, TYPE_CHECKING
4
+ import mimetypes
5
+ import requests
6
+ import sys
7
+
8
+ from .base import AsyncBase
9
+ from .task import Task
10
+ from ..utils import clean_data, join_url_params
11
+
12
+
13
+ if TYPE_CHECKING:
14
+ from . import AsyncGeoboxClient
15
+ from .user import User
16
+ from ..api import GeoboxClient as SyncGeoboxClient
17
+ from ..raster import Raster as SyncRaster
18
+
19
+
20
+ class Raster(AsyncBase):
21
+
22
+ BASE_ENDPOINT: str = 'rasters/'
23
+
24
+ def __init__(self,
25
+ api: 'AsyncGeoboxClient',
26
+ uuid: str,
27
+ data: Optional[Dict] = {}):
28
+ """
29
+ Constructs all the necessary attributes for the Raster object.
30
+
31
+ Args:
32
+ api (AsyncGeoboxClient): The API instance.
33
+ uuid (str): The UUID of the raster.
34
+ data (Dict, optional): The raster data.
35
+ """
36
+ super().__init__(api, uuid=uuid, data=data)
37
+
38
+
39
+ @classmethod
40
+ async def get_rasters(cls, api: 'AsyncGeoboxClient', **kwargs) -> Union[List['Raster'], int]:
41
+ """
42
+ [async] Get all rasters.
43
+
44
+ Args:
45
+ api (AsyncGeoboxClient): The API instance.
46
+
47
+ Keyword Args:
48
+ terrain (bool): whether to get terrain rasters.
49
+ q (str): query filter based on OGC CQL standard. e.g. "field1 LIKE '%GIS%' AND created_at > '2021-01-01'"
50
+ search (str): search term for keyword-based searching among search_fields or all textual fields if search_fields does not have value. NOTE: if q param is defined this param will be ignored.
51
+ search_fields (str): comma separated list of fields for searching
52
+ order_by (str): comma separated list of fields for sorting results [field1 A|D, field2 A|D, …]. e.g. name A, type D. NOTE: "A" denotes ascending order and "D" denotes descending order.
53
+ return_count (bool): whether to return the total count of rasters. default is False.
54
+ skip (int): number of rasters to skip. minimum is 0.
55
+ limit (int): number of rasters to return. minimum is 1.
56
+ user_id (int): user id to show the rasters of the user. privileges required.
57
+ shared (bool): whether to return shared rasters. default is False.
58
+
59
+ Returns:
60
+ List[Raster] | int: A list of Raster objects or the total count of rasters.
61
+
62
+ Example:
63
+ >>> from geobox.aio import AsyncGeoboxClient
64
+ >>> from geobox.aio.raster import Raster
65
+ >>> async with AsyncGeoboxClient() as client:
66
+ >>> rasters = await Raster.get_rasters(client, terrain=True, q="name LIKE '%GIS%'")
67
+ or
68
+ >>> rasters = await client.get_rasters(terrain=True, q="name LIKE '%GIS%'")
69
+ """
70
+ params = {
71
+ 'terrain': kwargs.get('terrain', None),
72
+ 'f': 'json',
73
+ 'q': kwargs.get('q', None),
74
+ 'search': kwargs.get('search', None),
75
+ 'search_fields': kwargs.get('search_fields', None),
76
+ 'order_by': kwargs.get('order_by', None),
77
+ 'return_count': kwargs.get('return_count', False),
78
+ 'skip': kwargs.get('skip', 0),
79
+ 'limit': kwargs.get('limit', 100),
80
+ 'user_id': kwargs.get('user_id', None),
81
+ 'shared': kwargs.get('shared', False)
82
+ }
83
+ return await super()._get_list(api, cls.BASE_ENDPOINT, params, factory_func=lambda api, item: Raster(api, item['uuid'], item))
84
+
85
+
86
+
87
+ @classmethod
88
+ async def get_rasters_by_ids(cls, api: 'AsyncGeoboxClient', ids: List[str], user_id: int = None) -> List['Raster']:
89
+ """
90
+ [async] Get rasters by their IDs.
91
+
92
+ Args:
93
+ api (AsyncGeoboxClient): The API instance.
94
+ ids (List[str]): The IDs of the rasters.
95
+ user_id (int, optional): specific user. privileges required.
96
+
97
+ Returns:
98
+ List['Raster']: A list of Raster objects.
99
+
100
+ Example:
101
+ >>> from geobox.aio import AsyncGeoboxClient
102
+ >>> from geobox.aio.raster import Raster
103
+ >>> async with AsyncGeoboxClient() as client:
104
+ >>> rasters = await Raster.get_rasters_by_ids(client, ids=['123', '456'])
105
+ or
106
+ >>> rasters = await client.get_rasters_by_ids(ids=['123', '456'])
107
+ """
108
+ params = {
109
+ 'ids': ids,
110
+ 'user_id': user_id,
111
+ }
112
+ endpoint = urljoin(cls.BASE_ENDPOINT, 'get-rasters/')
113
+
114
+ return await super()._get_list_by_ids(api, endpoint, params, factory_func=lambda api, item: Raster(api, item['uuid'], item))
115
+
116
+
117
+ @classmethod
118
+ async def get_raster(cls, api: 'AsyncGeoboxClient', uuid: str, user_id: int = None) -> 'Raster':
119
+ """
120
+ [async] Get a raster by its UUID.
121
+
122
+ Args:
123
+ api (AsyncGeoboxClient): The API instance.
124
+ uuid (str): The UUID of the raster.
125
+ user_id (int, optional): specific user. privileges required.
126
+
127
+ Returns:
128
+ Raster: A Raster object.
129
+
130
+ Example:
131
+ >>> from geobox.aio import AsyncGeoboxClient
132
+ >>> from geobox.aio.raster import Raster
133
+ >>> async with AsyncGeoboxClient() as client:
134
+ >>> raster = await Raster.get_raster(client, uuid="12345678-1234-5678-1234-567812345678")
135
+ or
136
+ >>> raster = await client.get_raster(uuid="12345678-1234-5678-1234-567812345678")
137
+ """
138
+ params = {
139
+ 'f': 'json',
140
+ 'user_id': user_id
141
+ }
142
+ return await super()._get_detail(api, cls.BASE_ENDPOINT, uuid, params, factory_func=lambda api, item: Raster(api, item['uuid'], item))
143
+
144
+
145
+ @classmethod
146
+ async def get_raster_by_name(cls, api: 'AsyncGeoboxClient', name: str, user_id: int = None) -> Union['Raster', None]:
147
+ """
148
+ [async] Get a raster by name
149
+
150
+ Args:
151
+ api (AsyncGeoboxClient): The AsyncGeoboxClient instance for making requests.
152
+ name (str): the name of the raster to get
153
+ user_id (int, optional): specific user. privileges required.
154
+
155
+ Returns:
156
+ Raster | None: returns the raster if a raster matches the given name, else None
157
+
158
+ Example:
159
+ >>> from geobox.aio import AsyncGeoboxClient
160
+ >>> from geobox.aio.raster import Raster
161
+ >>> async with AsyncGeoboxClient() as client:
162
+ >>> raster = await Raster.get_raster_by_name(client, name='test')
163
+ or
164
+ >>> raster = await client.get_raster_by_name(name='test')
165
+ """
166
+ rasters = await cls.get_rasters(api, q=f"name = '{name}'", user_id=user_id)
167
+ if rasters and rasters[0].name == name:
168
+ return rasters[0]
169
+ else:
170
+ return None
171
+
172
+
173
+ async def update(self, **kwargs) -> None:
174
+ """
175
+ [async] Update the raster.
176
+
177
+ Keyword Args:
178
+ name (str): The name of the raster.
179
+ display_name (str): The display name of the raster.
180
+ description (str): The description of the raster.
181
+
182
+ Returns:
183
+ None
184
+
185
+ Example:
186
+ >>> from geobox.aio import AsyncGeoboxClient
187
+ >>> from geobox.aio.raster import Raster
188
+ >>> async with AsyncGeoboxClient() as client:
189
+ >>> raster = await Raster.get_raster(client, uuid="12345678-1234-5678-1234-567812345678")
190
+ >>> await raster.update(name="new_name")
191
+ """
192
+ params = {
193
+ 'name': kwargs.get('name'),
194
+ 'display_name': kwargs.get('display_name'),
195
+ 'description': kwargs.get('description')
196
+ }
197
+ return await super()._update(self.endpoint, params)
198
+
199
+
200
+ async def delete(self) -> None:
201
+ """
202
+ [async] Delete the raster.
203
+
204
+ Returns:
205
+ None
206
+
207
+ Example:
208
+ >>> from geobox.aio import AsyncGeoboxClient
209
+ >>> from geobox.aio.raster import Raster
210
+ >>> async with AsyncGeoboxClient() as client:
211
+ >>> raster = await Raster.get_raster(client, uuid="12345678-1234-5678-1234-567812345678")
212
+ >>> await raster.delete()
213
+ """
214
+ await super().delete(self.endpoint)
215
+
216
+
217
+ @property
218
+ def thumbnail(self) -> str:
219
+ """
220
+ Get the thumbnail of the raster.
221
+
222
+ Returns:
223
+ str: The url of the thumbnail.
224
+
225
+ Example:
226
+ >>> from geobox.aio import AsyncGeoboxClient
227
+ >>> from geobox.aio.raster import Raster
228
+ >>> async with AsyncGeoboxClient() as client:
229
+ >>> raster = await Raster.get_raster(client, uuid="12345678-1234-5678-1234-567812345678")
230
+ >>> raster.thumbnail
231
+ """
232
+ return super().thumbnail(format='')
233
+
234
+
235
+ @property
236
+ async def info(self) -> Dict:
237
+ """
238
+ [async] Get the info of the raster.
239
+
240
+ Returns:
241
+ Dict: The info of the raster.
242
+
243
+ Example:
244
+ >>> from geobox.aio import AsyncGeoboxClient
245
+ >>> from geobox.aio.raster import Raster
246
+ >>> async with AsyncGeoboxClient() as client:
247
+ >>> raster = await Raster.get_raster(client, uuid="12345678-1234-5678-1234-567812345678")
248
+ >>> await raster.info
249
+ """
250
+ endpoint = urljoin(self.endpoint, 'info/')
251
+ return await self.api.get(endpoint)
252
+
253
+
254
+ async def get_statistics(self, indexes: str = None) -> Dict:
255
+ """
256
+ [async] Get the statistics of the raster.
257
+
258
+ Args:
259
+ indexes (str): list of comma separated band indexes. e.g. 1, 2, 3
260
+
261
+ Returns:
262
+ Dict: The statistics of the raster.
263
+
264
+ Example:
265
+ >>> from geobox.aio import AsyncGeoboxClient
266
+ >>> from geobox.aio.raster import Raster
267
+ >>> async with AsyncGeoboxClient() as client:
268
+ >>> raster = await Raster.get_raster(client, uuid="12345678-1234-5678-1234-567812345678")
269
+ >>> await raster.get_statistics(indexes='1, 2, 3')
270
+ """
271
+ params = clean_data({
272
+ 'indexes': indexes,
273
+ })
274
+ query_string = urlencode(params)
275
+ endpoint = urljoin(self.endpoint, f'statistics/?{query_string}')
276
+ return await self.api.get(endpoint)
277
+
278
+
279
+ async def get_point(self, lat: float, lng: float) -> Dict:
280
+ """
281
+ [async] Get the point of the raster.
282
+
283
+ Args:
284
+ lat (float): The latitude of the point. minimum is -90, maximum is 90.
285
+ lng (float): The longitude of the point. minimum is -180, maximum is 180.
286
+
287
+ Returns:
288
+ Dict: The point of the raster.
289
+
290
+ Example:
291
+ >>> from geobox.aio import AsyncGeoboxClient
292
+ >>> from geobox.aio.raster import Raster
293
+ >>> async with AsyncGeoboxClient() as client:
294
+ >>> raster = await Raster.get_raster(client, uuid="12345678-1234-5678-1234-567812345678")
295
+ >>> await raster.get_point(lat=60, lng=50)
296
+ """
297
+ if lat < -90 or lat > 90:
298
+ raise ValueError("lat must be between -90 and 90")
299
+ if lng < -180 or lng > 180:
300
+ raise ValueError("lng must be between -180 and 180")
301
+
302
+ params = clean_data({
303
+ 'lat': lat,
304
+ 'lng': lng,
305
+ })
306
+ query_string = urlencode(params)
307
+ endpoint = urljoin(self.endpoint, f'point?{query_string}')
308
+ return await self.api.get(endpoint)
309
+
310
+
311
+ def _get_save_path(self, save_path: str = None) -> str:
312
+ """
313
+ Get the path where the file should be saved.
314
+
315
+ Args:
316
+ save_path (str, optional): The path to save the file.
317
+
318
+ Returns:
319
+ str: The path where the file is saved.
320
+
321
+ Raises:
322
+ ValueError: If save_path does not end with a '/'.
323
+ """
324
+ # If save_path is provided, check if it ends with a '/'
325
+ if save_path and save_path.endswith('/'):
326
+ return f'{save_path}'
327
+
328
+ if save_path and not save_path.endswith('/'):
329
+ raise ValueError("save_path must end with a '/'")
330
+
331
+ return os.getcwd()
332
+
333
+
334
+ def _get_file_name(self, response: requests.Response) -> str:
335
+ """
336
+ Get the file name from the response.
337
+
338
+ Args:
339
+ response (requests.Response): The response of the request.
340
+
341
+ Returns:
342
+ str: The file name
343
+ """
344
+ if 'Content-Disposition' in response.headers and 'filename=' in response.headers['Content-Disposition']:
345
+ file_name = response.headers['Content-Disposition'].split('filename=')[-1].strip().strip('"')
346
+
347
+ else:
348
+ content_type = response.headers.get("Content-Type", "")
349
+ file_name = f'{self.name}{mimetypes.guess_extension(content_type.split(";")[0])}'
350
+
351
+ return file_name
352
+
353
+
354
+ def _create_progress_bar(self) -> 'tqdm':
355
+ """Creates a progress bar for the task."""
356
+ try:
357
+ from tqdm.auto import tqdm
358
+ except ImportError:
359
+ from .api import logger
360
+ logger.warning("[tqdm] extra is required to show the progress bar. install with: pip insatll geobox[tqdm]")
361
+ return None
362
+
363
+ return tqdm(unit="B",
364
+ total=int(self.size),
365
+ file=sys.stdout,
366
+ dynamic_ncols=True,
367
+ desc="Downloading",
368
+ unit_scale=True,
369
+ unit_divisor=1024,
370
+ ascii=True
371
+ )
372
+
373
+
374
+ async def download(self, save_path: str = None, progress_bar: bool = True) -> str:
375
+ """
376
+ [async] Download the raster.
377
+
378
+ Args:
379
+ save_path (str, optional): Path where the file should be saved.
380
+ If not provided, it saves to the current working directory
381
+ using the original filename and appropriate extension.
382
+ progress_bar (bool, optional): Whether to show a progress bar. default: True
383
+
384
+ Returns:
385
+ str: The path to save the raster.
386
+
387
+ Raises:
388
+ ValueError: If file_uuid is not set
389
+ OSError: If there are issues with file operations
390
+
391
+ Example:
392
+ >>> from geobox.aio import AsyncGeoboxClient
393
+ >>> from geobox.aio.raster import Raster
394
+ >>> async with AsyncGeoboxClient() as client:
395
+ >>> raster = await Raster.get_raster(client, uuid="12345678-1234-5678-1234-567812345678")
396
+ >>> await raster.download(save_path="path/to/save/")
397
+ """
398
+ if not self.uuid:
399
+ raise ValueError("Raster UUID is required to download the raster file")
400
+
401
+ save_path = self._get_save_path(save_path)
402
+ os.makedirs(os.path.dirname(save_path), exist_ok=True)
403
+
404
+ endpoint = urljoin(self.api.base_url, f"{self.endpoint}download/")
405
+
406
+ async with self.api.session.session.get(endpoint) as response:
407
+ file_name = self._get_file_name(response)
408
+ full_path = f"{save_path}/{file_name}"
409
+ with open(full_path, 'wb') as f:
410
+ pbar = self._create_progress_bar() if progress_bar else None
411
+ async for chunk in response.content.iter_chunked(8192):
412
+ f.write(chunk)
413
+ if pbar:
414
+ pbar.update(len(chunk))
415
+ pbar.refresh()
416
+ if pbar:
417
+ pbar.close()
418
+
419
+ return os.path.abspath(full_path)
420
+
421
+
422
+ async def get_content_file(self, save_path: str = None, progress_bar: bool = True) -> str:
423
+ """
424
+ [async] Get Raster Content URL
425
+
426
+ Args:
427
+ save_path (str, optional): Path where the file should be saved.
428
+ If not provided, it saves to the current working directory
429
+ using the original filename and appropriate extension.
430
+ progress_bar (bool, optional): Whether to show a progress bar. default: True
431
+
432
+ Returns:
433
+ str: The path to save the raster.
434
+
435
+ Raises:
436
+ ValueError: If uuid is not set
437
+ OSError: If there are issues with file operations
438
+
439
+ Examples:
440
+ >>> from geobox.aio import AsyncGeoboxClient
441
+ >>> from geobox.aio.raster import Raster
442
+ >>> async with AsyncGeoboxClient() as client:
443
+ >>> raster = await Raster.get_raster(client, uuid="12345678-1234-5678-1234-567812345678")
444
+ >>> raster_tiff = await raste.get_content_file()
445
+ """
446
+ if not self.uuid:
447
+ raise ValueError("Raster UUID is required to download the raster content")
448
+
449
+ save_path = self._get_save_path(save_path)
450
+ os.makedirs(os.path.dirname(save_path), exist_ok=True)
451
+
452
+ endpoint = urljoin(self.api.base_url, f"{self.endpoint}content/")
453
+
454
+ async with self.api.session.session.get(endpoint) as response:
455
+ file_name = self._get_file_name(response)
456
+ full_path = f"{save_path}/{file_name}"
457
+ with open(full_path, 'wb') as f:
458
+ pbar = self._create_progress_bar() if progress_bar else None
459
+ async for chunk in response.content.iter_chunked(8192):
460
+ f.write(chunk)
461
+ if pbar:
462
+ pbar.update(len(chunk))
463
+ pbar.refresh()
464
+ if pbar:
465
+ pbar.close()
466
+
467
+ return os.path.abspath(full_path)
468
+
469
+
470
+ def get_render_png_url(self, x: int, y: int, z: int, **kwargs) -> str:
471
+ """
472
+ Get the PNG URL of the raster.
473
+
474
+ Args:
475
+ x (int): The x coordinate of the tile.
476
+ y (int): The y coordinate of the tile.
477
+ z (int): The zoom level of the tile.
478
+
479
+ Keyword Args:
480
+ indexes (str, optional): list of comma separated band indexes to be rendered. e.g. 1, 2, 3
481
+ nodata (int, optional)
482
+ expression (str, optional): band math expression. e.g. b1*b2+b3
483
+ rescale (List, optional): comma (',') separated Min,Max range. Can set multiple time for multiple bands.
484
+ color_formula (str, optional): Color formula. e.g. gamma R 0.5
485
+ colormap_name (str, optional)
486
+ colormap (str, optional): JSON encoded custom Colormap. e.g. {"0": "#ff0000", "1": "#00ff00"} or [[[0, 100], "#ff0000"], [[100, 200], "#00ff00"]]
487
+
488
+ Returns:
489
+ str: The PNG Render URL of the raster.
490
+
491
+ Example:
492
+ >>> from geobox.aio import AsyncGeoboxClient
493
+ >>> from geobox.aio.raster import Raster
494
+ >>> async with AsyncGeoboxClient() as client:
495
+ >>> raster = await Raster.get_raster(client, uuid="12345678-1234-5678-1234-567812345678")
496
+ >>> raster.get_tile_render_url(x=10, y=20, z=1)
497
+ """
498
+ params = clean_data({
499
+ 'indexes': kwargs.get('indexes'),
500
+ 'nodata': kwargs.get('nodata'),
501
+ 'expression': kwargs.get('expression'),
502
+ 'rescale': kwargs.get('rescale'),
503
+ 'color_formula': kwargs.get('color_formula'),
504
+ 'colormap_name': kwargs.get('colormap_name'),
505
+ 'colormap': kwargs.get('colormap')
506
+ })
507
+ query_string = urlencode(params)
508
+ endpoint = f'{self.api.base_url}{self.endpoint}render/{z}/{x}/{y}.png'
509
+ if query_string:
510
+ endpoint = f'{endpoint}?{query_string}'
511
+
512
+ if not self.api.access_token and self.api.apikey:
513
+ endpoint = join_url_params(endpoint, {"apikey": self.api.apikey})
514
+
515
+ return endpoint
516
+
517
+
518
+ def get_tile_pbf_url(self, x: int = '{x}', y: int = '{y}', z: int = '{z}', indexes: str = None) -> str:
519
+ """
520
+ Get the URL of the tile.
521
+
522
+ Args:
523
+ x (int, optional): The x coordinate of the tile.
524
+ y (int, optional): The y coordinate of the tile.
525
+ z (int, optional): The zoom level of the tile.
526
+ indexes (str, optional): list of comma separated band indexes to be rendered. e.g. 1, 2, 3
527
+
528
+ Returns:
529
+ str: The URL of the tile.
530
+
531
+ Example:
532
+ >>> from geobox.aio import AsyncGeoboxClient
533
+ >>> from geobox.aio.raster import Raster
534
+ >>> async with AsyncGeoboxClient() as client:
535
+ >>> raster = await Raster.get_raster(client, uuid="12345678-1234-5678-1234-567812345678")
536
+ >>> raster.get_tile_pbf_url(x=10, y=20, z=1)
537
+ """
538
+ params = clean_data({
539
+ 'indexes': indexes
540
+ })
541
+ query_string = urlencode(params)
542
+ endpoint = urljoin(self.api.base_url, f'{self.endpoint}tiles/{z}/{x}/{y}.pbf')
543
+ endpoint = urljoin(endpoint, f'?{query_string}')
544
+
545
+ if not self.api.access_token and self.api.apikey:
546
+ endpoint = join_url_params(endpoint, {"apikey": self.api.apikey})
547
+
548
+ return endpoint
549
+
550
+
551
+ def get_tile_png_url(self, x: int = 'x', y: int = 'y', z: int = 'z') -> str:
552
+ """
553
+ Get the URL of the tile.
554
+
555
+ Args:
556
+ x (int, optional): The x coordinate of the tile.
557
+ y (int, optional): The y coordinate of the tile.
558
+ z (int, optional): The zoom level of the tile.
559
+
560
+ Returns:
561
+ str: The URL of the tile.
562
+
563
+ Example:
564
+ >>> from geobox.aio import AsyncGeoboxClient
565
+ >>> from geobox.aio.raster import Raster
566
+ >>> async with AsyncGeoboxClient() as client:
567
+ >>> raster = await Raster.get_raster(client, uuid="12345678-1234-5678-1234-567812345678")
568
+ >>> raster.get_tile_png_url(x=10, y=20, z=1)
569
+ """
570
+ endpoint = f'{self.api.base_url}{self.endpoint}tiles/{z}/{x}/{y}.png'
571
+
572
+ if not self.api.access_token and self.api.apikey:
573
+ endpoint = f'{endpoint}?apikey={self.api.apikey}'
574
+
575
+ return endpoint
576
+
577
+
578
+ async def get_tile_json(self) -> Dict:
579
+ """
580
+ [async] Get the tile JSON of the raster.
581
+
582
+ Returns:
583
+ Dict: The tile JSON of the raster.
584
+
585
+ Example:
586
+ >>> from geobox.aio import AsyncGeoboxClient
587
+ >>> from geobox.aio.raster import Raster
588
+ >>> async with AsyncGeoboxClient() as client:
589
+ >>> raster = await Raster.get_raster(client, uuid="12345678-1234-5678-1234-567812345678")
590
+ >>> await raster.get_tile_json()
591
+ """
592
+ endpoint = urljoin(self.endpoint, 'tilejson.json')
593
+ return await self.api.get(endpoint)
594
+
595
+
596
+ def wmts(self, scale: int = None) -> str:
597
+ """
598
+ Get the WMTS URL
599
+
600
+ Args:
601
+ scale (int, optional): The scale of the raster. values are: 1, 2
602
+
603
+ Returns:
604
+ str: the raster WMTS URL
605
+
606
+ Example:
607
+ >>> from geobox.aio import AsyncGeoboxClient
608
+ >>> from geobox.aio.raster import Raster
609
+ >>> async with AsyncGeoboxClient() as client:
610
+ >>> raster = await Raster.get_raster(client, uuid="12345678-1234-5678-1234-567812345678")
611
+ >>> raster.wmts(scale=1)
612
+ """
613
+ endpoint = urljoin(self.api.base_url, f'{self.endpoint}wmts/')
614
+ if scale:
615
+ endpoint = f"{endpoint}?scale={scale}"
616
+
617
+ if not self.api.access_token and self.api.apikey:
618
+ endpoint = join_url_params(endpoint, {"apikey": self.api.apikey})
619
+
620
+ return endpoint
621
+
622
+
623
+ @property
624
+ async def settings(self) -> Dict:
625
+ """
626
+ [async] Get the settings of the raster.
627
+
628
+ Returns:
629
+ Dict: The settings of the raster.
630
+
631
+ Example:
632
+ >>> from geobox.aio import AsyncGeoboxClient
633
+ >>> from geobox.aio.raster import Raster
634
+ >>> async with AsyncGeoboxClient() as client:
635
+ >>> raster = await Raster.get_raster(client, uuid="12345678-1234-5678-1234-567812345678")
636
+ >>> await raster.settings
637
+ """
638
+ return await super()._get_settings(self.endpoint)
639
+
640
+
641
+ async def update_settings(self, settings: Dict) -> Dict:
642
+ """
643
+ [async] Update the settings
644
+
645
+ settings (Dict): settings dictionary
646
+
647
+ Returns:
648
+ Dict: updated settings
649
+
650
+ Example:
651
+ >>> from geobox.aio import AsyncGeoboxClient
652
+ >>> async with AsyncGeoboxClient() as client:
653
+ >>> raster1 = client.get_raster(uuid="12345678-1234-5678-1234-567812345678")
654
+ >>> raster2 = client.get_raster(uuid="12345678-1234-5678-1234-567812345678")
655
+ >>> raster1.update_settings(raster2.settings)
656
+ """
657
+ return await super()._set_settings(self.endpoint, settings)
658
+
659
+
660
+ async def set_settings(self, **kwargs) -> None:
661
+ """
662
+ [async] Set the settings of the raster.
663
+
664
+ Keyword Args:
665
+ nodata (int): The nodata value of the raster.
666
+ indexes (list[int]): The indexes of the raster.
667
+ rescale (list[int]): The rescale of the raster.
668
+ colormap_name (str): The colormap name of the raster.
669
+ color_formula (str): The color formula of the raster.
670
+ expression (str): The expression of the raster.
671
+ exaggeraion (int): The exaggeraion of the raster.
672
+ min_zoom (int): The min zoom of the raster.
673
+ max_zoom (int): The max zoom of the raster.
674
+ use_cache (bool): Whether to use cache of the raster.
675
+ cache_until_zoom (int): The cache until zoom of the raster.
676
+
677
+
678
+ Example:
679
+ >>> from geobox.aio import AsyncGeoboxClient
680
+ >>> from geobox.aio.raster import Raster
681
+ >>> async with AsyncGeoboxClient() as client:
682
+ >>> raster = await Raster.get_raster(client, uuid="12345678-1234-5678-1234-567812345678")
683
+ >>> await raster.set_settings(nodata=0,
684
+ ... indexes=[1],
685
+ ... rescale=[[0, 10000]],
686
+ ... colormap_name='gist_rainbow',
687
+ ... color_formula='Gamma R 0.5',
688
+ ... expression='b1 * 2',
689
+ ... exaggeraion=10,
690
+ ... min_zoom=0,
691
+ ... max_zoom=22,
692
+ ... use_cache=True,
693
+ ... cache_until_zoom=17)
694
+ """
695
+ visual_settings = {
696
+ 'nodata', 'indexes', 'rescale', 'colormap_name',
697
+ 'color_formula', 'expression', 'exaggeraion'
698
+ }
699
+ tile_settings = {
700
+ 'min_zoom', 'max_zoom', 'use_cache', 'cache_until_zoom'
701
+ }
702
+
703
+ settings = await self.settings
704
+
705
+ for key, value in kwargs.items():
706
+ if key in visual_settings:
707
+ settings['visual_settings'][key] = value
708
+ elif key in tile_settings:
709
+ settings['tile_settings'][key] = value
710
+
711
+
712
+ return await super()._set_settings(self.endpoint, settings)
713
+
714
+
715
+ async def share(self, users: List['User']) -> None:
716
+ """
717
+ [async] Shares the raster with specified users.
718
+
719
+ Args:
720
+ users (List[User]): The list of user objects to share the raster with.
721
+
722
+ Returns:
723
+ None
724
+
725
+ Example:
726
+ >>> from geobox.aio import AsyncGeoboxClient
727
+ >>> from geobox.aio.raster import Raster
728
+ >>> async with AsyncGeoboxClient() as client:
729
+ >>> raster = await Raster.get_raster(client, uuid="12345678-1234-5678-1234-567812345678")
730
+ >>> users = await client.search_users(search="John")
731
+ >>> await raster.share(users=users)
732
+ """
733
+ await super()._share(self.endpoint, users)
734
+
735
+
736
+ async def unshare(self, users: List['User']) -> None:
737
+ """
738
+ [async] Unshares the raster with specified users.
739
+
740
+ Args:
741
+ users (List[User]): The list of user objects to unshare the raster with.
742
+
743
+ Returns:
744
+ None
745
+
746
+ Example:
747
+ >>> from geobox.aio import AsyncGeoboxClient
748
+ >>> from geobox.aio.raster import Raster
749
+ >>> async with AsyncGeoboxClient() as client:
750
+ >>> raster = await Raster.get_raster(client, uuid="12345678-1234-5678-1234-567812345678")
751
+ >>> users = await client.search_users(search="John")
752
+ >>> await raster.unshare(users=users)
753
+ """
754
+ await super()._unshare(self.endpoint, users)
755
+
756
+
757
+ async def get_shared_users(self, search: str = None, skip: int = 0, limit: int = 10) -> List['User']:
758
+ """
759
+ [async] Retrieves the list of users the raster is shared with.
760
+
761
+ Args:
762
+ search (str, optional): The search query.
763
+ skip (int, optional): The number of users to skip.
764
+ limit (int, optional): The maximum number of users to retrieve.
765
+
766
+ Returns:
767
+ List[User]: The list of shared users.
768
+
769
+ Example:
770
+ >>> from geobox.aio import AsyncGeoboxClient
771
+ >>> from geobox.aio.raster import Raster
772
+ >>> async with AsyncGeoboxClient() as client:
773
+ >>> raster = await Raster.get_raster(client, uuid="12345678-1234-5678-1234-567812345678")
774
+ >>> await raster.get_shared_users(search='John', skip=0, limit=10)
775
+ """
776
+ params = {
777
+ 'search': search,
778
+ 'skip': skip,
779
+ 'limit': limit
780
+ }
781
+ return await super()._get_shared_users(self.endpoint, params)
782
+
783
+
784
+ async def seed_cache(self, from_zoom: int = None, to_zoom: int = None, extent: List[int] = None, workers: int = 1) -> List['Task']:
785
+ """
786
+ [async] Seed the cache of the raster.
787
+
788
+ Args:
789
+ from_zoom (int, optional): The from zoom of the raster.
790
+ to_zoom (int, optional): The to zoom of the raster.
791
+ extent (List[int], optional): The extent of the raster.
792
+ workers (int, optional): The number of workers to use. default is 1.
793
+
794
+ Returns:
795
+ Task: The task of the seed cache.
796
+
797
+ Example:
798
+ >>> from geobox.aio import AsyncGeoboxClient
799
+ >>> from geobox.aio.raster import Raster
800
+ >>> async with AsyncGeoboxClient() as client:
801
+ >>> raster = await Raster.get_raster(client, uuid="12345678-1234-5678-1234-567812345678")
802
+ >>> task = await raster.seed_cache(from_zoom=0, to_zoom=22, extent=[0, 0, 100, 100], workers=1)
803
+ """
804
+ data = {
805
+ 'from_zoom': from_zoom,
806
+ 'to_zoom': to_zoom,
807
+ 'extent': extent,
808
+ 'workers': workers
809
+ }
810
+ return await super()._seed_cache(self.endpoint, data)
811
+
812
+
813
+ async def clear_cache(self) -> None:
814
+ """
815
+ [async] Clear the cache of the raster.
816
+
817
+ Returns:
818
+ None
819
+
820
+ Example:
821
+ >>> from geobox.aio import AsyncGeoboxClient
822
+ >>> from geobox.aio.raster import Raster
823
+ >>> async with AsyncGeoboxClient() as client:
824
+ >>> raster = await Raster.get_raster(client, uuid="12345678-1234-5678-1234-567812345678")
825
+ >>> await raster.clear_cache()
826
+ """
827
+ await super()._clear_cache(self.endpoint)
828
+
829
+
830
+ @property
831
+ async def cache_size(self) -> int:
832
+ """
833
+ [async] Get the size of the cache of the raster.
834
+
835
+ Returns:
836
+ int: The size of the cache of the raster.
837
+
838
+ Example:
839
+ >>> from geobox.aio import AsyncGeoboxClient
840
+ >>> from geobox.aio.raster import Raster
841
+ >>> async with AsyncGeoboxClient() as client:
842
+ >>> raster = await Raster.get_raster(client, uuid="12345678-1234-5678-1234-567812345678")
843
+ >>> await raster.cache_size
844
+ """
845
+ return await super()._cache_size(self.endpoint)
846
+
847
+
848
+ def to_sync(self, sync_client: 'SyncGeoboxClient') -> 'SyncRaster':
849
+ """
850
+ Switch to sync version of the raster instance to have access to the sync methods
851
+
852
+ Args:
853
+ sync_client (SyncGeoboxClient): The sync version of the GeoboxClient instance for making requests.
854
+
855
+ Returns:
856
+ geobox.raster.Raster: the sync instance of the raster.
857
+
858
+ Example:
859
+ >>> from geobox import Geoboxclient
860
+ >>> from geobox.aio import AsyncGeoboxClient
861
+ >>> from geobox.aio.raster import Raster
862
+ >>> client = GeoboxClient()
863
+ >>> async with AsyncGeoboxClient() as async_client:
864
+ >>> raster = await Raster.get_raster(async_client, uuid="12345678-1234-5678-1234-567812345678")
865
+ >>> sync_raster = raster.to_sync(client)
866
+ """
867
+ from ..raster import Raster as SyncRaster
868
+
869
+ return SyncRaster(api=sync_client, uuid=self.uuid, data=self.data)