pixel-client 1.1.0__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.
pixel_client/_base.py ADDED
@@ -0,0 +1,2540 @@
1
+ import asyncio
2
+ import json
3
+ import logging
4
+ from functools import partial
5
+ from pathlib import Path
6
+ from typing import Any, AsyncGenerator, Literal, TypeVar, Self, TypedDict, Unpack
7
+ from uuid import uuid4
8
+
9
+ import httpx
10
+ from geojson_pydantic import Polygon
11
+ from tqdm import tqdm
12
+
13
+ from .auth import KeyCloakAuth
14
+ from .exceptions import (
15
+ PixelBadRequestError,
16
+ PixelMultipleUploadJobError,
17
+ PixelUploadJobError,
18
+ )
19
+ from .models import (
20
+ ArcgisServiceCreateInput,
21
+ ArcgisServiceUpdateInput,
22
+ DataCollectionListParams,
23
+ HarvestServiceCreateInput,
24
+ HarvestTaskListParams,
25
+ ListParams,
26
+ NearblackOptions,
27
+ OIDCUserCreateInput,
28
+ OIDCUserUpdateInput,
29
+ PixelAttachmentUpload,
30
+ PixelUploadFile,
31
+ RasterInfo,
32
+ ImageUpdateInput,
33
+ HarvestServiceUpdateInput,
34
+ RasterUpdateInput,
35
+ )
36
+ from .settings import PixelApiSettings
37
+ from .types import AttachmentResourceType, DataCollectionType, OverviewResampling
38
+ from .utils import (
39
+ calculate_md5_base64_from_file,
40
+ chunks,
41
+ iter_file_parts,
42
+ silence_logger,
43
+ )
44
+
45
+
46
+ logger = logging.getLogger(__name__)
47
+
48
+
49
+ T = TypeVar("T")
50
+
51
+ DEFAULT_PIXEL_TIMEOUT = httpx.Timeout(
52
+ 10.0,
53
+ write=15.0,
54
+ )
55
+ DEFAULT_UPLOAD_TIMEOUT = httpx.Timeout(
56
+ 10.0,
57
+ write=300.0, # Increased write timeout for uploads
58
+ )
59
+
60
+
61
+ class PixelClientKwargs(TypedDict, total=False):
62
+ """TypedDict for PixelClient constructor arguments."""
63
+
64
+ timeout_pixel: httpx.Timeout
65
+ """Timeout configuration for Pixel API requests. Defaults to DEFAULT_PIXEL_TIMEOUT."""
66
+
67
+ timeout_upload: httpx.Timeout
68
+ """Timeout configuration for file uploads. Defaults to DEFAULT_UPLOAD_TIMEOUT"""
69
+
70
+
71
+ class PixelClientAsync:
72
+ """Asynchronous client for interacting with the Pixel API.
73
+
74
+ This client provides methods for working with projects, data collections, images,
75
+ rasters, and other resources in the Pixel system. It handles authentication,
76
+ request management, and provides high-level operations for common tasks.
77
+ """
78
+
79
+ def __init__(
80
+ self,
81
+ url: str,
82
+ keycloak_server_url: str,
83
+ realm: str,
84
+ client_id: str,
85
+ username: str,
86
+ password: str,
87
+ timeout_pixel: httpx.Timeout = DEFAULT_PIXEL_TIMEOUT,
88
+ timeout_upload: httpx.Timeout = DEFAULT_UPLOAD_TIMEOUT,
89
+ ):
90
+ """Initialize a new Pixel API client.
91
+
92
+ Args:
93
+ url: Base URL of the Pixel API.
94
+ keycloak_server_url: URL of the Keycloak authentication server.
95
+ realm: Keycloak realm name.
96
+ client_id: Keycloak client ID.
97
+ username: Username for authentication.
98
+ password: Password for authentication.
99
+ timeout_pixel: Optional timeout configuration for Pixel API requests.
100
+ timeout_upload: Optional timeout configuration for file uploads. If not provided, defaults to the same as `timeout_pixel`.
101
+ """
102
+ self.url: str = url
103
+ self._timeout_pixel = timeout_pixel
104
+ self._timeout_upload = timeout_upload
105
+ self.auth = KeyCloakAuth(
106
+ keycloak_server_url, realm, client_id, username, password
107
+ )
108
+ self.pixel_client = httpx.AsyncClient(
109
+ base_url=self.url, auth=self.auth, timeout=self._timeout_pixel
110
+ )
111
+ self._internal_client = httpx.AsyncClient(
112
+ timeout=self._timeout_upload, # Use a separate client for uploads
113
+ ) # For s3 uploads
114
+
115
+ @classmethod
116
+ def from_settings(
117
+ cls, settings: PixelApiSettings, **kwargs: Unpack[PixelClientKwargs]
118
+ ) -> Self:
119
+ """Instantiate the client from settings.
120
+
121
+ Args:
122
+ settings: PixelApiSettings object containing API configuration.
123
+ **kwargs: Additional keyword arguments to pass to the client constructor.
124
+
125
+ Returns:
126
+ PixelClientAsync: A new client instance configured with the provided settings.
127
+ """
128
+ return cls(
129
+ url=settings.PIXEL_API_URL,
130
+ keycloak_server_url=settings.KEYCLOAK_SERVER_URL,
131
+ client_id=settings.KEYCLOAK_CLIENT_ID,
132
+ username=settings.KEYCLOAK_USERNAME,
133
+ password=settings.KEYCLOAK_PASSWORD.get_secret_value(),
134
+ realm=settings.KEYCLOAK_REALM.get_secret_value(),
135
+ **kwargs,
136
+ )
137
+
138
+ async def __aenter__(self):
139
+ await self.pixel_client.__aenter__()
140
+ await self._internal_client.__aenter__()
141
+ return self
142
+
143
+ async def __aexit__(self, exc_type, exc_value, traceback):
144
+ await self.pixel_client.__aexit__(exc_type, exc_value, traceback)
145
+ await self._internal_client.__aexit__(exc_type, exc_value, traceback)
146
+
147
+ async def _make_request(self, method: str, url: str, **kwargs) -> httpx.Response:
148
+ """Make an HTTP request to the Pixel API with error handling.
149
+
150
+ Args:
151
+ method: The HTTP method to use (GET, POST, PUT, DELETE).
152
+ url: The URL to request, relative to the base URL.
153
+ **kwargs: Additional arguments to pass to the request method.
154
+
155
+ Returns:
156
+ httpx.Response: The HTTP response object.
157
+
158
+ Raises:
159
+ PixelBadRequestError: If the server returns a 4xx client error with JSON response.
160
+ httpx.HTTPStatusError: For other HTTP errors.
161
+ """
162
+ sensitive_content = kwargs.pop("sensitive_content", False)
163
+ headers = kwargs.pop("headers", {})
164
+ if "X-Request-ID" not in headers:
165
+ headers["X-Request-ID"] = str(uuid4())
166
+ kwargs["headers"] = headers
167
+ response = await self.pixel_client.request(method, url, **kwargs)
168
+ try:
169
+ response.raise_for_status()
170
+ except httpx.HTTPStatusError as e:
171
+ logger.error(f"Error in request {method} {url}: {e}")
172
+ if e.response.is_client_error:
173
+ try:
174
+ response_json = e.response.json()
175
+ except json.JSONDecodeError:
176
+ raise e # If the response is not JSON, raise the original exception
177
+ raise PixelBadRequestError(
178
+ response_json=response_json,
179
+ status_code=e.response.status_code,
180
+ method=method,
181
+ url=str(e.request.url),
182
+ request_id=e.response.headers.get("X-Request-ID"),
183
+ body=e.request.content.decode() if not sensitive_content else None,
184
+ ) from e
185
+ raise e
186
+ return response
187
+
188
+ async def _get(self, url: str, **kwargs) -> httpx.Response:
189
+ """Make a GET request to the Pixel API.
190
+
191
+ Args:
192
+ url: The URL to request, relative to the base URL.
193
+ **kwargs: Additional arguments to pass to the request method.
194
+
195
+ Returns:
196
+ httpx.Response: The HTTP response object.
197
+ """
198
+ return await self._make_request("GET", url, **kwargs)
199
+
200
+ async def _post(self, url: str, **kwargs) -> httpx.Response:
201
+ """Make a POST request to the Pixel API.
202
+
203
+ Args:
204
+ url: The URL to request, relative to the base URL.
205
+ **kwargs: Additional arguments to pass to the request method.
206
+
207
+ Returns:
208
+ httpx.Response: The HTTP response object.
209
+ """
210
+ return await self._make_request("POST", url, **kwargs)
211
+
212
+ async def _put(self, url: str, **kwargs) -> httpx.Response:
213
+ """Make a PUT request to the Pixel API.
214
+
215
+ Args:
216
+ url: The URL to request, relative to the base URL.
217
+ **kwargs: Additional arguments to pass to the request method.
218
+
219
+ Returns:
220
+ httpx.Response: The HTTP response object.
221
+ """
222
+ return await self._make_request("PUT", url, **kwargs)
223
+
224
+ async def _delete(self, url: str, **kwargs) -> httpx.Response:
225
+ """Make a DELETE request to the Pixel API.
226
+
227
+ Args:
228
+ url: The URL to request, relative to the base URL.
229
+ **kwargs: Additional arguments to pass to the request method.
230
+
231
+ Returns:
232
+ httpx.Response: The HTTP response object.
233
+ """
234
+ return await self._make_request("DELETE", url, **kwargs)
235
+
236
+ async def _paginate(
237
+ self, url: str, page_size: int, **kwargs
238
+ ) -> AsyncGenerator[dict, None]:
239
+ """Internal helper function for paginating through API results.
240
+
241
+ Args:
242
+ url: The API endpoint URL to paginate through.
243
+ page_size: Number of items to fetch per page.
244
+ **kwargs: Additional parameters to pass to the GET request.
245
+
246
+ Yields:
247
+ dict: Individual items from the paginated results, one at a time.
248
+ """
249
+ params = kwargs.pop("params", {})
250
+ offset = params.get("offset", 0)
251
+ limit = page_size
252
+ while True:
253
+ response = await self._get(
254
+ url, params={**params, "offset": offset, "limit": limit}
255
+ )
256
+ data = response.json()
257
+ for item in data:
258
+ yield item
259
+ if (
260
+ len(data) < page_size
261
+ ): # If the number of items is less than the page size, we are done
262
+ break
263
+ offset += limit
264
+
265
+ async def me(self, extended: bool = False) -> dict:
266
+ """Get information about the authenticated user.
267
+
268
+ Args:
269
+ extended: If True, returns extended user information including projects user is a member of
270
+
271
+ Returns:
272
+ dict: User information including username, email, and other profile details.
273
+ """
274
+ response = await self._get("/users/me", params={"extended": extended})
275
+ return response.json()
276
+
277
+ async def get_plugins(self) -> list[dict]:
278
+ """Retrieve a list of available plugins for the pixel tenant.
279
+ Possible plugins include:
280
+ * 'optimized_raster' - Optimize Raster capability
281
+ * 'image_service' - Image Service capability, dependent on the 'optimize_raster' plugin.
282
+
283
+ Returns:
284
+ list[dict]: A list of plugin objects with their details.
285
+ """
286
+ response = await self._get("/plugins/")
287
+ return response.json()
288
+
289
+ async def create_project(
290
+ self,
291
+ name: str,
292
+ description: str,
293
+ area_of_interest: Polygon,
294
+ parent_project_id: int | None = None,
295
+ tags: list[str] | None = None,
296
+ ) -> dict:
297
+ """Create a new project in the Pixel system.
298
+
299
+ Args:
300
+ name: The name of the project.
301
+ description: A description of the project.
302
+ area_of_interest: A GeoJSON polygon defining the project's geographic area of interest.
303
+ parent_project_id: Optional ID of a parent project. If provided, this project will be created as a child of that project.
304
+ tags: Optional list of tags to associate with the project.
305
+
306
+ Returns:
307
+ dict: The created project object.
308
+ """
309
+ body = {
310
+ "name": name,
311
+ "description": description,
312
+ "area_of_interest": area_of_interest.__geo_interface__,
313
+ }
314
+ if parent_project_id:
315
+ body["parent_project_id"] = parent_project_id
316
+ if tags:
317
+ body["tags"] = tags
318
+ response = await self._post("/projects/", json=body)
319
+ return response.json()
320
+
321
+ async def list_projects(
322
+ self, params: ListParams | None = None, **kwargs
323
+ ) -> list[dict]:
324
+ """List projects with optional filtering.
325
+
326
+ Args:
327
+ params: Optional ListParams object containing filtering parameters such as offset, limit, search, etc.
328
+ **kwargs: Alternative way to provide filtering parameters. Ignored if params is provided.
329
+
330
+ Returns:
331
+ list[dict]: A list of project objects matching the filter criteria.
332
+ """
333
+ if params and kwargs:
334
+ logger.warning("Ignoring kwargs when params is provided")
335
+ params_dict = (
336
+ params.model_dump(exclude_none=True)
337
+ if params
338
+ else ListParams.model_validate(kwargs).model_dump(exclude_none=True)
339
+ )
340
+ response = await self._get("/projects/", params=params_dict)
341
+ return response.json()
342
+
343
+ async def get_project(self, project_id: int, extended: bool = False) -> dict:
344
+ """Retrieve a project by its ID.
345
+
346
+ Args:
347
+ project_id: The ID of the project to retrieve.
348
+ extended: If True, returns extended project information including child projects and data collections.
349
+
350
+ Returns:
351
+ dict: The project object with its details.
352
+ """
353
+ response = await self._get(
354
+ f"/projects/{project_id}", params={"extended": extended}
355
+ )
356
+ return response.json()
357
+
358
+ async def update_project(
359
+ self,
360
+ project_id: int,
361
+ name: str | None = None,
362
+ description: str | None = None,
363
+ area_of_interest: Polygon | None = None,
364
+ add_tags: list[str] | None = None,
365
+ remove_tags: list[str] | None = None,
366
+ ) -> dict:
367
+ """Update an existing project with new values.
368
+
369
+ Args:
370
+ project_id: The ID of the project to update.
371
+ name: Optional new name for the project.
372
+ description: Optional new description for the project.
373
+ area_of_interest: Optional new GeoJSON polygon defining the project's geographic area of interest.
374
+ add_tags: Optional list of tags to add to the project.
375
+ remove_tags: Optional list of tags to remove from the project.
376
+
377
+ Returns:
378
+ dict: The updated project object.
379
+
380
+ Raises:
381
+ ValueError: If no update parameters are provided.
382
+ """
383
+ body = {}
384
+ for param_name, value in {
385
+ "name": name,
386
+ "description": description,
387
+ "area_of_interest": area_of_interest.__geo_interface__
388
+ if area_of_interest
389
+ else None,
390
+ "add_tags": add_tags,
391
+ "remove_tags": remove_tags,
392
+ }.items():
393
+ if value is not None:
394
+ body[param_name] = value
395
+ if not body:
396
+ raise ValueError("No update parameters provided")
397
+ response = await self._put(f"/projects/{project_id}", json=body)
398
+ return response.json()
399
+
400
+ async def delete_project(self, project_id: int) -> dict:
401
+ """Delete a project by its ID.
402
+
403
+ Args:
404
+ project_id: The ID of the project to delete.
405
+
406
+ Returns:
407
+ dict: The response confirming deletion.
408
+ """
409
+ response = await self._delete(f"/projects/{project_id}")
410
+ return response.json()
411
+
412
+ async def move_project(
413
+ self, project_id: int, new_parent_project_id: int | None = None
414
+ ) -> dict:
415
+ """Move a project to a new parent project or to the root level.
416
+
417
+ Args:
418
+ project_id: The ID of the project to move.
419
+ new_parent_project_id: Optional ID of the new parent project. If None, the project will be moved to the root level.
420
+
421
+ Returns:
422
+ dict: The updated project object.
423
+ """
424
+ # If None is provided, set to -1 to move to root
425
+ new_parent_project_id = new_parent_project_id or -1
426
+ response = await self._put(
427
+ f"/projects/{project_id}",
428
+ params={"new_parent_id": new_parent_project_id},
429
+ )
430
+ return response.json()
431
+
432
+ async def create_data_collection(
433
+ self,
434
+ project_id: int,
435
+ name: str,
436
+ description: str,
437
+ data_collection_type: DataCollectionType,
438
+ tags: list[str] | None = None,
439
+ raster_info: RasterInfo | None = None,
440
+ ) -> dict:
441
+ """Create a new data collection within a project.
442
+
443
+ Args:
444
+ project_id: The ID of the project to create the data collection in.
445
+ name: The name of the data collection.
446
+ description: A description of the data collection.
447
+ data_collection_type: The type of data collection (e.g., "image", "raster", "RGB", "DTM", "DSM").
448
+ tags: Optional list of tags to associate with the data collection.
449
+ raster_info: Optional RasterInfo object containing raster-specific configuration.
450
+
451
+ Returns:
452
+ dict: The created data collection object.
453
+ """
454
+ body: dict[str, Any] = {
455
+ "name": name,
456
+ "description": description,
457
+ "data_collection_type": data_collection_type,
458
+ }
459
+ if tags:
460
+ body["tags"] = tags
461
+ if raster_info:
462
+ body["raster_info"] = raster_info.model_dump(exclude_none=True, mode="json")
463
+ response = await self._post(
464
+ f"/projects/{project_id}/data_collections/", json=body
465
+ )
466
+ return response.json()
467
+
468
+ async def list_data_collections(
469
+ self, project_id: int, params: DataCollectionListParams | None = None, **kwargs
470
+ ) -> list[dict]:
471
+ """List data collections within a project with optional filtering.
472
+
473
+ Args:
474
+ project_id: The ID of the project to list data collections from.
475
+ params: Optional DataCollectionListParams object containing filtering parameters.
476
+ **kwargs: Alternative way to provide filtering parameters. Ignored if params is provided.
477
+
478
+ Returns:
479
+ list[dict]: A list of data collection objects matching the filter criteria.
480
+ """
481
+ if params and kwargs:
482
+ logger.warning("Ignoring kwargs when params is provided")
483
+ params_dict = (
484
+ params.model_dump(exclude_none=True)
485
+ if params
486
+ else DataCollectionListParams.model_validate(kwargs).model_dump(
487
+ exclude_none=True
488
+ )
489
+ )
490
+ response = await self._get(
491
+ f"/projects/{project_id}/data_collections/", params=params_dict
492
+ )
493
+ return response.json()
494
+
495
+ async def get_data_collection(
496
+ self, project_id: int, data_collection_id: int
497
+ ) -> dict:
498
+ """Retrieve a data collection by its ID.
499
+
500
+ Args:
501
+ project_id: The ID of the project containing the data collection.
502
+ data_collection_id: The ID of the data collection to retrieve.
503
+
504
+ Returns:
505
+ dict: The data collection object with its details.
506
+ """
507
+ response = await self._get(
508
+ f"/projects/{project_id}/data_collections/{data_collection_id}"
509
+ )
510
+ return response.json()
511
+
512
+ async def update_data_collection(
513
+ self,
514
+ project_id: int,
515
+ data_collection_id: int,
516
+ name: str | None = None,
517
+ description: str | None = None,
518
+ add_tags: list[str] | None = None,
519
+ remove_tags: list[str] | None = None,
520
+ ) -> dict:
521
+ """Update an existing data collection with new values.
522
+
523
+ Args:
524
+ project_id: The ID of the project containing the data collection.
525
+ data_collection_id: The ID of the data collection to update.
526
+ name: Optional new name for the data collection.
527
+ description: Optional new description for the data collection.
528
+ add_tags: Optional list of tags to add to the data collection.
529
+ remove_tags: Optional list of tags to remove from the data collection.
530
+
531
+ Returns:
532
+ dict: The updated data collection object.
533
+
534
+ Raises:
535
+ ValueError: If no update parameters are provided.
536
+ """
537
+ body = {}
538
+ for param_name, value in {
539
+ "name": name,
540
+ "description": description,
541
+ "add_tags": add_tags,
542
+ "remove_tags": remove_tags,
543
+ }.items():
544
+ if value is not None:
545
+ body[param_name] = value
546
+ if not body:
547
+ raise ValueError("No update parameters provided")
548
+ response = await self._put(
549
+ f"/projects/{project_id}/data_collections/{data_collection_id}", json=body
550
+ )
551
+ return response.json()
552
+
553
+ async def move_data_collection(
554
+ self, project_id: int, data_collection_id: int, new_project_id: int
555
+ ) -> dict:
556
+ """Move a data collection to a different project.
557
+
558
+ Args:
559
+ project_id: The ID of the project currently containing the data collection.
560
+ data_collection_id: The ID of the data collection to move.
561
+ new_project_id: The ID of the project to move the data collection to.
562
+
563
+ Returns:
564
+ dict: The updated data collection object.
565
+ """
566
+ response = await self._put(
567
+ f"/projects/{project_id}/data_collections/{data_collection_id}",
568
+ params={"new_project_id": new_project_id},
569
+ )
570
+ return response.json()
571
+
572
+ async def delete_data_collection(
573
+ self, project_id: int, data_collection_id: int
574
+ ) -> dict:
575
+ """Delete a data collection by its ID.
576
+
577
+ Args:
578
+ project_id: The ID of the project containing the data collection.
579
+ data_collection_id: The ID of the data collection to delete.
580
+
581
+ Returns:
582
+ dict: The response confirming deletion.
583
+ """
584
+ response = await self.pixel_client.delete(
585
+ f"/projects/{project_id}/data_collections/{data_collection_id}"
586
+ )
587
+ return response.json()
588
+
589
+ async def get_images(
590
+ self,
591
+ project_id: int,
592
+ data_collection_id: int,
593
+ params: ListParams | None = None,
594
+ **kwargs,
595
+ ) -> dict:
596
+ """Retrieve images from a data collection with optional filtering.
597
+
598
+ Args:
599
+ project_id: The ID of the project containing the data collection.
600
+ data_collection_id: The ID of the data collection containing the images.
601
+ params: Optional ListParams object containing filtering parameters.
602
+ **kwargs: Alternative way to provide filtering parameters.
603
+
604
+ Returns:
605
+ dict: A list of image objects matching the filter criteria.
606
+ """
607
+ params_dict = params.model_dump(exclude_none=True) if params else {}
608
+ params_dict.update(kwargs)
609
+ response = await self._get(
610
+ f"/projects/{project_id}/data_collections/{data_collection_id}/images/",
611
+ params=params_dict,
612
+ )
613
+ return response.json()
614
+
615
+ async def paginate_images(
616
+ self,
617
+ project_id: int,
618
+ data_collection_id: int,
619
+ page_size: int,
620
+ params: ListParams | None = None,
621
+ **kwargs,
622
+ ) -> AsyncGenerator[dict, None]:
623
+ """Paginate through images in a data collection with optional filtering.
624
+
625
+ This method returns an async generator that yields images one at a time,
626
+ automatically handling pagination in the background.
627
+
628
+ Args:
629
+ project_id: The ID of the project containing the data collection.
630
+ data_collection_id: The ID of the data collection containing the images.
631
+ page_size: The number of images to fetch per page.
632
+ params: Optional ListParams object containing filtering parameters (excluding offset and limit).
633
+ **kwargs: Alternative way to provide filtering parameters.
634
+
635
+ Yields:
636
+ dict: Image objects matching the filter criteria, one at a time.
637
+ """
638
+ params_dict = (
639
+ params.model_dump(exclude_none=True, exclude={"offset", "limit"})
640
+ if params
641
+ else {}
642
+ )
643
+ params_dict.update(kwargs)
644
+ url = f"/projects/{project_id}/data_collections/{data_collection_id}/images/"
645
+ async for item in self._paginate(url, page_size, params=params_dict):
646
+ yield item
647
+
648
+ async def get_image(
649
+ self,
650
+ project_id: int,
651
+ data_collection_id: int,
652
+ image_id: int,
653
+ ) -> dict:
654
+ """Retrieve a specific image by its ID.
655
+
656
+ Args:
657
+ project_id: The ID of the project containing the data collection.
658
+ data_collection_id: The ID of the data collection containing the image.
659
+ image_id: The ID of the image to retrieve.
660
+
661
+ Returns:
662
+ dict: The image object with its details.
663
+ """
664
+ response = await self._get(
665
+ f"/projects/{project_id}/data_collections/{data_collection_id}/images/{image_id}"
666
+ )
667
+ return response.json()
668
+
669
+ async def get_image_metadata(
670
+ self, project_id: int, data_collection_id: int, image_id: int
671
+ ) -> dict:
672
+ """
673
+ Retrieve metadata for a specific image by its ID.
674
+
675
+ Args:
676
+ project_id: The ID of the project containing the data collection.
677
+ data_collection_id: The ID of the data collection containing the image.
678
+ image_id: The ID of the image to retrieve metadata for.
679
+
680
+ Returns:
681
+ dict: The image metadata object with its details.
682
+ """
683
+ response = await self._get(
684
+ f"/projects/{project_id}/data_collections/{data_collection_id}/images/{image_id}/metadata"
685
+ )
686
+ return response.json()
687
+
688
+ async def update_image(
689
+ self,
690
+ project_id: int,
691
+ data_collection_id: int,
692
+ image_id: int,
693
+ update_input: ImageUpdateInput,
694
+ ) -> dict:
695
+ """Update an existing image with new values.
696
+
697
+ Args:
698
+ project_id: The ID of the project containing the data collection.
699
+ data_collection_id: The ID of the data collection containing the image.
700
+ image_id: The ID of the image to update.
701
+ update_input: ImageUpdateInput object containing the fields to update.
702
+
703
+ Returns:
704
+ dict: The updated image object.
705
+ """
706
+
707
+ response = await self._put(
708
+ f"/projects/{project_id}/data_collections/{data_collection_id}/images/{image_id}",
709
+ json=update_input.model_dump(mode="json", exclude_none=True),
710
+ )
711
+ return response.json()
712
+
713
+ async def delete_image(
714
+ self,
715
+ project_id: int,
716
+ data_collection_id: int,
717
+ image_id: int,
718
+ ) -> dict:
719
+ """Delete a specific image by its ID.
720
+
721
+ Args:
722
+ project_id: The ID of the project containing the data collection.
723
+ data_collection_id: The ID of the data collection containing the image.
724
+ image_id: The ID of the image to delete.
725
+
726
+ Returns:
727
+ dict: The response confirming deletion.
728
+ """
729
+ response = await self._delete(
730
+ f"/projects/{project_id}/data_collections/{data_collection_id}/images/{image_id}"
731
+ )
732
+ return response.json()
733
+
734
+ async def get_rasters(
735
+ self,
736
+ project_id: int,
737
+ data_collection_id: int,
738
+ params: ListParams | None = None,
739
+ **kwargs,
740
+ ) -> dict:
741
+ """Retrieve rasters from a data collection with optional filtering.
742
+
743
+ Args:
744
+ project_id: The ID of the project containing the data collection.
745
+ data_collection_id: The ID of the data collection containing the rasters.
746
+ params: Optional ListParams object containing filtering parameters.
747
+ **kwargs: Alternative way to provide filtering parameters.
748
+
749
+ Returns:
750
+ dict: A list of raster objects matching the filter criteria.
751
+ """
752
+ params_dict = params.model_dump(exclude_none=True) if params else {}
753
+ params_dict.update(kwargs)
754
+ response = await self._get(
755
+ f"/projects/{project_id}/data_collections/{data_collection_id}/rasters/",
756
+ params=params_dict,
757
+ )
758
+ return response.json()
759
+
760
+ async def paginate_rasters(
761
+ self,
762
+ project_id: int,
763
+ data_collection_id: int,
764
+ page_size: int,
765
+ params: ListParams | None = None,
766
+ **kwargs,
767
+ ) -> AsyncGenerator[dict, None]:
768
+ """Paginate through rasters in a data collection with optional filtering.
769
+
770
+ This method returns an async generator that yields rasters one at a time,
771
+ automatically handling pagination in the background.
772
+
773
+ Args:
774
+ project_id: The ID of the project containing the data collection.
775
+ data_collection_id: The ID of the data collection containing the rasters.
776
+ page_size: The number of rasters to fetch per page.
777
+ params: Optional ListParams object containing filtering parameters (excluding offset and limit).
778
+ **kwargs: Alternative way to provide filtering parameters.
779
+
780
+ Yields:
781
+ dict: Raster objects matching the filter criteria, one at a time.
782
+ """
783
+ params_dict = (
784
+ params.model_dump(exclude_none=True, exclude={"offset", "limit"})
785
+ if params
786
+ else {}
787
+ )
788
+ params_dict.update(kwargs)
789
+ url = f"/projects/{project_id}/data_collections/{data_collection_id}/rasters/"
790
+ async for item in self._paginate(url, page_size, params=params_dict):
791
+ yield item
792
+
793
+ async def get_raster(
794
+ self,
795
+ project_id: int,
796
+ data_collection_id: int,
797
+ raster_id: int,
798
+ ) -> dict:
799
+ """Retrieve a specific raster by its ID.
800
+
801
+ Args:
802
+ project_id: The ID of the project containing the data collection.
803
+ data_collection_id: The ID of the data collection containing the raster.
804
+ raster_id: The ID of the raster to retrieve.
805
+
806
+ Returns:
807
+ dict: The raster object with its details.
808
+ """
809
+ response = await self._get(
810
+ f"/projects/{project_id}/data_collections/{data_collection_id}/rasters/{raster_id}"
811
+ )
812
+ return response.json()
813
+
814
+ async def update_raster(
815
+ self,
816
+ project_id: int,
817
+ data_collection_id: int,
818
+ raster_id: int,
819
+ update_input: RasterUpdateInput,
820
+ ) -> dict:
821
+ """Update an existing raster with new values.
822
+
823
+ Args:
824
+ project_id: The ID of the project containing the data collection.
825
+ data_collection_id: The ID of the data collection containing the raster.
826
+ raster_id: The ID of the raster to update.
827
+ update_input: RasterUpdateInput object containing the fields to update.
828
+
829
+ Returns:
830
+ dict: The updated raster object.
831
+
832
+ """
833
+ response = await self._put(
834
+ f"/projects/{project_id}/data_collections/{data_collection_id}/rasters/{raster_id}",
835
+ json=update_input.model_dump(mode="json", exclude_none=True),
836
+ )
837
+ return response.json()
838
+
839
+ async def delete_raster(
840
+ self,
841
+ project_id: int,
842
+ data_collection_id: int,
843
+ raster_id: int,
844
+ ) -> dict:
845
+ """Delete a specific raster by its ID.
846
+
847
+ Args:
848
+ project_id: The ID of the project containing the data collection.
849
+ data_collection_id: The ID of the data collection containing the raster.
850
+ raster_id: The ID of the raster to delete.
851
+
852
+ Returns:
853
+ dict: The response confirming deletion.
854
+ """
855
+ response = await self._delete(
856
+ f"/projects/{project_id}/data_collections/{data_collection_id}/rasters/{raster_id}"
857
+ )
858
+ return response.json()
859
+
860
+ async def get_upload_jobs(
861
+ self,
862
+ project_id: int,
863
+ data_collection_id: int,
864
+ params: ListParams | None = None,
865
+ **kwargs,
866
+ ) -> list[dict]:
867
+ """Retrieve upload jobs for a data collection with optional filtering.
868
+
869
+ Args:
870
+ project_id: The ID of the project containing the data collection.
871
+ data_collection_id: The ID of the data collection to list upload jobs for.
872
+ params: Optional ListParams object containing filtering parameters.
873
+ **kwargs: Alternative way to provide filtering parameters. Ignored if params is provided.
874
+
875
+ Returns:
876
+ list[dict]: A list of upload job objects matching the filter criteria.
877
+ """
878
+ if params and kwargs:
879
+ logger.warning("Ignoring kwargs when params is provided")
880
+ params_dict = (
881
+ params.model_dump(exclude_none=True)
882
+ if params
883
+ else ListParams.model_validate(kwargs).model_dump(exclude_none=True)
884
+ )
885
+ response = await self._get(
886
+ f"/projects/{project_id}/data_collections/{data_collection_id}/upload_jobs/",
887
+ params=params_dict,
888
+ )
889
+ return response.json()
890
+
891
+ async def _create_upload_jobs(
892
+ self,
893
+ project_id: int,
894
+ data_collection_id: int,
895
+ multipart: bool,
896
+ files: list[dict],
897
+ ) -> list[dict]:
898
+ """Internal helper to create upload job objects in the API.
899
+
900
+ Args:
901
+ project_id: The ID of the project containing the data collection.
902
+ data_collection_id: The ID of the data collection to create upload jobs for.
903
+ multipart: If True, create multipart upload jobs for large files.
904
+ files: List of file objects containing metadata for the upload jobs.
905
+
906
+ Returns:
907
+ list[dict]: The created upload job objects.
908
+ """
909
+ url = (
910
+ f"/projects/{project_id}/data_collections/{data_collection_id}/upload_jobs/"
911
+ )
912
+ if multipart:
913
+ url += "multipart"
914
+ body = {"files": files}
915
+ response = await self._post(url, json=body)
916
+ return response.json()
917
+
918
+ def _create_support_file_file(
919
+ self,
920
+ file_path: Path,
921
+ ) -> dict:
922
+ """Create a file object for a support file to be included in an upload job.
923
+
924
+ Args:
925
+ file_path: Path to the support file.
926
+
927
+ Returns:
928
+ dict: A file object containing the file name and MD5 hash.
929
+
930
+ Raises:
931
+ FileNotFoundError: If the file does not exist.
932
+ """
933
+ if not file_path.exists():
934
+ raise FileNotFoundError(f"File {file_path} not found")
935
+ return {
936
+ "name": file_path.name,
937
+ "md5": calculate_md5_base64_from_file(file_path),
938
+ }
939
+
940
+ def _create_single_part_upload_job_from_file(
941
+ self,
942
+ file_path: Path,
943
+ support_files: list[Path] | None = None,
944
+ metadata: dict | None = None,
945
+ ) -> dict:
946
+ """Create a file object for a single-part upload job.
947
+
948
+ Args:
949
+ file_path: Path to the file to upload.
950
+ support_files: Optional list of support file paths to include with the upload.
951
+ metadata: Optional metadata to associate with the file.
952
+
953
+ Returns:
954
+ dict: A file object containing the file name, MD5 hash, and optional metadata and support files.
955
+ """
956
+ body: dict[str, Any] = {
957
+ "name": file_path.name,
958
+ "md5": calculate_md5_base64_from_file(file_path),
959
+ }
960
+ if metadata:
961
+ body["metadata"] = metadata
962
+ if support_files:
963
+ body["support_files"] = [
964
+ self._create_support_file_file(f) for f in support_files
965
+ ]
966
+ return body
967
+
968
+ def _create_multipart_upload_job_from_file(
969
+ self,
970
+ file_path: Path,
971
+ part_size: int,
972
+ support_files: list[Path] | None = None,
973
+ metadata: dict | None = None,
974
+ ) -> dict:
975
+ """Create a file object for a multipart upload job.
976
+
977
+ Args:
978
+ file_path: Path to the file to upload.
979
+ part_size: Size of each part in bytes.
980
+ support_files: Optional list of support file paths to include with the upload.
981
+ metadata: Optional metadata to associate with the file.
982
+
983
+ Returns:
984
+ dict: A file object containing the file name, parts information, and optional metadata and support files.
985
+ """
986
+ parts = []
987
+ for part_number, (content_length, md5, _) in enumerate(
988
+ iter_file_parts(file_path, part_size), start=1
989
+ ):
990
+ parts.append(
991
+ {
992
+ "part_number": part_number,
993
+ "md5": md5,
994
+ "content_length": content_length,
995
+ }
996
+ )
997
+ file_body = {
998
+ "name": file_path.name,
999
+ "parts": parts,
1000
+ }
1001
+ if metadata:
1002
+ file_body["metadata"] = metadata
1003
+ if support_files:
1004
+ file_body["support_files"] = [
1005
+ self._create_support_file_file(f) for f in support_files
1006
+ ]
1007
+ return file_body
1008
+
1009
+ async def _upload_singlepart_to_s3(
1010
+ self,
1011
+ upload_job: dict,
1012
+ file_path: Path,
1013
+ ):
1014
+ """Upload a file to S3 using a single part upload.
1015
+
1016
+ Args:
1017
+ upload_job: Upload job object containing the S3 URL and upload fields.
1018
+ file_path: Path to the file to upload.
1019
+
1020
+ Returns:
1021
+ None: This method returns None on success.
1022
+
1023
+ Raises:
1024
+ httpx.HTTPStatusError: If the upload fails.
1025
+ """
1026
+ response = await self._internal_client.post(
1027
+ upload_job["url"],
1028
+ files={"file": file_path.read_bytes()},
1029
+ data=upload_job["upload_fields"],
1030
+ )
1031
+ response.raise_for_status()
1032
+ return None
1033
+
1034
+ async def _upload_part_to_s3(
1035
+ self,
1036
+ part: dict,
1037
+ part_data: bytes,
1038
+ ):
1039
+ """Upload a part of a file to S3 as part of a multipart upload.
1040
+
1041
+ Args:
1042
+ part: Part object containing the S3 URL and headers.
1043
+ part_data: Binary data for this part of the file.
1044
+
1045
+ Returns:
1046
+ None: This method returns None on success.
1047
+
1048
+ Raises:
1049
+ httpx.HTTPStatusError: If the upload fails.
1050
+ """
1051
+ response = await self._internal_client.put(
1052
+ part["url"], content=part_data, headers=part["headers"]
1053
+ )
1054
+ response.raise_for_status()
1055
+ return None
1056
+
1057
+ async def _upload_multipart_to_s3(
1058
+ self,
1059
+ upload_job: dict,
1060
+ file_path: Path,
1061
+ multipart_part_size: int,
1062
+ ):
1063
+ """Upload all parts of a file to S3 using a multipart upload.
1064
+
1065
+ Args:
1066
+ upload_job: Upload job object containing the parts information.
1067
+ file_path: Path to the file to upload.
1068
+ multipart_part_size: Size of each part in bytes.
1069
+
1070
+ Returns:
1071
+ None: This method returns None on success.
1072
+ """
1073
+ parts = sorted(upload_job["upload_parts"], key=lambda p: p["part_number"])
1074
+ upload_iterator = zip(iter_file_parts(file_path, multipart_part_size), parts)
1075
+ await asyncio.gather(
1076
+ *[
1077
+ self._upload_part_to_s3(part, part_data)
1078
+ for (_, _, part_data), part in upload_iterator
1079
+ ]
1080
+ )
1081
+ return None
1082
+
1083
+ async def _upload_to_s3(
1084
+ self,
1085
+ file: Path,
1086
+ support_files: list[Path] | None,
1087
+ upload_job: dict,
1088
+ multipart: bool,
1089
+ multipart_part_size: int | None,
1090
+ ):
1091
+ """Upload a file and its support files to S3.
1092
+
1093
+ Args:
1094
+ file: Path to the main file to upload.
1095
+ support_files: Optional list of support file paths to upload with the main file.
1096
+ upload_job: Upload job object containing the upload information.
1097
+ multipart: If True, use multipart upload for the main file.
1098
+ multipart_part_size: Required size of each part in bytes when using multipart upload.
1099
+
1100
+ Returns:
1101
+ None: This method returns None on success.
1102
+
1103
+ Raises:
1104
+ AssertionError: If multipart is True but multipart_part_size is not provided,
1105
+ or if support_files are required but not provided.
1106
+ """
1107
+ logger.info(f"Uploading {file} to S3 with upload job {upload_job['id']}")
1108
+ if multipart:
1109
+ assert multipart_part_size, (
1110
+ "multipart_part_size must be provided for multipart upload"
1111
+ )
1112
+ await self._upload_multipart_to_s3(upload_job, file, multipart_part_size)
1113
+ else:
1114
+ await self._upload_singlepart_to_s3(upload_job, file)
1115
+ if upload_job.get("support_files"):
1116
+ assert support_files, "Support files must be provided for upload job"
1117
+ # Sort the support file by name
1118
+ support_files = sorted(support_files, key=lambda f: f.name)
1119
+ upload_job_support_files = sorted(
1120
+ upload_job["support_files"], key=lambda f: f["name"]
1121
+ )
1122
+ await asyncio.gather(
1123
+ *[
1124
+ self._upload_singlepart_to_s3(uj_sp, sp_path)
1125
+ for uj_sp, sp_path in zip(upload_job_support_files, support_files)
1126
+ ]
1127
+ )
1128
+ logger.info(f"Upload job {upload_job['id']} with {file} completed upload")
1129
+ return None
1130
+
1131
+ async def _upload_file_finished(
1132
+ self,
1133
+ project_id: int,
1134
+ data_collection_id: int,
1135
+ upload_job_id: int,
1136
+ ) -> dict:
1137
+ """Signal to the API that a file upload has completed.
1138
+
1139
+ Args:
1140
+ project_id: The ID of the project containing the data collection.
1141
+ data_collection_id: The ID of the data collection containing the upload job.
1142
+ upload_job_id: The ID of the upload job to mark as finished.
1143
+
1144
+ Returns:
1145
+ dict: The response containing job information for the validation process.
1146
+ """
1147
+ response = await self._put(
1148
+ f"/projects/{project_id}/data_collections/{data_collection_id}/upload_jobs/{upload_job_id}/uploadFinished"
1149
+ )
1150
+ return response.json()
1151
+
1152
+ async def _multiple_upload_file_finished(
1153
+ self,
1154
+ project_id: int,
1155
+ data_collection_id: int,
1156
+ upload_job_ids: list[int],
1157
+ ) -> dict:
1158
+ """Signal to the API that multiple file uploads have completed.
1159
+
1160
+ Args:
1161
+ project_id: The ID of the project containing the data collection.
1162
+ data_collection_id: The ID of the data collection containing the upload jobs.
1163
+ upload_job_ids: List of upload job IDs to mark as finished.
1164
+
1165
+ Returns:
1166
+ dict: The response containing group job information and updated upload jobs.
1167
+ """
1168
+ response = await self._put(
1169
+ f"/projects/{project_id}/data_collections/{data_collection_id}/upload_jobs/multiple_uploadFinished",
1170
+ json={"job_ids": upload_job_ids},
1171
+ )
1172
+ return response.json()
1173
+
1174
+ async def _wait_for_multiple_upload_jobs(
1175
+ self,
1176
+ project_id: int,
1177
+ data_collection_id: int,
1178
+ group_job_id: int,
1179
+ upload_job_ids: list[int],
1180
+ ) -> tuple[list[dict], list[PixelUploadJobError]]:
1181
+ """Wait for multiple upload jobs to complete validation and processing.
1182
+
1183
+ Args:
1184
+ project_id: The ID of the project containing the data collection.
1185
+ data_collection_id: The ID of the data collection containing the upload jobs.
1186
+ group_job_id: The ID of the group job managing the upload jobs.
1187
+ upload_job_ids: List of upload job IDs to wait for.
1188
+
1189
+ Returns:
1190
+ tuple: A tuple containing:
1191
+ - list[dict]: List of successfully completed upload jobs.
1192
+ - list[PixelUploadJobError]: List of errors for failed upload jobs.
1193
+ """
1194
+ _ = await self.wait_for_group_job(group_job_id=group_job_id)
1195
+ upload_jobs = await self.get_upload_jobs(
1196
+ project_id,
1197
+ data_collection_id,
1198
+ ids=upload_job_ids,
1199
+ limit=len(upload_job_ids),
1200
+ )
1201
+ while any(
1202
+ uj["status"] in ("lobby", "validating", "submitted", "validated")
1203
+ for uj in upload_jobs
1204
+ ):
1205
+ upload_jobs = await self.get_upload_jobs(
1206
+ project_id,
1207
+ data_collection_id,
1208
+ ids=upload_job_ids,
1209
+ limit=len(upload_job_ids),
1210
+ )
1211
+ await asyncio.sleep(1)
1212
+ # Collect any errors
1213
+ errors = []
1214
+ finished_upload_jobs = []
1215
+ for uj in upload_jobs:
1216
+ try:
1217
+ if uj["status"] != "validated_and_moved":
1218
+ raise PixelUploadJobError(
1219
+ job_id=uj["id"], status=uj["status"], detail=uj["detail"]
1220
+ )
1221
+ except PixelUploadJobError as e:
1222
+ errors.append(e)
1223
+ else:
1224
+ finished_upload_jobs.append(uj)
1225
+ return finished_upload_jobs, errors
1226
+
1227
+ async def _wait_for_upload_job(
1228
+ self, project_id: int, data_collection_id: int, upload_job_id: int, job_id: int
1229
+ ) -> dict:
1230
+ """Wait for a single upload job to complete validation and processing.
1231
+
1232
+ Args:
1233
+ project_id: The ID of the project containing the data collection.
1234
+ data_collection_id: The ID of the data collection containing the upload job.
1235
+ upload_job_id: The ID of the upload job to wait for.
1236
+ job_id: The ID of the job managing the upload job validation.
1237
+
1238
+ Returns:
1239
+ dict: The completed upload job object.
1240
+
1241
+ Raises:
1242
+ PixelUploadJobError: If the upload job fails validation or processing.
1243
+ """
1244
+ await self.wait_for_job(job_id)
1245
+ upload_jobs = await self.get_upload_jobs(
1246
+ project_id, data_collection_id, ids=[upload_job_id], limit=1
1247
+ )
1248
+ upload_job = upload_jobs[0]
1249
+ if upload_job["status"] == "validated_and_moved":
1250
+ return upload_job
1251
+ if upload_job["status"] != "validated_and_moved":
1252
+ raise PixelUploadJobError(
1253
+ job_id=upload_job_id,
1254
+ status=upload_job["status"],
1255
+ detail=upload_job["detail"],
1256
+ )
1257
+ return upload_job
1258
+
1259
+ async def _resources_from_upload_jobs(
1260
+ self, project_id: int, data_collection_id: int, upload_jobs: list[dict]
1261
+ ) -> list[dict]:
1262
+ """Retrieve the created resources (images or rasters) from completed upload jobs.
1263
+
1264
+ Args:
1265
+ project_id: The ID of the project containing the data collection.
1266
+ data_collection_id: The ID of the data collection containing the resources.
1267
+ upload_jobs: List of completed upload job objects.
1268
+
1269
+ Returns:
1270
+ list[dict]: List of resource objects (images or rasters) created from the upload jobs.
1271
+ """
1272
+ # Chunk up the resources ids
1273
+ chunk_size = 50
1274
+ image_resource_ids: list[int] = []
1275
+ raster_resource_ids: list[int] = []
1276
+ image_resources: list[dict] = []
1277
+ raster_resources: list[dict] = []
1278
+ for upload_job in upload_jobs:
1279
+ if upload_job["result"]["resource_name"] == "image":
1280
+ image_resource_ids.append(upload_job["result"]["resource_id"])
1281
+ if upload_job["result"]["resource_name"] == "raster":
1282
+ raster_resource_ids.append(upload_job["result"]["resource_id"])
1283
+ for chunk in chunks(image_resource_ids, chunk_size):
1284
+ image_resources.extend(
1285
+ await self.get_images(
1286
+ project_id,
1287
+ data_collection_id,
1288
+ params=ListParams(ids=chunk, limit=len(chunk)),
1289
+ )
1290
+ )
1291
+ for chunk in chunks(raster_resource_ids, chunk_size):
1292
+ raster_resources.extend(
1293
+ await self.get_rasters(
1294
+ project_id,
1295
+ data_collection_id,
1296
+ params=ListParams(ids=chunk, limit=len(chunk)),
1297
+ )
1298
+ )
1299
+ resources = image_resources + raster_resources
1300
+ return resources
1301
+
1302
+ async def _resource_from_upload_job(
1303
+ self, project_id: int, data_collection_id: int, upload_job: dict
1304
+ ) -> dict:
1305
+ """Retrieve the created resource (image or raster) from a completed upload job.
1306
+
1307
+ Args:
1308
+ project_id: The ID of the project containing the data collection.
1309
+ data_collection_id: The ID of the data collection containing the resource.
1310
+ upload_job: The completed upload job object.
1311
+
1312
+ Returns:
1313
+ dict: The resource object (image or raster) created from the upload job.
1314
+
1315
+ Raises:
1316
+ ValueError: If the resource type in the upload job result is unknown.
1317
+ """
1318
+ if upload_job["result"]["resource_name"] == "image":
1319
+ return await self.get_image(
1320
+ project_id, data_collection_id, upload_job["result"]["resource_id"]
1321
+ )
1322
+ if upload_job["result"]["resource_name"] == "raster":
1323
+ return await self.get_raster(
1324
+ project_id, data_collection_id, upload_job["result"]["resource_id"]
1325
+ )
1326
+ raise ValueError(
1327
+ f"Unknown resource name in upload job result: {upload_job['result']}"
1328
+ )
1329
+
1330
+ async def _upload_multiple_files(
1331
+ self,
1332
+ project_id: int,
1333
+ data_collection_id: int,
1334
+ files: list[PixelUploadFile],
1335
+ multipart: bool,
1336
+ multipart_part_size: int | None,
1337
+ raise_on_error: bool = False,
1338
+ ) -> tuple[list[dict], list[PixelUploadJobError]]:
1339
+ """Upload multiple files to a data collection.
1340
+
1341
+ Args:
1342
+ project_id: The ID of the project containing the data collection.
1343
+ data_collection_id: The ID of the data collection to upload to.
1344
+ files: List of PixelUploadFile objects containing the files to upload.
1345
+ multipart: If True, use multipart upload for large files.
1346
+ multipart_part_size: Required size of each part in bytes when using multipart upload.
1347
+ raise_on_error: If True, raise a PixelMultipleUploadJobError if any uploads fail.
1348
+
1349
+ Returns:
1350
+ tuple: A tuple containing:
1351
+ - list[dict]: List of created resource objects (images or rasters).
1352
+ - list[PixelUploadJobError]: List of errors for failed uploads.
1353
+
1354
+ Raises:
1355
+ ValueError: If any files have duplicate names.
1356
+ PixelMultipleUploadJobError: If raise_on_error is True and any uploads fail.
1357
+ """
1358
+
1359
+ # Chunk the operation into 200 files at a time (maximum for API)
1360
+ all_resources: list[dict] = []
1361
+ all_errors: list[PixelUploadJobError] = []
1362
+
1363
+ create_body_func = (
1364
+ partial(
1365
+ self._create_multipart_upload_job_from_file,
1366
+ part_size=multipart_part_size, # type: ignore
1367
+ )
1368
+ if multipart
1369
+ else self._create_single_part_upload_job_from_file
1370
+ )
1371
+ # Assert unique file names
1372
+ file_names = [f.file.name for f in files]
1373
+ if len(file_names) != len(set(file_names)):
1374
+ raise ValueError("All files must have unique names")
1375
+ for files_chunk in chunks(files, 200):
1376
+ logger.info("Uploading chunk of %d files", len(files_chunk))
1377
+ file_bodies = [
1378
+ create_body_func(
1379
+ file.file,
1380
+ support_files=file.support_files,
1381
+ metadata=file.metadata.model_dump(mode="json", exclude_none=True)
1382
+ if file.metadata
1383
+ else None,
1384
+ )
1385
+ for file in files_chunk
1386
+ ]
1387
+ upload_jobs = await self._create_upload_jobs(
1388
+ project_id, data_collection_id, multipart, file_bodies
1389
+ )
1390
+ # sort the upload jobs by the file name
1391
+ upload_jobs = sorted(upload_jobs, key=lambda uj: uj["name"])
1392
+ files = sorted(files, key=lambda f: f.file.name)
1393
+ await asyncio.gather(
1394
+ *[
1395
+ self._upload_to_s3(
1396
+ file.file,
1397
+ file.support_files,
1398
+ upload_job,
1399
+ multipart,
1400
+ multipart_part_size,
1401
+ )
1402
+ for upload_job, file in zip(upload_jobs, files)
1403
+ ]
1404
+ )
1405
+ upload_finished = await self._multiple_upload_file_finished(
1406
+ project_id, data_collection_id, [uj["id"] for uj in upload_jobs]
1407
+ )
1408
+ group_job = upload_finished["group_job"]
1409
+ upload_jobs = upload_finished["upload_jobs"]
1410
+ upload_jobs, errors = await self._wait_for_multiple_upload_jobs(
1411
+ project_id,
1412
+ data_collection_id,
1413
+ group_job["group_id"],
1414
+ [uj["id"] for uj in upload_jobs],
1415
+ )
1416
+ resources = await self._resources_from_upload_jobs(
1417
+ project_id, data_collection_id, upload_jobs
1418
+ )
1419
+ all_resources.extend(resources)
1420
+ all_errors.extend(errors)
1421
+
1422
+ if raise_on_error and all_errors:
1423
+ raise PixelMultipleUploadJobError(errors)
1424
+ return all_resources, all_errors
1425
+
1426
+ async def _upload_file(
1427
+ self,
1428
+ project_id: int,
1429
+ data_collection_id: int,
1430
+ file_path: Path,
1431
+ support_files: list[Path] | None = None,
1432
+ metadata: dict | None = None,
1433
+ multipart: bool = False,
1434
+ multipart_part_size: int | None = None,
1435
+ ) -> dict:
1436
+ """Upload a single file to a data collection.
1437
+
1438
+ Args:
1439
+ project_id: The ID of the project containing the data collection.
1440
+ data_collection_id: The ID of the data collection to upload to.
1441
+ file_path: Path to the file to upload.
1442
+ support_files: Optional list of support file paths to upload with the file.
1443
+ metadata: Optional dictionary of metadata to associate with the file.
1444
+ multipart: If True, use multipart upload for large files.
1445
+ multipart_part_size: Required size of each part in bytes when using multipart upload.
1446
+
1447
+ Returns:
1448
+ dict: The created resource object (image or raster).
1449
+
1450
+ Raises:
1451
+ FileNotFoundError: If the file does not exist.
1452
+ ValueError: If multipart is True but multipart_part_size is not provided.
1453
+ PixelUploadJobError: If the upload job fails validation or processing.
1454
+ """
1455
+ if not file_path.exists():
1456
+ raise FileNotFoundError(f"File {file_path} not found")
1457
+ if multipart and not multipart_part_size:
1458
+ raise ValueError(
1459
+ "multipart_part_size must be provided for multipart upload"
1460
+ )
1461
+ if multipart:
1462
+ assert multipart_part_size
1463
+ file_body = self._create_multipart_upload_job_from_file(
1464
+ file_path,
1465
+ multipart_part_size,
1466
+ support_files=support_files,
1467
+ metadata=metadata,
1468
+ )
1469
+ else:
1470
+ file_body = self._create_single_part_upload_job_from_file(
1471
+ file_path,
1472
+ support_files=support_files,
1473
+ metadata=metadata,
1474
+ )
1475
+ upload_jobs = await self._create_upload_jobs(
1476
+ project_id, data_collection_id, multipart, [file_body]
1477
+ )
1478
+ upload_job = upload_jobs[0]
1479
+ await self._upload_to_s3(
1480
+ file_path,
1481
+ support_files,
1482
+ upload_job,
1483
+ multipart,
1484
+ multipart_part_size,
1485
+ )
1486
+ upload_job_finished = await self._upload_file_finished(
1487
+ project_id, data_collection_id, upload_job["id"]
1488
+ )
1489
+ job = upload_job_finished["job"]
1490
+ upload_job = await self._wait_for_upload_job(
1491
+ project_id, data_collection_id, upload_job["id"], job["job_id"]
1492
+ )
1493
+ return await self._resource_from_upload_job(
1494
+ project_id, data_collection_id, upload_job
1495
+ )
1496
+
1497
+ async def upload_image(
1498
+ self,
1499
+ project_id: int,
1500
+ data_collection_id: int,
1501
+ file_path: Path,
1502
+ metadata: dict | None = None,
1503
+ support_files: list[Path] | None = None,
1504
+ multipart: bool = False,
1505
+ multipart_part_size: int | None = None,
1506
+ ) -> dict:
1507
+ """Upload an image file to an image data collection.
1508
+
1509
+ Args:
1510
+ project_id: The ID of the project containing the data collection.
1511
+ data_collection_id: The ID of the image data collection to upload to.
1512
+ file_path: Path to the image file to upload.
1513
+ metadata: Optional dictionary of metadata to associate with the image.
1514
+ support_files: Optional list of support file paths to upload with the image.
1515
+ multipart: If True, use multipart upload for large files.
1516
+ multipart_part_size: Required size of each part in bytes when using multipart upload.
1517
+
1518
+ Returns:
1519
+ dict: The created image object.
1520
+
1521
+ Raises:
1522
+ ValueError: If the data collection is not an image data collection.
1523
+ FileNotFoundError: If the file does not exist.
1524
+ ValueError: If multipart is True but multipart_part_size is not provided.
1525
+ """
1526
+ dc = await self.get_data_collection(project_id, data_collection_id)
1527
+ if dc["data_collection_type"] != "image":
1528
+ raise ValueError("Data collection is not an image data collection")
1529
+ return await self._upload_file(
1530
+ project_id,
1531
+ data_collection_id,
1532
+ file_path,
1533
+ support_files=support_files,
1534
+ metadata=metadata,
1535
+ multipart=multipart,
1536
+ multipart_part_size=multipart_part_size,
1537
+ )
1538
+
1539
+ async def upload_multiple_images(
1540
+ self,
1541
+ project_id: int,
1542
+ data_collection_id: int,
1543
+ files: list[PixelUploadFile],
1544
+ multipart: bool = False,
1545
+ multipart_part_size: int | None = None,
1546
+ ) -> tuple[list[dict], list[PixelUploadJobError]]:
1547
+ """Upload multiple image files to an image data collection.
1548
+
1549
+ Args:
1550
+ project_id: The ID of the project containing the data collection.
1551
+ data_collection_id: The ID of the image data collection to upload to.
1552
+ files: List of PixelUploadFile objects containing the files to upload.
1553
+ multipart: If True, use multipart upload for large files.
1554
+ multipart_part_size: Required size of each part in bytes when using multipart upload.
1555
+
1556
+ Returns:
1557
+ tuple: A tuple containing:
1558
+ - list[dict]: List of created image objects.
1559
+ - list[PixelUploadJobError]: List of errors that occurred during upload.
1560
+
1561
+ Raises:
1562
+ ValueError: If the data collection is not an image data collection.
1563
+ ValueError: If any files have duplicate names.
1564
+ ValueError: If multipart is True but multipart_part_size is not provided.
1565
+ """
1566
+ dc = await self.get_data_collection(project_id, data_collection_id)
1567
+ if dc["data_collection_type"] != "image":
1568
+ raise ValueError("Data collection is not an image data collection")
1569
+ return await self._upload_multiple_files(
1570
+ project_id,
1571
+ data_collection_id,
1572
+ files,
1573
+ multipart,
1574
+ multipart_part_size,
1575
+ )
1576
+
1577
+ async def upload_multiple_rasters(
1578
+ self,
1579
+ project_id: int,
1580
+ data_collection_id: int,
1581
+ files: list[PixelUploadFile],
1582
+ multipart: bool = False,
1583
+ multipart_part_size: int | None = None,
1584
+ ) -> tuple[list[dict], list[PixelUploadJobError]]:
1585
+ """Upload multiple raster files to a raster data collection.
1586
+
1587
+ Args:
1588
+ project_id: The ID of the project containing the data collection.
1589
+ data_collection_id: The ID of the raster data collection to upload to.
1590
+ files: List of PixelUploadFile objects containing the files to upload.
1591
+ multipart: If True, use multipart upload for large files.
1592
+ multipart_part_size: Required size of each part in bytes when using multipart upload.
1593
+
1594
+ Returns:
1595
+ tuple: A tuple containing:
1596
+ - list[dict]: List of created raster objects.
1597
+ - list[PixelUploadJobError]: List of errors that occurred during upload.
1598
+
1599
+ Raises:
1600
+ ValueError: If the data collection is not a raster data collection.
1601
+ ValueError: If any files have duplicate names.
1602
+ ValueError: If multipart is True but multipart_part_size is not provided.
1603
+ """
1604
+ dc = await self.get_data_collection(project_id, data_collection_id)
1605
+ if dc["data_collection_type"] not in ("raster", "RGB", "DTM", "DSM"):
1606
+ raise ValueError("Data collection is not a raster data collection")
1607
+ return await self._upload_multiple_files(
1608
+ project_id,
1609
+ data_collection_id,
1610
+ files,
1611
+ multipart,
1612
+ multipart_part_size,
1613
+ )
1614
+
1615
+ async def upload_raster(
1616
+ self,
1617
+ project_id: int,
1618
+ data_collection_id: int,
1619
+ file_path: Path,
1620
+ support_files: list[Path] | None = None,
1621
+ multipart: bool = False,
1622
+ multipart_part_size: int | None = None,
1623
+ ) -> dict:
1624
+ """Upload a raster file to a raster data collection.
1625
+
1626
+ Args:
1627
+ project_id: The ID of the project containing the data collection.
1628
+ data_collection_id: The ID of the raster data collection to upload to.
1629
+ file_path: Path to the raster file to upload.
1630
+ support_files: Optional list of support file paths to upload with the raster.
1631
+ multipart: If True, use multipart upload for large files.
1632
+ multipart_part_size: Required size of each part in bytes when using multipart upload.
1633
+
1634
+ Returns:
1635
+ dict: The created raster object.
1636
+
1637
+ Raises:
1638
+ ValueError: If the data collection is not a raster data collection.
1639
+ FileNotFoundError: If the file does not exist.
1640
+ ValueError: If multipart is True but multipart_part_size is not provided.
1641
+ """
1642
+ dc = await self.get_data_collection(project_id, data_collection_id)
1643
+ if dc["data_collection_type"] not in ("raster", "RGB", "DTM", "DSM"):
1644
+ raise ValueError("Data collection is not a raster data collection")
1645
+ return await self._upload_file(
1646
+ project_id,
1647
+ data_collection_id,
1648
+ file_path,
1649
+ support_files=support_files,
1650
+ multipart=multipart,
1651
+ multipart_part_size=multipart_part_size,
1652
+ )
1653
+
1654
+ async def create_optimized_rasters(
1655
+ self,
1656
+ project_id: int,
1657
+ data_collection_id: int,
1658
+ raster_ids: list[int] | None,
1659
+ profile: str | None = None,
1660
+ nearblack: NearblackOptions | None = None,
1661
+ overview_resampling: OverviewResampling = "average",
1662
+ ) -> list[dict]:
1663
+ """Create optimized raster objects in the database.
1664
+
1665
+ This function creates optimized raster objects but does not run the actual optimization process.
1666
+ To run the optimization, use the run_optimize_rasters function with the returned optimized raster IDs.
1667
+
1668
+ Args:
1669
+ project_id: The ID of the project containing the data collection.
1670
+ data_collection_id: The ID of the data collection containing the rasters.
1671
+ raster_ids: Optional list of raster IDs to optimize. If None, all rasters in the collection will be optimized.
1672
+ profile: Optional profile name to use for optimization.
1673
+ nearblack: Optional NearblackOptions object for configuring the nearblack process.
1674
+ overview_resampling: The resampling method to use for creating overviews. Default is "average".
1675
+
1676
+ Returns:
1677
+ list[dict]: List of created optimized raster objects.
1678
+ """
1679
+ body: dict = {
1680
+ "creation_options": {
1681
+ "nearblack_options": nearblack.model_dump(
1682
+ exclude_none=True, mode="json"
1683
+ )
1684
+ if nearblack
1685
+ else NearblackOptions(enabled=False).model_dump(
1686
+ exclude_none=True, mode="json"
1687
+ ),
1688
+ "overview_resampling": overview_resampling,
1689
+ }
1690
+ }
1691
+ if raster_ids:
1692
+ body["raster_ids"] = raster_ids
1693
+ if profile:
1694
+ body["profile"] = profile
1695
+ response = await self._post(
1696
+ f"/projects/{project_id}/data_collections/{data_collection_id}/rasters/optimized/",
1697
+ json=body,
1698
+ )
1699
+ return response.json()
1700
+
1701
+ async def run_optimize_rasters(
1702
+ self,
1703
+ project_id: int,
1704
+ data_collection_id: int,
1705
+ optimize_raster_ids: list[int] | None,
1706
+ retry_failed: bool = False,
1707
+ ) -> dict:
1708
+ """Run the optimization process on optimized raster objects.
1709
+
1710
+ Args:
1711
+ project_id: The ID of the project containing the data collection.
1712
+ data_collection_id: The ID of the data collection containing the optimized rasters.
1713
+ optimize_raster_ids: Optional list of optimized raster IDs to process. If None, all optimized rasters in the collection will be processed.
1714
+ retry_failed: If True, retry previously failed optimization jobs.
1715
+
1716
+ Returns:
1717
+ dict: The group job object representing the optimization process.
1718
+ """
1719
+ body: dict = {"retry_failed": retry_failed}
1720
+ if optimize_raster_ids:
1721
+ body["optimized_raster_ids"] = optimize_raster_ids
1722
+ response = await self._post(
1723
+ f"/projects/{project_id}/data_collections/{data_collection_id}/rasters/optimized/run",
1724
+ json=body,
1725
+ )
1726
+ response_json = response.json()
1727
+
1728
+ job = await self.wait_for_group_job(response_json["group_job"]["group_id"])
1729
+ return job
1730
+
1731
+ async def get_job(
1732
+ self,
1733
+ job_id: int,
1734
+ ) -> dict:
1735
+ """Retrieve information about a specific job.
1736
+
1737
+ Args:
1738
+ job_id: The ID of the job to retrieve.
1739
+
1740
+ Returns:
1741
+ dict: The job object with its details.
1742
+ """
1743
+ response = await self._get(f"/jobs/{job_id}")
1744
+ return response.json()
1745
+
1746
+ async def get_job_group(
1747
+ self,
1748
+ job_id: int,
1749
+ ) -> dict:
1750
+ """Retrieve information about a specific job group.
1751
+
1752
+ Args:
1753
+ job_id: The ID of the job group to retrieve.
1754
+
1755
+ Returns:
1756
+ dict: The job group object with its details.
1757
+ """
1758
+ response = await self._get(f"/jobs/groups/{job_id}")
1759
+ return response.json()
1760
+
1761
+ async def wait_for_job(
1762
+ self,
1763
+ job_id: int,
1764
+ timeout: int = 600,
1765
+ ) -> dict:
1766
+ """Wait for a job to complete, polling its status at regular intervals.
1767
+
1768
+ Args:
1769
+ job_id: The ID of the job to wait for.
1770
+ timeout: Maximum time to wait in seconds before raising a TimeoutError. Default is 600 seconds (10 minutes).
1771
+
1772
+ Returns:
1773
+ dict: The completed job object.
1774
+
1775
+ Raises:
1776
+ TimeoutError: If the job does not complete within the specified timeout period.
1777
+ """
1778
+ job = await self.get_job(job_id)
1779
+ with silence_logger(logging.getLogger("httpx")):
1780
+ while not job["completed"]:
1781
+ job = await self.get_job(job_id)
1782
+ job_name = job["name"] or "unnamed"
1783
+ logger.info(f"Job {job_name} {job_id} status: {job['status']}")
1784
+ await asyncio.sleep(3)
1785
+ timeout -= 5
1786
+ if timeout <= 0:
1787
+ raise TimeoutError("Timed out waiting for job")
1788
+ logger.info(f"Job {job_id} finished with status {job['status']}")
1789
+ return job
1790
+
1791
+ async def wait_for_group_job(
1792
+ self,
1793
+ group_job_id: int,
1794
+ timeout: int = 1200,
1795
+ ) -> dict:
1796
+ """Wait for a group job to complete, polling its status at regular intervals.
1797
+
1798
+ A group job consists of multiple individual jobs. This method displays a progress bar
1799
+ showing the completion status of all jobs in the group.
1800
+
1801
+ Args:
1802
+ group_job_id: The ID of the group job to wait for.
1803
+ timeout: Maximum time to wait in seconds before raising a TimeoutError. Default is 1200 seconds (20 minutes).
1804
+
1805
+ Returns:
1806
+ dict: The completed group job object.
1807
+
1808
+ Raises:
1809
+ TimeoutError: If the group job does not complete within the specified timeout period.
1810
+ """
1811
+ job = await self.get_job_group(group_job_id)
1812
+ num_jobs = job["total_jobs"]
1813
+ with (
1814
+ silence_logger(logging.getLogger("httpx")),
1815
+ tqdm(total=num_jobs, desc=f"Running group job {group_job_id}") as pbar,
1816
+ ):
1817
+ while not job["completed"]:
1818
+ job = await self.get_job_group(group_job_id)
1819
+ num_failed = job["failed_count"]
1820
+ num_success = job["success_count"]
1821
+ num_finished = num_failed + num_success
1822
+ pbar.n = num_finished
1823
+ pbar.refresh()
1824
+ await asyncio.sleep(3)
1825
+ timeout -= 5
1826
+ if timeout <= 0:
1827
+ raise TimeoutError("Timed out waiting for optimize rasters job")
1828
+ logger.info(
1829
+ f"Group job {group_job_id} finished {job['total_jobs']} jobs, with {num_failed} failures and {num_success} successes"
1830
+ )
1831
+ return job
1832
+
1833
+ async def get_optimized_rasters(
1834
+ self,
1835
+ project_id: int,
1836
+ data_collection_id: int,
1837
+ params: ListParams | None = None,
1838
+ **kwargs,
1839
+ ) -> list[dict]:
1840
+ """Retrieve optimized rasters from a data collection with optional filtering.
1841
+
1842
+ Args:
1843
+ project_id: The ID of the project containing the data collection.
1844
+ data_collection_id: The ID of the data collection containing the optimized rasters.
1845
+ params: Optional ListParams object containing filtering parameters.
1846
+ **kwargs: Alternative way to provide filtering parameters.
1847
+
1848
+ Returns:
1849
+ list[dict]: A list of optimized raster objects matching the filter criteria.
1850
+ """
1851
+ params_dict = (
1852
+ params.model_dump(exclude_none=True)
1853
+ if params
1854
+ else ListParams.model_validate(kwargs).model_dump(exclude_none=True)
1855
+ )
1856
+ response = await self._get(
1857
+ f"/projects/{project_id}/data_collections/{data_collection_id}/rasters/optimized/",
1858
+ params=params_dict,
1859
+ )
1860
+ return response.json()
1861
+
1862
+ async def delete_optimized_rasters(
1863
+ self,
1864
+ project_id: int,
1865
+ data_collection_id: int,
1866
+ raster_id: int,
1867
+ profile: str | None = None,
1868
+ ) -> list[dict]:
1869
+ """Delete optimized rasters associated with a specific raster.
1870
+
1871
+ Args:
1872
+ project_id: The ID of the project containing the data collection.
1873
+ data_collection_id: The ID of the data collection containing the raster.
1874
+ raster_id: The ID of the raster whose optimized versions should be deleted.
1875
+ profile: Optional profile name to filter which optimized rasters to delete.
1876
+ If None, all optimized versions of the raster will be deleted.
1877
+
1878
+ Returns:
1879
+ list[dict]: A list of the deleted optimized raster objects.
1880
+ """
1881
+ params = {}
1882
+ if profile:
1883
+ params["profile"] = profile
1884
+ response = await self._delete(
1885
+ f"/projects/{project_id}/data_collections/{data_collection_id}/rasters/{raster_id}/optimized",
1886
+ params=params,
1887
+ )
1888
+ return response.json()
1889
+
1890
+ async def optimize_rasters(
1891
+ self,
1892
+ project_id: int,
1893
+ data_collection_id: int,
1894
+ raster_ids: list[int] | None = None,
1895
+ profile: str | None = None,
1896
+ nearblack: NearblackOptions | None = None,
1897
+ overview_resampling: OverviewResampling = "average",
1898
+ ) -> list[dict]:
1899
+ """Create and run optimization on rasters in a data collection.
1900
+
1901
+ This is a convenience method that combines create_optimized_rasters and run_optimize_rasters
1902
+ into a single operation.
1903
+
1904
+ Args:
1905
+ project_id: The ID of the project containing the data collection.
1906
+ data_collection_id: The ID of the data collection containing the rasters.
1907
+ raster_ids: Optional list of raster IDs to optimize. If None, all rasters in the collection will be optimized.
1908
+ profile: Optional profile name to use for optimization.
1909
+ nearblack: Optional NearblackOptions object for configuring the nearblack process.
1910
+ overview_resampling: The resampling method to use for creating overviews. Default is "average".
1911
+
1912
+ Returns:
1913
+ list[dict]: List of optimized raster objects after the optimization process has completed.
1914
+ """
1915
+ optimized_rasters = await self.create_optimized_rasters(
1916
+ project_id,
1917
+ data_collection_id,
1918
+ raster_ids,
1919
+ profile,
1920
+ nearblack=nearblack,
1921
+ overview_resampling=overview_resampling,
1922
+ )
1923
+ await self.run_optimize_rasters(
1924
+ project_id, data_collection_id, [r["id"] for r in optimized_rasters]
1925
+ )
1926
+ optimized_rasters = await self.get_optimized_rasters(
1927
+ project_id,
1928
+ data_collection_id,
1929
+ params=ListParams(
1930
+ ids=[r["id"] for r in optimized_rasters], limit=len(optimized_rasters)
1931
+ ),
1932
+ )
1933
+ return optimized_rasters
1934
+
1935
+ async def list_gdo_users(self) -> list[str]:
1936
+ """Retrieve a list of GDO (GeoData Online) users.
1937
+
1938
+ Returns:
1939
+ list[dict]: A list of GDO user names.
1940
+ """
1941
+ response = await self._get("/arcgis_services/gdo-users")
1942
+ return response.json()
1943
+
1944
+ async def create_arcgis_service(
1945
+ self,
1946
+ service_type: Literal["Feature", "Image"],
1947
+ create_input: ArcgisServiceCreateInput,
1948
+ ) -> dict:
1949
+ """Create a new ArcGIS service.
1950
+
1951
+ Args:
1952
+ service_type: The type of service to create, either "Feature" or "Image".
1953
+ create_input: ArcgisServiceCreateInput object containing the service configuration.
1954
+
1955
+ Returns:
1956
+ dict: The created ArcGIS service object.
1957
+
1958
+ Raises:
1959
+ AssertionError: If the create_input does not contain the appropriate service options for the specified service_type.
1960
+ """
1961
+ assert (
1962
+ getattr(
1963
+ create_input.options, f"{service_type.lower()}_service_options", None
1964
+ )
1965
+ is not None
1966
+ ), (
1967
+ f"Service options for {service_type} service must be provided in the create input"
1968
+ )
1969
+ response = await self._post(
1970
+ f"/arcgis_services/{service_type}/",
1971
+ json=create_input.model_dump(mode="json"),
1972
+ )
1973
+ return response.json()
1974
+
1975
+ async def list_arcgis_services(
1976
+ self,
1977
+ service_type: Literal["Feature", "Image"],
1978
+ params: ListParams | None = None,
1979
+ **kwargs,
1980
+ ) -> list[dict]:
1981
+ """List ArcGIS services of a specific type with optional filtering.
1982
+
1983
+ Args:
1984
+ service_type: The type of services to list, either "Feature" or "Image".
1985
+ params: Optional ListParams object containing filtering parameters.
1986
+ **kwargs: Alternative way to provide filtering parameters.
1987
+
1988
+ Returns:
1989
+ list[dict]: A list of ArcGIS service objects matching the filter criteria.
1990
+ """
1991
+ params_dict = (
1992
+ params.model_dump(exclude_none=True)
1993
+ if params
1994
+ else ListParams.model_validate(kwargs).model_dump(exclude_none=True)
1995
+ )
1996
+ response = await self._get(
1997
+ f"/arcgis_services/{service_type}/", params=params_dict
1998
+ )
1999
+ return response.json()
2000
+
2001
+ async def get_arcgis_service(
2002
+ self, service_type: Literal["Feature", "Image"], service_id: int
2003
+ ) -> dict:
2004
+ """Retrieve a specific ArcGIS service by its ID.
2005
+
2006
+ Args:
2007
+ service_type: The type of service, either "Feature" or "Image".
2008
+ service_id: The ID of the service to retrieve.
2009
+
2010
+ Returns:
2011
+ dict: The ArcGIS service object with its details.
2012
+ """
2013
+ response = await self._get(f"/arcgis_services/{service_type}/{service_id}")
2014
+ return response.json()
2015
+
2016
+ async def delete_arcgis_service(
2017
+ self, service_type: Literal["Feature", "Image"], service_id: int
2018
+ ) -> dict:
2019
+ """Delete a specific ArcGIS service by its ID.
2020
+
2021
+ Args:
2022
+ service_type: The type of service, either "Feature" or "Image".
2023
+ service_id: The ID of the service to delete.
2024
+
2025
+ Returns:
2026
+ dict: The response confirming deletion.
2027
+ """
2028
+ response = await self._delete(f"/arcgis_services/{service_type}/{service_id}")
2029
+ return response.json()
2030
+
2031
+ async def update_arcgis_service(
2032
+ self,
2033
+ service_type: Literal["Feature", "Image"],
2034
+ service_id: int,
2035
+ update_input: ArcgisServiceUpdateInput,
2036
+ ) -> dict:
2037
+ """Update an existing ArcGIS service with new values.
2038
+
2039
+ Args:
2040
+ service_type: The type of service, either "Feature" or "Image".
2041
+ service_id: The ID of the service to update.
2042
+ update_input: ArcgisServiceUpdateInput object containing the fields to update.
2043
+
2044
+ Returns:
2045
+ dict: The updated ArcGIS service object.
2046
+ """
2047
+ response = await self._put(
2048
+ f"/arcgis_services/{service_type}/{service_id}",
2049
+ json=update_input.model_dump(mode="json"),
2050
+ )
2051
+ return response.json()
2052
+
2053
+ async def start_arcgis_service(
2054
+ self,
2055
+ service_type: Literal["Feature", "Image"],
2056
+ service_id: int,
2057
+ wait: bool = True,
2058
+ ) -> dict:
2059
+ """Start a specific ArcGIS service.
2060
+
2061
+ Args:
2062
+ service_type: The type of service, either "Feature" or "Image".
2063
+ service_id: The ID of the service to start.
2064
+ wait: If True, wait for the start operation to complete before returning.
2065
+ If False, return immediately after initiating the start operation.
2066
+
2067
+ Returns:
2068
+ dict: A response object containing job information and, if wait is True,
2069
+ the updated service object after starting.
2070
+ """
2071
+ response = await self._put(
2072
+ f"/arcgis_services/{service_type}/{service_id}/start"
2073
+ )
2074
+ resp = response.json()
2075
+ job = resp["job"]
2076
+ if wait and job:
2077
+ job = await self.wait_for_job(job["job_id"], timeout=1000)
2078
+ resp["job"] = job
2079
+ resp["arcgis_service"] = await self.get_arcgis_service(
2080
+ service_type, service_id
2081
+ )
2082
+ return resp
2083
+
2084
+ async def stop_arcgis_service(
2085
+ self,
2086
+ service_type: Literal["Feature", "Image"],
2087
+ service_id: int,
2088
+ wait: bool = True,
2089
+ ) -> dict:
2090
+ """Stop a specific ArcGIS service.
2091
+
2092
+ Args:
2093
+ service_type: The type of service, either "Feature" or "Image".
2094
+ service_id: The ID of the service to stop.
2095
+ wait: If True, wait for the stop operation to complete before returning.
2096
+ If False, return immediately after initiating the stop operation.
2097
+
2098
+ Returns:
2099
+ dict: A response object containing job information and, if wait is True,
2100
+ the updated service object after stopping.
2101
+ """
2102
+ response = await self._put(f"/arcgis_services/{service_type}/{service_id}/stop")
2103
+ resp = response.json()
2104
+ job = resp["job"]
2105
+ if wait and job:
2106
+ job = await self.wait_for_job(job["job_id"], timeout=1000)
2107
+ resp["job"] = job
2108
+ resp["arcgis_service"] = await self.get_arcgis_service(
2109
+ service_type, service_id
2110
+ )
2111
+ return resp
2112
+
2113
+ async def refresh_arcgis_service(
2114
+ self,
2115
+ service_type: Literal["Feature", "Image"],
2116
+ service_id: int,
2117
+ refresh_data: bool = False,
2118
+ wait: bool = True,
2119
+ ) -> dict:
2120
+ """Refresh a specific ArcGIS service, optionally refreshing its data.
2121
+
2122
+ Args:
2123
+ service_type: The type of service, either "Feature" or "Image".
2124
+ service_id: The ID of the service to refresh.
2125
+ refresh_data: If True, also refresh the data used by the service.
2126
+ wait: If True, wait for the refresh operation to complete before returning.
2127
+ If False, return immediately after initiating the refresh operation.
2128
+
2129
+ Returns:
2130
+ dict: A response object containing job information and, if wait is True,
2131
+ the updated service object after refreshing.
2132
+ """
2133
+ response = await self._put(
2134
+ f"/arcgis_services/{service_type}/{service_id}/refresh",
2135
+ params={"refresh_data": refresh_data},
2136
+ )
2137
+ resp = response.json()
2138
+ job = resp["job"]
2139
+ if wait and job:
2140
+ job = await self.wait_for_job(job["job_id"], timeout=1000)
2141
+ resp["job"] = job
2142
+ resp["arcgis_service"] = await self.get_arcgis_service(
2143
+ service_type, service_id
2144
+ )
2145
+ return resp
2146
+
2147
+ async def create_harvest_service(
2148
+ self,
2149
+ project_id: int,
2150
+ data_collection_id: int,
2151
+ create_input: HarvestServiceCreateInput,
2152
+ ) -> dict:
2153
+ """Create a new harvest service for a data collection.
2154
+
2155
+ Args:
2156
+ project_id: The ID of the project containing the data collection.
2157
+ data_collection_id: The ID of the data collection to create the harvest service for.
2158
+ create_input: HarvestServiceCreateInput object containing the service configuration.
2159
+
2160
+ Returns:
2161
+ dict: The created harvest service object.
2162
+ """
2163
+ response = await self._post(
2164
+ f"/projects/{project_id}/data_collections/{data_collection_id}/harvest_services/",
2165
+ json=create_input.model_dump(mode="json"),
2166
+ sensitive_content=True,
2167
+ )
2168
+ return response.json()
2169
+
2170
+ async def list_harvest_services(
2171
+ self,
2172
+ project_id: int,
2173
+ data_collection_id: int,
2174
+ params: ListParams | None = None,
2175
+ **kwargs,
2176
+ ) -> list[dict]:
2177
+ """List harvest services for a data collection with optional filtering.
2178
+
2179
+ Args:
2180
+ project_id: The ID of the project containing the data collection.
2181
+ data_collection_id: The ID of the data collection to list harvest services for.
2182
+ params: Optional ListParams object containing filtering parameters.
2183
+ **kwargs: Alternative way to provide filtering parameters. Ignored if params is provided.
2184
+
2185
+ Returns:
2186
+ list[dict]: A list of harvest service objects matching the filter criteria.
2187
+ """
2188
+ if params and kwargs:
2189
+ logger.warning("Ignoring kwargs when params is provided")
2190
+ params_dict = (
2191
+ params.model_dump(exclude_none=True)
2192
+ if params
2193
+ else ListParams.model_validate(kwargs).model_dump(exclude_none=True)
2194
+ )
2195
+ response = await self._get(
2196
+ f"/projects/{project_id}/data_collections/{data_collection_id}/harvest_services/",
2197
+ params=params_dict,
2198
+ )
2199
+ return response.json()
2200
+
2201
+ async def get_harvest_service(
2202
+ self, project_id: int, data_collection_id: int, service_id: int
2203
+ ) -> dict:
2204
+ """Retrieve a specific harvest service by its ID.
2205
+
2206
+ Args:
2207
+ project_id: The ID of the project containing the data collection.
2208
+ data_collection_id: The ID of the data collection containing the harvest service.
2209
+ service_id: The ID of the harvest service to retrieve.
2210
+
2211
+ Returns:
2212
+ dict: The harvest service object with its details.
2213
+ """
2214
+ response = await self._get(
2215
+ f"/projects/{project_id}/data_collections/{data_collection_id}/harvest_services/{service_id}"
2216
+ )
2217
+ return response.json()
2218
+
2219
+ async def update_harvest_service(
2220
+ self,
2221
+ project_id: int,
2222
+ data_collection_id: int,
2223
+ service_id: int,
2224
+ update_input: HarvestServiceUpdateInput,
2225
+ ) -> dict:
2226
+ """Update an existing harvest service with new values.
2227
+
2228
+ Args:
2229
+ project_id: The ID of the project containing the data collection.
2230
+ data_collection_id: The ID of the data collection containing the harvest service.
2231
+ service_id: The ID of the harvest service to update.
2232
+ update_input: HarvestServiceUpdateInput object containing the fields to update.
2233
+
2234
+ Returns:
2235
+ dict: The updated harvest service object.
2236
+ """
2237
+ response = await self._put(
2238
+ f"/projects/{project_id}/data_collections/{data_collection_id}/harvest_services/{service_id}",
2239
+ json=update_input.model_dump(mode="json", exclude_none=True),
2240
+ sensitive_content=True,
2241
+ )
2242
+ return response.json()
2243
+
2244
+ async def delete_harvest_service(
2245
+ self, project_id: int, data_collection_id: int, service_id: int
2246
+ ) -> dict:
2247
+ """Delete a specific harvest service by its ID.
2248
+
2249
+ Args:
2250
+ project_id: The ID of the project containing the data collection.
2251
+ data_collection_id: The ID of the data collection containing the harvest service.
2252
+ service_id: The ID of the harvest service to delete.
2253
+
2254
+ Returns:
2255
+ dict: The response confirming deletion.
2256
+ """
2257
+ response = await self._delete(
2258
+ f"/projects/{project_id}/data_collections/{data_collection_id}/harvest_services/{service_id}"
2259
+ )
2260
+ return response.json()
2261
+
2262
+ async def get_harvest_service_tasks(
2263
+ self,
2264
+ project_id: int,
2265
+ data_collection_id: int,
2266
+ service_id: int,
2267
+ params: HarvestTaskListParams,
2268
+ **kwargs,
2269
+ ) -> list[dict]:
2270
+ """Retrieve tasks for a specific harvest service with optional filtering.
2271
+
2272
+ Args:
2273
+ project_id: The ID of the project containing the data collection.
2274
+ data_collection_id: The ID of the data collection containing the harvest service.
2275
+ service_id: The ID of the harvest service to retrieve tasks for.
2276
+ params: HarvestTaskListParams object containing filtering parameters.
2277
+ **kwargs: Alternative way to provide filtering parameters. Ignored if params is provided.
2278
+
2279
+ Returns:
2280
+ list[dict]: A list of harvest task objects matching the filter criteria.
2281
+ """
2282
+ params_dict = (
2283
+ params.model_dump(exclude_none=True)
2284
+ if params
2285
+ else ListParams.model_validate(kwargs).model_dump(exclude_none=True)
2286
+ )
2287
+ response = await self._get(
2288
+ f"/projects/{project_id}/data_collections/{data_collection_id}/harvest_services/{service_id}/",
2289
+ params=params_dict,
2290
+ )
2291
+ return response.json()
2292
+
2293
+ async def start_harvest_service(
2294
+ self, project_id: int, data_collection_id: int, service_id: int
2295
+ ) -> dict:
2296
+ """Start a specific harvest service.
2297
+
2298
+ Args:
2299
+ project_id: The ID of the project containing the data collection.
2300
+ data_collection_id: The ID of the data collection containing the harvest service.
2301
+ service_id: The ID of the harvest service to start.
2302
+
2303
+ Returns:
2304
+ dict: The response confirming the service has been started.
2305
+ """
2306
+ response = await self._post(
2307
+ f"/projects/{project_id}/data_collections/{data_collection_id}/harvest_services/{service_id}/start"
2308
+ )
2309
+ return response.json()
2310
+
2311
+ async def stop_harvest_service(
2312
+ self, project_id: int, data_collection_id: int, service_id: int
2313
+ ) -> dict:
2314
+ """Stop a specific harvest service.
2315
+
2316
+ Args:
2317
+ project_id: The ID of the project containing the data collection.
2318
+ data_collection_id: The ID of the data collection containing the harvest service.
2319
+ service_id: The ID of the harvest service to stop.
2320
+
2321
+ Returns:
2322
+ dict: The response confirming the service has been stopped.
2323
+ """
2324
+ response = await self._post(
2325
+ f"/projects/{project_id}/data_collections/{data_collection_id}/harvest_services/{service_id}/stop"
2326
+ )
2327
+ return response.json()
2328
+
2329
+ async def create_oidc_user(self, create_input: OIDCUserCreateInput) -> dict:
2330
+ """Create a new OIDC user in the system.
2331
+
2332
+ Args:
2333
+ create_input: OIDCUserCreateInput object containing the user information.
2334
+
2335
+ Returns:
2336
+ dict: The created user object.
2337
+
2338
+ Note:
2339
+ This method handles the extraction of the password from the SecretStr field
2340
+ in the create_input object.
2341
+ """
2342
+ model_dump = create_input.model_dump(mode="json")
2343
+ response = await self._post(
2344
+ "/users/oidc/", json=model_dump, sensitive_content=True
2345
+ )
2346
+ return response.json()
2347
+
2348
+ async def update_oidc_user(
2349
+ self, user_id: int, update_input: OIDCUserUpdateInput
2350
+ ) -> dict:
2351
+ """Update an existing OIDC user with new values.
2352
+
2353
+ Args:
2354
+ user_id: The ID of the user to update.
2355
+ update_input: OIDCUserUpdateInput object containing the fields to update.
2356
+
2357
+ Returns:
2358
+ dict: The updated user object.
2359
+
2360
+ Note:
2361
+ This method handles the extraction of the password from the SecretStr field
2362
+ in the update_input object if provided.
2363
+ """
2364
+ model_dump = update_input.model_dump(mode="json")
2365
+ response = await self._put(
2366
+ f"/users/oidc/{user_id}/", json=model_dump, sensitive_content=True
2367
+ )
2368
+ return response.json()
2369
+
2370
+ async def _upload_attachment_to_s3(
2371
+ self,
2372
+ resource_type: AttachmentResourceType,
2373
+ resource_id: int,
2374
+ attachment: dict,
2375
+ file_path: Path,
2376
+ ) -> dict:
2377
+ """Upload an attachment file to S3 and mark it as completed.
2378
+
2379
+ Args:
2380
+ resource_type: The type of resource the attachment belongs to.
2381
+ resource_id: The ID of the resource the attachment belongs to.
2382
+ attachment: The attachment object containing upload parameters.
2383
+ file_path: Path to the attachment file to upload.
2384
+
2385
+ Returns:
2386
+ dict: The updated attachment object.
2387
+
2388
+ Raises:
2389
+ AssertionError: If the attachment status is not "Pending".
2390
+ httpx.HTTPStatusError: If the upload fails.
2391
+ """
2392
+ assert attachment["status"] == "Pending", "Attachment status must be pending"
2393
+ response = await self._internal_client.post(
2394
+ attachment["upload_file_params"]["url"],
2395
+ files={"file": file_path.read_bytes()},
2396
+ data=attachment["upload_file_params"]["fields"],
2397
+ )
2398
+ response.raise_for_status()
2399
+ # Update the status to completed
2400
+ resp = await self._put(
2401
+ "/attachments/update",
2402
+ params={
2403
+ "resource_type": resource_type,
2404
+ "resource_id": resource_id,
2405
+ "attachment_id": attachment["id"],
2406
+ "status": "Completed",
2407
+ },
2408
+ )
2409
+ return resp.json()
2410
+
2411
+ async def list_attachments(
2412
+ self,
2413
+ resource_type: AttachmentResourceType,
2414
+ resource_id: int,
2415
+ status: Literal["Pending", "Completed"] | None = None,
2416
+ ) -> list[dict]:
2417
+ """List attachments for a specific resource with optional status filtering.
2418
+
2419
+ Args:
2420
+ resource_type: The type of resource the attachments belong to.
2421
+ resource_id: The ID of the resource to list attachments for.
2422
+ status: Optional filter for attachment status, either "Pending" or "Completed".
2423
+
2424
+ Returns:
2425
+ list[dict]: A list of attachment objects matching the filter criteria.
2426
+ """
2427
+ params = {"resource_type": resource_type, "resource_id": resource_id}
2428
+ if status:
2429
+ params["status"] = status
2430
+ response = await self._get(
2431
+ "/attachments/",
2432
+ params=params,
2433
+ )
2434
+ return response.json()
2435
+
2436
+ async def add_attachments(
2437
+ self,
2438
+ resource_type: AttachmentResourceType,
2439
+ resource_id: int,
2440
+ files: list[PixelAttachmentUpload | Path]
2441
+ | list[Path]
2442
+ | list[PixelAttachmentUpload],
2443
+ ) -> list[dict]:
2444
+ """Add one or more file attachments to a resource.
2445
+
2446
+ Args:
2447
+ resource_type: The type of resource to attach files to.
2448
+ resource_id: The ID of the resource to attach files to.
2449
+ files: List of files to attach, which can be Path objects or PixelAttachmentUpload objects.
2450
+
2451
+ Returns:
2452
+ list[dict]: A list of the created attachment objects.
2453
+
2454
+ Raises:
2455
+ AssertionError: If any attachment names are not unique.
2456
+ """
2457
+ pixel_attachments = [
2458
+ PixelAttachmentUpload(
2459
+ file=f,
2460
+ )
2461
+ if isinstance(f, Path)
2462
+ else f
2463
+ for f in files
2464
+ ]
2465
+ assert len(set(pa.name for pa in pixel_attachments)) == len(
2466
+ pixel_attachments
2467
+ ), "Attachment names must be unique"
2468
+ response = await self._post(
2469
+ "/attachments/",
2470
+ params={"resource_type": resource_type, "resource_id": resource_id},
2471
+ json={"files": [pa.model_dump(mode="json") for pa in pixel_attachments]},
2472
+ )
2473
+ attachments = response.json()
2474
+ sorted_attachments = sorted(attachments, key=lambda a: a["name"])
2475
+ sorted_files = sorted(pixel_attachments, key=lambda f: f.name)
2476
+ attachments = await asyncio.gather(
2477
+ *[
2478
+ self._upload_attachment_to_s3(resource_type, resource_id, a, pa.file)
2479
+ for a, pa in zip(sorted_attachments, sorted_files)
2480
+ ]
2481
+ )
2482
+ return attachments
2483
+
2484
+ async def move_attachment(
2485
+ self,
2486
+ resource_type: AttachmentResourceType,
2487
+ resource_id: int,
2488
+ attachment_id: int,
2489
+ new_resource_type: AttachmentResourceType,
2490
+ new_resource_id: int,
2491
+ ) -> dict:
2492
+ """Move an attachment from one resource to another.
2493
+
2494
+ Args:
2495
+ resource_type: The current resource type of the attachment.
2496
+ resource_id: The current resource ID the attachment belongs to.
2497
+ attachment_id: The ID of the attachment to move.
2498
+ new_resource_type: The target resource type to move the attachment to.
2499
+ new_resource_id: The target resource ID to move the attachment to.
2500
+
2501
+ Returns:
2502
+ dict: The updated attachment object.
2503
+ """
2504
+ resp = await self._put(
2505
+ "/attachments/move",
2506
+ params={
2507
+ "resource_type": resource_type,
2508
+ "resource_id": resource_id,
2509
+ "attachment_id": attachment_id,
2510
+ "new_resource_type": new_resource_type,
2511
+ "new_resource_id": new_resource_id,
2512
+ },
2513
+ )
2514
+ return resp.json()
2515
+
2516
+ async def delete_attachment(
2517
+ self,
2518
+ resource_type: AttachmentResourceType,
2519
+ resource_id: int,
2520
+ attachment_id: int,
2521
+ ) -> dict:
2522
+ """Delete a specific attachment from a resource.
2523
+
2524
+ Args:
2525
+ resource_type: The resource type the attachment belongs to.
2526
+ resource_id: The resource ID the attachment belongs to.
2527
+ attachment_id: The ID of the attachment to delete.
2528
+
2529
+ Returns:
2530
+ dict: The response confirming deletion.
2531
+ """
2532
+ resp = await self._delete(
2533
+ "/attachments/",
2534
+ params={
2535
+ "resource_type": resource_type,
2536
+ "resource_id": resource_id,
2537
+ "attachment_id": attachment_id,
2538
+ },
2539
+ )
2540
+ return resp.json()