geobox 2.1.0__py3-none-any.whl → 2.2.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 (70) hide show
  1. geobox/__init__.py +61 -63
  2. geobox/aio/__init__.py +61 -63
  3. geobox/aio/api.py +491 -574
  4. geobox/aio/apikey.py +263 -263
  5. geobox/aio/attachment.py +341 -339
  6. geobox/aio/base.py +261 -262
  7. geobox/aio/basemap.py +196 -196
  8. geobox/aio/dashboard.py +340 -342
  9. geobox/aio/feature.py +35 -35
  10. geobox/aio/field.py +315 -321
  11. geobox/aio/file.py +72 -72
  12. geobox/aio/layout.py +340 -341
  13. geobox/aio/log.py +23 -23
  14. geobox/aio/map.py +1033 -1034
  15. geobox/aio/model3d.py +415 -415
  16. geobox/aio/mosaic.py +696 -696
  17. geobox/aio/plan.py +314 -314
  18. geobox/aio/query.py +693 -693
  19. geobox/aio/raster.py +88 -454
  20. geobox/aio/{analysis.py → raster_analysis.py} +153 -170
  21. geobox/aio/route.py +4 -4
  22. geobox/aio/scene.py +340 -342
  23. geobox/aio/settings.py +18 -18
  24. geobox/aio/task.py +404 -402
  25. geobox/aio/tile3d.py +337 -339
  26. geobox/aio/tileset.py +102 -103
  27. geobox/aio/usage.py +52 -51
  28. geobox/aio/user.py +506 -507
  29. geobox/aio/vector_tool.py +1968 -0
  30. geobox/aio/vectorlayer.py +316 -414
  31. geobox/aio/version.py +272 -273
  32. geobox/aio/view.py +1019 -983
  33. geobox/aio/workflow.py +340 -341
  34. geobox/api.py +14 -98
  35. geobox/apikey.py +262 -262
  36. geobox/attachment.py +336 -337
  37. geobox/base.py +384 -384
  38. geobox/basemap.py +194 -194
  39. geobox/dashboard.py +339 -341
  40. geobox/enums.py +31 -1
  41. geobox/feature.py +31 -10
  42. geobox/field.py +320 -320
  43. geobox/file.py +4 -4
  44. geobox/layout.py +339 -340
  45. geobox/log.py +4 -4
  46. geobox/map.py +1031 -1032
  47. geobox/model3d.py +410 -410
  48. geobox/mosaic.py +696 -696
  49. geobox/plan.py +313 -313
  50. geobox/query.py +691 -691
  51. geobox/raster.py +5 -368
  52. geobox/{analysis.py → raster_analysis.py} +108 -128
  53. geobox/scene.py +341 -342
  54. geobox/settings.py +194 -194
  55. geobox/task.py +399 -400
  56. geobox/tile3d.py +337 -338
  57. geobox/tileset.py +4 -4
  58. geobox/usage.py +3 -3
  59. geobox/user.py +503 -503
  60. geobox/vector_tool.py +1968 -0
  61. geobox/vectorlayer.py +5 -110
  62. geobox/version.py +272 -272
  63. geobox/view.py +981 -981
  64. geobox/workflow.py +338 -339
  65. {geobox-2.1.0.dist-info → geobox-2.2.1.dist-info}/METADATA +15 -1
  66. geobox-2.2.1.dist-info/RECORD +72 -0
  67. geobox-2.1.0.dist-info/RECORD +0 -70
  68. {geobox-2.1.0.dist-info → geobox-2.2.1.dist-info}/WHEEL +0 -0
  69. {geobox-2.1.0.dist-info → geobox-2.2.1.dist-info}/licenses/LICENSE +0 -0
  70. {geobox-2.1.0.dist-info → geobox-2.2.1.dist-info}/top_level.txt +0 -0
