pixel-client 1.2.3__tar.gz → 1.2.5__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pixel-client
3
- Version: 1.2.3
3
+ Version: 1.2.5
4
4
  Summary: Client library for Geodata Pixel
5
5
  Project-URL: Documentation, https://doc.geodatapixel.no/
6
6
  Project-URL: Organization, https://geodata.no
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "pixel-client"
3
- version = "1.2.3"
3
+ version = "1.2.5"
4
4
  description = "Client library for Geodata Pixel"
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.11"
@@ -44,7 +44,7 @@ dev = [
44
44
  "ruff>=0.9.7",
45
45
  ]
46
46
  docs = [
47
- "griffe-pydantic>=1.1.2",
47
+ "griffe-pydantic==1.1.8",
48
48
  "griffe-typingdoc>=0.2.8",
49
49
  "mkdocs-glightbox>=0.4.0",
50
50
  "mkdocs-material>=9.6.14",
@@ -62,4 +62,4 @@ include = [
62
62
 
63
63
  [tool.basedpyright]
64
64
  include = ["src"]
65
- typeCheckingMode = "basic"
65
+ typeCheckingMode = "basic"
@@ -3,7 +3,16 @@ import json
3
3
  import logging
4
4
  from functools import partial
5
5
  from pathlib import Path
6
- from typing import Any, AsyncGenerator, Literal, TypeVar, Self, TypedDict, Unpack
6
+ from typing import (
7
+ Any,
8
+ AsyncGenerator,
9
+ Callable,
10
+ Literal,
11
+ TypeVar,
12
+ Self,
13
+ TypedDict,
14
+ Unpack,
15
+ )
7
16
  from uuid import uuid4
8
17
  import tenacity
9
18
  import httpx
@@ -34,6 +43,9 @@ from .models import (
34
43
  ImageUpdateInput,
35
44
  HarvestServiceUpdateInput,
36
45
  RasterUpdateInput,
46
+ SearchOn,
47
+ SearchQuery,
48
+ SearchResults,
37
49
  )
38
50
  from .settings import PixelApiSettings
39
51
  from .types import AttachmentResourceType, DataCollectionType, OverviewResampling
@@ -258,26 +270,40 @@ class PixelClientAsync:
258
270
  return await self._make_request("DELETE", url, **kwargs)
259
271
 
260
272
  async def _paginate(
261
- self, url: str, page_size: int, **kwargs
273
+ self,
274
+ url: str,
275
+ page_size: int,
276
+ method: str = "GET",
277
+ use_body: bool = False,
278
+ results_parser: Callable[[dict], list[dict]] | None = None,
279
+ **kwargs,
262
280
  ) -> AsyncGenerator[dict, None]:
263
281
  """Internal helper function for paginating through API results.
264
282
 
265
283
  Args:
266
284
  url: The API endpoint URL to paginate through.
267
285
  page_size: Number of items to fetch per page.
268
- **kwargs: Additional parameters to pass to the GET request.
269
-
286
+ method: HTTP method to use for the request (default is "GET").
287
+ use_body: Whether to use the request body for pagination parameters instead of query parameters.
288
+ **kwargs: Additional parameters to pass to the _make_request method.
270
289
  Yields:
271
290
  dict: Individual items from the paginated results, one at a time.
272
291
  """
273
- params = kwargs.pop("params", {})
274
- offset = params.get("offset", 0)
292
+ params: dict = kwargs.pop("params", {})
293
+ body: dict = kwargs.pop("json", {})
294
+ offset: int = params.get("offset", 0) if not use_body else body.get("offset", 0)
275
295
  limit = page_size
276
296
  while True:
277
- response = await self._get(
278
- url, params={**params, "offset": offset, "limit": limit}
297
+ new_body = {**body, "offset": offset, "limit": limit} if use_body else body
298
+ new_params = (
299
+ {**params, "offset": offset, "limit": limit} if not use_body else params
300
+ )
301
+ response = await self._make_request(
302
+ method, url, params=new_params, json=new_body, **kwargs
279
303
  )
280
304
  data = response.json()
305
+ if results_parser and isinstance(data, dict):
306
+ data = results_parser(data)
281
307
  for item in data:
282
308
  yield item
283
309
  if (
@@ -1132,34 +1158,29 @@ class PixelClientAsync:
1132
1158
  response.raise_for_status()
1133
1159
  return None
1134
1160
 
1135
-
1136
- async def _upload_multipart_to_s3(self, upload_job: dict, file_path: Path, multipart_part_size: int):
1161
+ async def _upload_multipart_to_s3(
1162
+ self, upload_job: dict, file_path: Path, multipart_part_size: int
1163
+ ):
1137
1164
  parts = sorted(upload_job["upload_parts"], key=lambda p: p["part_number"])
1138
-
1139
-
1165
+
1140
1166
  async def read_and_upload_single_part(part_index, part):
1141
-
1142
1167
  async with self._semaphore:
1143
- with open(file_path, 'rb') as f:
1168
+ with open(file_path, "rb") as f:
1144
1169
  f.seek(part_index * multipart_part_size)
1145
1170
  part_data = f.read(multipart_part_size)
1146
-
1171
+
1147
1172
  response = await self._internal_client.put(
1148
1173
  part["url"], content=part_data, headers=part["headers"]
1149
1174
  )
1150
1175
  response.raise_for_status()
1151
-
1152
-
1153
-
1154
- tasks = [
1155
- read_and_upload_single_part(i, part)
1156
- for i, part in enumerate(parts)
1157
- ]
1158
-
1176
+
1177
+ tasks = [read_and_upload_single_part(i, part) for i, part in enumerate(parts)]
1178
+
1159
1179
  with silence_logger(logging.getLogger("httpx")):
1160
- await tqdm_asyncio.gather(*tasks, total=len(tasks),
1161
- desc=f"Uploading {file_path.name} to Pixel")
1162
-
1180
+ await tqdm_asyncio.gather(
1181
+ *tasks, total=len(tasks), desc=f"Uploading {file_path.name} to Pixel"
1182
+ )
1183
+
1163
1184
  return None
1164
1185
 
1165
1186
  async def _upload_to_s3(
@@ -2620,3 +2641,71 @@ class PixelClientAsync:
2620
2641
  },
2621
2642
  )
2622
2643
  return resp.json()
2644
+
2645
+ async def search_info(self, on: SearchOn):
2646
+ """
2647
+ Retrieve search metadata for a specific resource type.
2648
+
2649
+ Args:
2650
+ on: The resource type to retrieve search metadata for.
2651
+ Returns:
2652
+ dict: A dictionary containing output fields, filterable fields and search capabilities.
2653
+ """
2654
+ response = await self._get(
2655
+ "/search/info",
2656
+ params={"on": on},
2657
+ )
2658
+ return response.json()
2659
+
2660
+ async def search(
2661
+ self,
2662
+ search_query: dict | SearchQuery,
2663
+ ) -> SearchResults:
2664
+ """
2665
+ Perform a search across various resources.
2666
+
2667
+ Args:
2668
+ search_query: SearchQuery object or dict containing the search parameters.
2669
+ Returns:
2670
+ SearchResults: The search results dictionary.
2671
+ """
2672
+ search_model = (
2673
+ SearchQuery.model_validate(search_query)
2674
+ if isinstance(search_query, dict)
2675
+ else search_query
2676
+ )
2677
+ response = await self._post(
2678
+ "/search/",
2679
+ json=search_model.model_dump(mode="json", exclude_none=True),
2680
+ )
2681
+ return response.json()
2682
+
2683
+ async def paginate_search(
2684
+ self, search_query: dict | SearchQuery, page_size: int
2685
+ ) -> AsyncGenerator[dict, None]:
2686
+ """
2687
+ Perform a paginated search across various resources.
2688
+
2689
+ Args:
2690
+ search_query: SearchQuery object or dict containing the search parameters.
2691
+ page_size: Number of results to retrieve per page.
2692
+
2693
+ Yields:
2694
+ dict: Individual search result items.
2695
+ """
2696
+ search_model = (
2697
+ SearchQuery.model_validate(search_query)
2698
+ if isinstance(search_query, dict)
2699
+ else search_query
2700
+ )
2701
+ search_query_body = search_model.model_dump(mode="json", exclude_none=True)
2702
+ async for item in self._paginate(
2703
+ "/search/",
2704
+ method="POST",
2705
+ page_size=page_size,
2706
+ use_body=True,
2707
+ # The return of the search endpoint is in the "results" field
2708
+ results_parser=lambda resp: resp.get("results", []),
2709
+ json=search_query_body,
2710
+ ):
2711
+ yield item
@@ -2,7 +2,7 @@ from pathlib import Path
2
2
  from typing import Literal, Iterator
3
3
  from geojson_pydantic import Polygon
4
4
  from typing import Self
5
- from pixel_client.models import (
5
+ from .models import (
6
6
  ArcgisServiceCreateInput,
7
7
  ArcgisServiceUpdateInput,
8
8
  HarvestServiceCreateInput,
@@ -18,6 +18,9 @@ from pixel_client.models import (
18
18
  DataCollectionListParams,
19
19
  ImageUpdateInput,
20
20
  RasterUpdateInput,
21
+ SearchOn,
22
+ SearchQuery,
23
+ SearchResults,
21
24
  )
22
25
  from .types import AttachmentResourceType, OverviewResampling
23
26
  from .exceptions import PixelUploadJobError
@@ -1548,3 +1551,45 @@ class PixelClient:
1548
1551
  resource_type, resource_id, attachment_id
1549
1552
  )
1550
1553
  )
1554
+
1555
+ def search_info(self, on: SearchOn) -> dict:
1556
+ """
1557
+ Retrieve search metadata for a specific resource type.
1558
+
1559
+ Args:
1560
+ on: The resource type to retrieve search metadata for.
1561
+ Returns:
1562
+ dict: A dictionary containing output fields, filterable fields and search capabilities.
1563
+ """
1564
+ return run_sync(self._async_client.search_info(on))
1565
+
1566
+ def search(self, search_query: dict | SearchQuery) -> SearchResults:
1567
+ """
1568
+ Perform a search across various resources.
1569
+
1570
+ Args:
1571
+ search_query: SearchQuery object or dict containing the search parameters.
1572
+ Returns:
1573
+ SearchResults: The search results dictionary.
1574
+ """
1575
+ return run_sync(self._async_client.search(search_query))
1576
+
1577
+ def paginate_search(
1578
+ self, search_query: dict | SearchQuery, page_size: int
1579
+ ) -> Iterator[dict]:
1580
+ """
1581
+ Perform a paginated search across various resources.
1582
+
1583
+ Args:
1584
+ search_query: SearchQuery object or dict containing the search parameters.
1585
+ page_size: Number of results to retrieve per page.
1586
+
1587
+ Yields:
1588
+ dict: Individual search result items.
1589
+ """
1590
+ return iter_over_async(
1591
+ self._async_client.paginate_search(
1592
+ search_query,
1593
+ page_size,
1594
+ )
1595
+ )
@@ -1,10 +1,18 @@
1
+ import sys
1
2
  import datetime
2
3
  from enum import StrEnum
3
4
  from functools import cached_property
4
5
  from pathlib import Path
5
6
  from typing import Annotated, Literal, Self, Union
6
7
 
7
- from annotated_types import Ge, Len, Lt
8
+ # Import TypedDict from typing_extensions if python version is < 3.12
9
+ if sys.version_info >= (3, 12):
10
+ from typing import TypedDict
11
+ else:
12
+ from typing_extensions import TypedDict
13
+
14
+
15
+ from annotated_types import Ge, Len, Lt, MinLen
8
16
  from pydantic import (
9
17
  BaseModel,
10
18
  Discriminator,
@@ -421,3 +429,83 @@ class RasterUpdateInput(UpdateInputBase):
421
429
  """
422
430
 
423
431
  fields: RasterMetadataFields | None = None
432
+
433
+
434
+ SearchOn = Literal["images", "rasters", "projects", "data_collections"]
435
+
436
+
437
+ ### Search filter definitions
438
+ class SearchFilterVar(TypedDict):
439
+ var: str
440
+
441
+
442
+ SearchFilterOperator = Literal[
443
+ "==", "!=", "<", "<=", ">", ">=", "~", "!~", "contains", "!contains", "in", "!in"
444
+ ]
445
+ SearchFilterDataType = Union[str, int, float, datetime.datetime, None]
446
+ SearchFilterListDataType = Annotated[list[SearchFilterDataType], MinLen(1)]
447
+ SearchFilterCompDataType = Union[SearchFilterDataType, SearchFilterListDataType]
448
+ SearchFilterComparisonDict = dict[
449
+ SearchFilterOperator, tuple[SearchFilterVar, SearchFilterCompDataType]
450
+ ]
451
+ SearchFilterAndExpr = TypedDict("SearchFilterAndExpr", {"and": list["SearchFilter"]})
452
+ SearchFilterOrExpr = TypedDict("SearchFilterOrExpr", {"or": list["SearchFilter"]})
453
+ SearchFilter = Union[
454
+ SearchFilterComparisonDict, SearchFilterAndExpr, SearchFilterOrExpr
455
+ ]
456
+
457
+
458
+ class SortField(BaseModel):
459
+ field: str
460
+ direction: Literal["asc", "desc"] = "asc"
461
+
462
+
463
+ class SearchQuery(BaseModel):
464
+ """
465
+ Model definition for search queries in Pixel API."""
466
+
467
+ on: SearchOn = Field(description="Type to search on")
468
+ intersects: str | None = Field(
469
+ default=None,
470
+ description="A WKT geometry to filter results by intersection, must be in EPSG:4326 (WGS84) coordinates",
471
+ )
472
+ filter: SearchFilter | None = Field(
473
+ default=None,
474
+ description="The filter logic to apply",
475
+ examples=[
476
+ {
477
+ "or": [
478
+ {">=": [{"var": "created_at"}, "2023-01-01T00:00:00Z"]},
479
+ {"~": [{"var": "name"}, "%test%"]},
480
+ {
481
+ "and": [
482
+ {">=": [{"var": "id"}, 1]},
483
+ {"<=": [{"var": "id"}, 10]},
484
+ ]
485
+ },
486
+ ]
487
+ }
488
+ ],
489
+ )
490
+ search: str | None = Field(
491
+ default=None, description="A full text search string to apply"
492
+ )
493
+
494
+ out_fields: list[str] | None = Field(
495
+ default=None, description="Fields to include in the output"
496
+ )
497
+
498
+ sort: list[SortField] | None = Field(
499
+ default=None, description="Fields to sort the results by"
500
+ )
501
+ distinct: bool = Field(
502
+ default=False, description="Whether to return distinct results"
503
+ )
504
+ limit: int = Field(default=100, description="Maximum number of results to return")
505
+ offset: int = Field(default=0, description="Number of results to skip")
506
+
507
+
508
+ class SearchResults(TypedDict):
509
+ count: int
510
+ results: list[dict]
511
+ total_count: int
File without changes
File without changes
File without changes