geobox/task.py CHANGED
@@ -1,401 +1,400 @@
1
- from urllib.parse import urljoin, urlencode
2
- from typing import Optional, Dict, List, Optional, Union, TYPE_CHECKING
3
- import time
4
-
5
- from .base import Base
6
- from .enums import TaskStatus
7
-
8
- if TYPE_CHECKING:
9
- from . import GeoboxClient
10
- from .vectorlayer import VectorLayer
11
- from .raster import Raster
12
- from .model3d import Model
13
- from .file import File
14
- from .tile3d import Tile3d
15
- from .aio import AsyncGeoboxClient
16
- from .aio.task import Task as AsyncTask
17
-
18
-
19
- class Task(Base):
20
-
21
- BASE_ENDPOINT: str = 'tasks/'
22
-
23
- def __init__(self,
24
- api: 'GeoboxClient',
25
- uuid: str,
26
- data: Optional[Dict] = {}):
27
- """
28
- Constructs all the necessary attributes for the Task object.
29
-
30
- Args:
31
- api (GeoboxClient): The API instance.
32
- uuid (str): The UUID of the task.
33
- data (Dict, optional): The task data.
34
- """
35
- super().__init__(api, uuid=uuid, data=data)
36
- self._data = data if isinstance(data, dict) else {}
37
-
38
-
39
- def refresh_data(self) -> None:
40
- """
41
- Updates the task data.
42
- """
43
- self._data = self.get_task(self.api, self.uuid).data
44
-
45
-
46
- @property
47
- def output_asset(self) -> Union['VectorLayer', 'Raster', 'Model', 'File', 'Tile3d', None]:
48
- """
49
- output asset property
50
-
51
- Returns:
52
- VectorLayer | Raster | Model | Tile3d | None: if task type is publish, it returns the published layer
53
-
54
- Example:
55
- >>> from geobox import GeoboxClient
56
- >>> from geobox.task import Task
57
- >>> client = GeoboxClient()
58
- >>> task = Task.get_task(client, uuid="12345678-1234-5678-1234-567812345678")
59
- >>> task.output_asset
60
- """
61
- if self.data.get('result', {}).get('layer_uuid'):
62
- return self.api.get_vector(uuid=self.data['result']['layer_uuid'])
63
-
64
- elif self.data.get('result', {}).get('raster_uuid'):
65
- return self.api.get_raster(uuid=self.data['result']['raster_uuid'])
66
-
67
- elif self.data.get('result', {}).get('model_uuid'):
68
- return self.api.get_model(uuid=self.data['result']['model_uuid'])
69
-
70
- elif self.data.get('result', {}).get('file_uuid'):
71
- return self.api.get_file(uuid=self.data['result']['file_uuid'])
72
-
73
- elif self.data.get('result', {}).get('3dtiles_uuid'):
74
- return self.api.get_3dtile(uuid=self.data['result']['3dtiles_uuid'])
75
-
76
- else:
77
- return None
78
-
79
-
80
- @property
81
- def data(self) -> Dict:
82
- """
83
- Returns the task data.
84
-
85
- Returns:
86
- Dict: the task data as a dictionary
87
-
88
- Example:
89
- >>> from geobox import GeoboxClient
90
- >>> from geobox.task import Task
91
- >>> client = GeoboxClient()
92
- >>> task = Task.get_task(client, uuid="12345678-1234-5678-1234-567812345678")
93
- >>> task.data
94
- """
95
- return self._data
96
-
97
-
98
- @data.setter
99
- def data(self, value: Dict) -> None:
100
- """
101
- Sets the task data.
102
-
103
- Example:
104
- >>> from geobox import GeoboxClient
105
- >>> from geobox.task import Task
106
- >>> client = GeoboxClient()
107
- >>> task = Task.get_task(client, uuid="12345678-1234-5678-1234-567812345678")
108
- >>> task.data = {'name': 'test'}
109
- """
110
- self._data = value if isinstance(value, dict) else {}
111
-
112
-
113
- @property
114
- def status(self) -> 'TaskStatus':
115
- """
116
- Returns the status of the task. (auto refresh)
117
-
118
- Returns:
119
- TaskStatus: the status of the task(SUCCESS, FAILURE, ABORTED, PENDING, PROGRESS)
120
-
121
- Example:
122
- >>> from geobox import GeoboxClient
123
- >>> from geobox.task import Task
124
- >>> client = GeoboxClient()
125
- >>> task = Task.get_task(client, uuid="12345678-1234-5678-1234-567812345678")
126
- >>> task.status
127
- """
128
- self.refresh_data()
129
- return TaskStatus(self._data.get('state'))
130
-
131
-
132
- @property
133
- def errors(self) -> Union[Dict, None]:
134
- """
135
- Get the task errors.
136
-
137
- Returns:
138
- Dict | None: if there are any errors
139
-
140
- Example:
141
- >>> from geobox import GeoboxClient
142
- >>> from geobox.task import Task
143
- >>> client = GeoboxClient()
144
- >>> task = Task.get_task(client, uuid="12345678-1234-5678-1234-567812345678")
145
- >>> task.errors
146
- """
147
- result = self.data.get('result', {})
148
- if result.get('errors') or result.get('detail', {}).get('msg'):
149
- return result
150
- else:
151
- return None
152
-
153
-
154
- @property
155
- def progress(self) -> Union[int, None]:
156
- """
157
- Returns the progress of the task.
158
-
159
- Returns:
160
- int | None: the progress of the task in percentage or None if the task is not running
161
-
162
- Example:
163
- >>> from geobox import GeoboxClient
164
- >>> from geobox.task import Task
165
- >>> client = GeoboxClient()
166
- >>> task = Task.get_task(client, uuid="12345678-1234-5678-1234-567812345678")
167
- >>> task.progress
168
- """
169
- endpoint = urljoin(self.endpoint, 'status/')
170
- response = self.api.get(endpoint)
171
-
172
- current = response.get('current')
173
- total = response.get('total')
174
- if not total or not current:
175
- return None
176
-
177
- return int((current / total) * 100)
178
-
179
-
180
- def _wait(self, timeout: Union[int, None] = None, interval: int = 1, progress_bar: bool = True) -> 'TaskStatus':
181
- start_time = time.time()
182
- last_progress = 0
183
- pbar = self._create_progress_bar() if progress_bar else None
184
-
185
- try:
186
- while True:
187
- self._check_timeout(start_time, timeout)
188
- status = self.status
189
-
190
- if self._is_final_state(status):
191
- self._update_progress_bar(pbar, last_progress, status)
192
- return TaskStatus(status)
193
-
194
- if pbar:
195
- last_progress = self._update_progress_bar(pbar, last_progress)
196
-
197
- time.sleep(interval)
198
- finally:
199
- if pbar:
200
- pbar.close()
201
-
202
-
203
- def wait(self, timeout: Union[int, None] = None, interval: int = 1, progress_bar: bool = True, retry: int = 3) -> 'TaskStatus':
204
- """
205
- Wait for the task to finish.
206
-
207
- Args:
208
- timeout (int, optional): Maximum time to wait in seconds.
209
- interval (int, optional): Time between status checks in seconds.
210
- progress_bar (bool, optional): Whether to show a progress bar. default: True
211
- retry (int, optional): Number of times to retry if waiting for the task fails. default is 3
212
-
213
- Returns:
214
- TaskStatus: the status of the task(SUCCESS, FAILURE, ABORTED, PENDING, PROGRESS)
215
-
216
- Raises:
217
- TimeoutError: If the task doesn't complete within timeout seconds.
218
-
219
- Example:
220
- >>> from geobox import GeoboxClient
221
- >>> from geobox.task import Task
222
- >>> client = GeoboxClient()
223
- >>> task = Task.get_task(client, uuid="12345678-1234-5678-1234-567812345678")
224
- >>> task.wait() # return the status of the task
225
- """
226
- last_exception = None
227
-
228
- for attempt in range(1, retry + 1):
229
- try:
230
- return self._wait(timeout, interval, progress_bar)
231
- except Exception as e:
232
- last_exception = e
233
- print(f"[Retry {attempt}/{retry}] Task wait failed: {e}")
234
- time.sleep(interval)
235
- raise last_exception
236
-
237
-
238
- def _create_progress_bar(self) -> 'tqdm':
239
- """Creates a progress bar for the task."""
240
- try:
241
- from tqdm.auto import tqdm
242
- except ImportError:
243
- from .api import logger
244
- logger.warning("[tqdm] extra is required to show the progress bar. install with: pip insatll geobox[tqdm]")
245
- return None
246
-
247
- return tqdm(total=100, colour='green', desc=f"Task: {self.name}", unit="%", leave=True)
248
-
249
-
250
- def _check_timeout(self, start_time: float, timeout: Union[int, None]) -> None:
251
- """Checks if the task has exceeded the timeout period."""
252
- if timeout and time.time() - start_time > float(timeout):
253
- raise TimeoutError(f"Task {self.name} timed out after {timeout} seconds")
254
-
255
-
256
- def _is_final_state(self, status: 'TaskStatus') -> bool:
257
- """Checks if the task has reached a final state."""
258
- return status in [TaskStatus.FAILURE, TaskStatus.SUCCESS, TaskStatus.ABORTED]
259
-
260
-
261
- def _update_progress_bar(self, pbar: Union['tqdm', None], last_progress: int, status: 'TaskStatus' = None) -> int:
262
- """
263
- Updates the progress bar with current progress and returns the new last_progress.
264
-
265
- Args:
266
- pbar (tqdm | None): The progress bar to update
267
- last_progress (int): The last progress value
268
- status (TaskStatus, optional): The task status. If provided and SUCCESS, updates to 100%
269
-
270
- Returns:
271
- int: The new last_progress value
272
- """
273
- if not pbar:
274
- return last_progress
275
-
276
- if status == TaskStatus.SUCCESS:
277
- pbar.update(100 - last_progress)
278
- return 100
279
-
280
- current_progress = self.progress
281
- if current_progress is not None:
282
- progress_diff = current_progress - last_progress
283
- if progress_diff > 0:
284
- pbar.update(progress_diff)
285
- return current_progress
286
- return last_progress
287
-
288
-
289
- def abort(self) -> None:
290
- """
291
- Aborts the task.
292
-
293
- Returns:
294
- None
295
-
296
- Example:
297
- >>> from geobox import GeoboxClient
298
- >>> from geobox.task import Task
299
- >>> client = GeoboxClient()
300
- >>> task = Task.get_task(client, uuid="12345678-1234-5678-1234-567812345678")
301
- >>> task.abort()
302
- """
303
- endpoint = urljoin(self.endpoint, 'abort/')
304
- self.api.post(endpoint)
305
-
306
-
307
- @classmethod
308
- def get_tasks(cls, api: 'GeoboxClient', **kwargs) -> Union[List['Task'], int]:
309
- """
310
- Get a list of tasks
311
-
312
- Args:
313
- api (GeoboxClient): The GeoboxClient instance for making requests.
314
-
315
- Keyword Args:
316
- state (TaskStatus): Available values : TaskStatus.PENDING, TaskStatus.PROGRESS, TaskStatus.SUCCESS, TaskStatus.FAILURE, TaskStatus.ABORTED
317
- q (str): query filter based on OGC CQL standard. e.g. "field1 LIKE '%GIS%' AND created_at > '2021-01-01'"
318
- 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.
319
- search_fields (str): comma separated list of fields for searching.
320
- 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.
321
- return_count (bool): The count of the tasks. default is False.
322
- skip (int): The skip of the task. default is 0.
323
- limit (int): The limit of the task. default is 10.
324
- user_id (int): Specific user. privileges required.
325
- shared (bool): Whether to return shared tasks. default is False.
326
-
327
- Returns:
328
- List[Task] | int: The list of task objects or the count of the tasks if return_count is True.
329
-
330
- Example:
331
- >>> from geobox import GeoboxClient
332
- >>> from geobox.task import Task
333
- >>> client = GeoboxClient()
334
- >>> tasks = Task.get_tasks(client)
335
- or
336
- >>> tasks = client.get_tasks()
337
- """
338
- params = {
339
- 'f': 'json',
340
- 'state': kwargs.get('state').value if kwargs.get('state') else None,
341
- 'q': kwargs.get('q'),
342
- 'search': kwargs.get('search'),
343
- 'search_fields': kwargs.get('search_fields'),
344
- 'order_by': kwargs.get('order_by'),
345
- 'return_count': kwargs.get('return_count', False),
346
- 'skip': kwargs.get('skip'),
347
- 'limit': kwargs.get('limit'),
348
- 'user_id': kwargs.get('user_id'),
349
- 'shared': kwargs.get('shared', False)
350
- }
351
- return super()._get_list(api, cls.BASE_ENDPOINT, params, factory_func=lambda api, item: Task(api, item['uuid'], item))
352
-
353
-
354
-
355
- @classmethod
356
- def get_task(cls, api: 'GeoboxClient', uuid: str) -> 'Task':
357
- """
358
- Gets a task.
359
-
360
- Args:
361
- api (GeoboxClient): The GeoboxClient instance for making requests.
362
- uuid (str): The UUID of the task.
363
-
364
- Returns:
365
- Task: The task object.
366
-
367
- Example:
368
- >>> from geobox import GeoboxClient
369
- >>> from geobox.task import Task
370
- >>> client = GeoboxClient()
371
- >>> task = Task.get_task(client, uuid="12345678-1234-5678-1234-567812345678")
372
- or
373
- >>> task = client.get_task(uuid="12345678-1234-5678-1234-567812345678")
374
- """
375
- return super()._get_detail(api, cls.BASE_ENDPOINT, uuid, factory_func=lambda api, item: Task(api, item['uuid'], item))
376
-
377
-
378
- def to_async(self, async_client: 'AsyncGeoboxClient') -> 'AsyncTask':
379
- """
380
- Switch to async version of the task instance to have access to the async methods
381
-
382
- Args:
383
- async_client (AsyncGeoboxClient): The async version of the GeoboxClient instance for making requests.
384
-
385
- Returns:
386
- geobox.aio.task.Task: the async instance of the task.
387
-
388
- Example:
389
- >>> from geobox import Geoboxclient
390
- >>> from geobox.aio import AsyncGeoboxClient
391
- >>> from geobox.task import Task
392
- >>> client = GeoboxClient()
393
- >>> task = Task.get_task(client, uuid="12345678-1234-5678-1234-567812345678")
394
- or
395
- >>> task = client.get_task(uuid="12345678-1234-5678-1234-567812345678")
396
- >>> async with AsyncGeoboxClient() as async_client:
397
- >>> async_task = task.to_async(async_client)
398
- """
399
- from .aio.task import Task as AsyncTask
400
-
1
+ from urllib.parse import urljoin, urlencode
2
+ from typing import Optional, Dict, List, Optional, Union, TYPE_CHECKING
3
+ import time
4
+
5
+ from .base import Base
6
+ from .enums import TaskStatus
7
+
8
+ if TYPE_CHECKING:
9
+ from . import GeoboxClient
10
+ from .vectorlayer import VectorLayer
11
+ from .raster import Raster
12
+ from .model3d import Model
13
+ from .file import File
14
+ from .tile3d import Tile3d
15
+ from .aio import AsyncGeoboxClient
16
+ from .aio.task import AsyncTask
17
+
18
+
19
+ class Task(Base):
20
+
21
+ BASE_ENDPOINT: str = 'tasks/'
22
+
23
+ def __init__(self,
24
+ api: 'GeoboxClient',
25
+ uuid: str,
26
+ data: Optional[Dict] = {}):
27
+ """
28
+ Constructs all the necessary attributes for the Task object.
29
+
30
+ Args:
31
+ api (GeoboxClient): The API instance.
32
+ uuid (str): The UUID of the task.
33
+ data (Dict, optional): The task data.
34
+ """
35
+ super().__init__(api, uuid=uuid, data=data)
36
+ self._data = data if isinstance(data, dict) else {}
37
+
38
+
39
+ def refresh_data(self) -> None:
40
+ """
41
+ Updates the task data.
42
+ """
43
+ self._data = self.get_task(self.api, self.uuid).data
44
+
45
+
46
+ @property
47
+ def output_asset(self) -> Union['VectorLayer', 'Raster', 'Model', 'File', 'Tile3d', None]:
48
+ """
49
+ output asset property
50
+
51
+ Returns:
52
+ VectorLayer | Raster | Model | File | Tile3d | None: if task type is publish, it returns the published layer
53
+
54
+ Example:
55
+ >>> from geobox import GeoboxClient
56
+ >>> from geobox.task import Task
57
+ >>> client = GeoboxClient()
58
+ >>> task = Task.get_task(client, uuid="12345678-1234-5678-1234-567812345678")
59
+ >>> task.output_asset
60
+ """
61
+ if self.data.get('result', {}).get('layer_uuid'):
62
+ return self.api.get_vector(uuid=self.data['result']['layer_uuid'])
63
+
64
+ elif self.data.get('result', {}).get('raster_uuid'):
65
+ return self.api.get_raster(uuid=self.data['result']['raster_uuid'])
66
+
67
+ elif self.data.get('result', {}).get('model_uuid'):
68
+ return self.api.get_model(uuid=self.data['result']['model_uuid'])
69
+
70
+ elif self.data.get('result', {}).get('file_uuid'):
71
+ return self.api.get_file(uuid=self.data['result']['file_uuid'])
72
+
73
+ elif self.data.get('result', {}).get('3dtiles_uuid'):
74
+ return self.api.get_3dtile(uuid=self.data['result']['3dtiles_uuid'])
75
+
76
+ else:
77
+ return None
78
+
79
+
80
+ @property
81
+ def data(self) -> Dict:
82
+ """
83
+ Returns the task data.
84
+
85
+ Returns:
86
+ Dict: the task data as a dictionary
87
+
88
+ Example:
89
+ >>> from geobox import GeoboxClient
90
+ >>> from geobox.task import Task
91
+ >>> client = GeoboxClient()
92
+ >>> task = Task.get_task(client, uuid="12345678-1234-5678-1234-567812345678")
93
+ >>> task.data
94
+ """
95
+ return self._data
96
+
97
+
98
+ @data.setter
99
+ def data(self, value: Dict) -> None:
100
+ """
101
+ Sets the task data.
102
+
103
+ Example:
104
+ >>> from geobox import GeoboxClient
105
+ >>> from geobox.task import Task
106
+ >>> client = GeoboxClient()
107
+ >>> task = Task.get_task(client, uuid="12345678-1234-5678-1234-567812345678")
108
+ >>> task.data = {'name': 'test'}
109
+ """
110
+ self._data = value if isinstance(value, dict) else {}
111
+
112
+
113
+ @property
114
+ def status(self) -> 'TaskStatus':
115
+ """
116
+ Returns the status of the task. (auto refresh)
117
+
118
+ Returns:
119
+ TaskStatus: the status of the task(SUCCESS, FAILURE, ABORTED, PENDING, PROGRESS)
120
+
121
+ Example:
122
+ >>> from geobox import GeoboxClient
123
+ >>> from geobox.task import Task
124
+ >>> client = GeoboxClient()
125
+ >>> task = Task.get_task(client, uuid="12345678-1234-5678-1234-567812345678")
126
+ >>> task.status
127
+ """
128
+ self.refresh_data()
129
+ return TaskStatus(self._data.get('state'))
130
+
131
+
132
+ @property
133
+ def errors(self) -> Union[Dict, None]:
134
+ """
135
+ Get the task errors.
136
+
137
+ Returns:
138
+ Dict | None: if there are any errors
139
+
140
+ Example:
141
+ >>> from geobox import GeoboxClient
142
+ >>> from geobox.task import Task
143
+ >>> client = GeoboxClient()
144
+ >>> task = Task.get_task(client, uuid="12345678-1234-5678-1234-567812345678")
145
+ >>> task.errors
146
+ """
147
+ result = self.data.get('result', {})
148
+ if result.get('errors') or result.get('detail', {}).get('msg'):
149
+ return result
150
+ else:
151
+ return None
152
+
153
+
154
+ @property
155
+ def progress(self) -> Union[int, None]:
156
+ """
157
+ Returns the progress of the task.
158
+
159
+ Returns:
160
+ int | None: the progress of the task in percentage or None if the task is not running
161
+
162
+ Example:
163
+ >>> from geobox import GeoboxClient
164
+ >>> from geobox.task import Task
165
+ >>> client = GeoboxClient()
166
+ >>> task = Task.get_task(client, uuid="12345678-1234-5678-1234-567812345678")
167
+ >>> task.progress
168
+ """
169
+ endpoint = urljoin(self.endpoint, 'status/')
170
+ response = self.api.get(endpoint)
171
+
172
+ current = response.get('current')
173
+ total = response.get('total')
174
+ if not total or not current:
175
+ return None
176
+
177
+ return int((current / total) * 100)
178
+
179
+
180
+ def _wait(self, timeout: Union[int, None] = None, interval: int = 1, progress_bar: bool = True) -> 'TaskStatus':
181
+ start_time = time.time()
182
+ last_progress = 0
183
+ pbar = self._create_progress_bar() if progress_bar else None
184
+
185
+ try:
186
+ while True:
187
+ self._check_timeout(start_time, timeout)
188
+ status = self.status
189
+
190
+ if self._is_final_state(status):
191
+ self._update_progress_bar(pbar, last_progress, status)
192
+ return status
193
+
194
+ if pbar:
195
+ last_progress = self._update_progress_bar(pbar, last_progress)
196
+
197
+ time.sleep(interval)
198
+ finally:
199
+ if pbar:
200
+ pbar.close()
201
+
202
+
203
+ def wait(self, timeout: Union[int, None] = None, interval: int = 1, progress_bar: bool = True, retry: int = 3) -> 'TaskStatus':
204
+ """
205
+ Wait for the task to finish.
206
+
207
+ Args:
208
+ timeout (int, optional): Maximum time to wait in seconds.
209
+ interval (int, optional): Time between status checks in seconds.
210
+ progress_bar (bool, optional): Whether to show a progress bar. default: True
211
+ retry (int, optional): Number of times to retry if waiting for the task fails. default is 3
212
+
213
+ Returns:
214
+ TaskStatus: the status of the task(SUCCESS, FAILURE, ABORTED, PENDING, PROGRESS)
215
+
216
+ Raises:
217
+ TimeoutError: If the task doesn't complete within timeout seconds.
218
+
219
+ Example:
220
+ >>> from geobox import GeoboxClient
221
+ >>> from geobox.task import Task
222
+ >>> client = GeoboxClient()
223
+ >>> task = Task.get_task(client, uuid="12345678-1234-5678-1234-567812345678")
224
+ >>> task.wait() # return the status of the task
225
+ """
226
+ last_exception = None
227
+
228
+ for attempt in range(1, retry + 1):
229
+ try:
230
+ return self._wait(timeout, interval, progress_bar)
231
+ except Exception as e:
232
+ last_exception = e
233
+ print(f"[Retry {attempt}/{retry}] Task wait failed: {e}")
234
+ time.sleep(interval)
235
+ raise last_exception
236
+
237
+
238
+ def _create_progress_bar(self) -> 'tqdm':
239
+ """Creates a progress bar for the task."""
240
+ try:
241
+ from tqdm.auto import tqdm
242
+ except ImportError:
243
+ from .api import logger
244
+ logger.warning("[tqdm] extra is required to show the progress bar. install with: pip insatll geobox[tqdm]")
245
+ return None
246
+
247
+ return tqdm(total=100, colour='green', desc=f"Task: {self.name}", unit="%", leave=True)
248
+
249
+
250
+ def _check_timeout(self, start_time: float, timeout: Union[int, None]) -> None:
251
+ """Checks if the task has exceeded the timeout period."""
252
+ if timeout and time.time() - start_time > float(timeout):
253
+ raise TimeoutError(f"Task {self.name} timed out after {timeout} seconds")
254
+
255
+
256
+ def _is_final_state(self, status: 'TaskStatus') -> bool:
257
+ """Checks if the task has reached a final state."""
258
+ return status in [TaskStatus.FAILURE, TaskStatus.SUCCESS, TaskStatus.ABORTED]
259
+
260
+
261
+ def _update_progress_bar(self, pbar: Union['tqdm', None], last_progress: int, status: 'TaskStatus' = None) -> int:
262
+ """
263
+ Updates the progress bar with current progress and returns the new last_progress.
264
+
265
+ Args:
266
+ pbar (tqdm | None): The progress bar to update
267
+ last_progress (int): The last progress value
268
+ status (TaskStatus, optional): The task status. If provided and SUCCESS, updates to 100%
269
+
270
+ Returns:
271
+ int: The new last_progress value
272
+ """
273
+ if not pbar:
274
+ return last_progress
275
+
276
+ if status == TaskStatus.SUCCESS:
277
+ pbar.update(100 - last_progress)
278
+ return 100
279
+
280
+ current_progress = self.progress
281
+ if current_progress is not None:
282
+ progress_diff = current_progress - last_progress
283
+ if progress_diff > 0:
284
+ pbar.update(progress_diff)
285
+ return current_progress
286
+ return last_progress
287
+
288
+
289
+ def abort(self) -> None:
290
+ """
291
+ Aborts the task.
292
+
293
+ Returns:
294
+ None
295
+
296
+ Example:
297
+ >>> from geobox import GeoboxClient
298
+ >>> from geobox.task import Task
299
+ >>> client = GeoboxClient()
300
+ >>> task = Task.get_task(client, uuid="12345678-1234-5678-1234-567812345678")
301
+ >>> task.abort()
302
+ """
303
+ endpoint = urljoin(self.endpoint, 'abort/')
304
+ self.api.post(endpoint)
305
+
306
+
307
+ @classmethod
308
+ def get_tasks(cls, api: 'GeoboxClient', **kwargs) -> Union[List['Task'], int]:
309
+ """
310
+ Get a list of tasks
311
+
312
+ Args:
313
+ api (GeoboxClient): The GeoboxClient instance for making requests.
314
+
315
+ Keyword Args:
316
+ state (TaskStatus): Available values : TaskStatus.PENDING, TaskStatus.PROGRESS, TaskStatus.SUCCESS, TaskStatus.FAILURE, TaskStatus.ABORTED
317
+ q (str): query filter based on OGC CQL standard. e.g. "field1 LIKE '%GIS%' AND created_at > '2021-01-01'"
318
+ 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.
319
+ search_fields (str): comma separated list of fields for searching.
320
+ 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.
321
+ return_count (bool): The count of the tasks. default is False.
322
+ skip (int): The skip of the task. default is 0.
323
+ limit (int): The limit of the task. default is 10.
324
+ user_id (int): Specific user. privileges required.
325
+ shared (bool): Whether to return shared tasks. default is False.
326
+
327
+ Returns:
328
+ List[Task] | int: The list of task objects or the count of the tasks if return_count is True.
329
+
330
+ Example:
331
+ >>> from geobox import GeoboxClient
332
+ >>> from geobox.task import Task
333
+ >>> client = GeoboxClient()
334
+ >>> tasks = Task.get_tasks(client)
335
+ or
336
+ >>> tasks = client.get_tasks()
337
+ """
338
+ params = {
339
+ 'f': 'json',
340
+ 'state': kwargs.get('state').value if kwargs.get('state') else None,
341
+ 'q': kwargs.get('q'),
342
+ 'search': kwargs.get('search'),
343
+ 'search_fields': kwargs.get('search_fields'),
344
+ 'order_by': kwargs.get('order_by'),
345
+ 'return_count': kwargs.get('return_count', False),
346
+ 'skip': kwargs.get('skip'),
347
+ 'limit': kwargs.get('limit'),
348
+ 'user_id': kwargs.get('user_id'),
349
+ 'shared': kwargs.get('shared', False)
350
+ }
351
+ return super()._get_list(api, cls.BASE_ENDPOINT, params, factory_func=lambda api, item: Task(api, item['uuid'], item))
352
+
353
+
354
+ @classmethod
355
+ def get_task(cls, api: 'GeoboxClient', uuid: str) -> 'Task':
356
+ """
357
+ Gets a task.
358
+
359
+ Args:
360
+ api (GeoboxClient): The GeoboxClient instance for making requests.
361
+ uuid (str): The UUID of the task.
362
+
363
+ Returns:
364
+ Task: The task object.
365
+
366
+ Example:
367
+ >>> from geobox import GeoboxClient
368
+ >>> from geobox.task import Task
369
+ >>> client = GeoboxClient()
370
+ >>> task = Task.get_task(client, uuid="12345678-1234-5678-1234-567812345678")
371
+ or
372
+ >>> task = client.get_task(uuid="12345678-1234-5678-1234-567812345678")
373
+ """
374
+ return super()._get_detail(api, cls.BASE_ENDPOINT, uuid, factory_func=lambda api, item: Task(api, item['uuid'], item))
375
+
376
+
377
+ def to_async(self, async_client: 'AsyncGeoboxClient') -> 'AsyncTask':
378
+ """
379
+ Switch to async version of the task instance to have access to the async methods
380
+
381
+ Args:
382
+ async_client (AsyncGeoboxClient): The async version of the GeoboxClient instance for making requests.
383
+
384
+ Returns:
385
+ AsyncTask: the async instance of the task.
386
+
387
+ Example:
388
+ >>> from geobox import Geoboxclient
389
+ >>> from geobox.aio import AsyncGeoboxClient
390
+ >>> from geobox.task import Task
391
+ >>> client = GeoboxClient()
392
+ >>> task = Task.get_task(client, uuid="12345678-1234-5678-1234-567812345678")
393
+ or
394
+ >>> task = client.get_task(uuid="12345678-1234-5678-1234-567812345678")
395
+ >>> async with AsyncGeoboxClient() as async_client:
396
+ >>> async_task = task.to_async(async_client)
397
+ """
398
+ from .aio.task import AsyncTask
399
+
401
400
  return AsyncTask(api=async_client, uuid=self.uuid, data=self.data)