hypersr 0.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.
hypersr/__init__.py ADDED
@@ -0,0 +1,67 @@
1
+ """Public API for the HyperSR Python SDK."""
2
+
3
+ from ._version import __version__
4
+ from .client import HyperSR
5
+ from .exceptions import (
6
+ APIError,
7
+ AuthenticationError,
8
+ ConflictError,
9
+ HyperSRError,
10
+ NotFoundError,
11
+ RateLimitError,
12
+ RequestError,
13
+ TimeoutError,
14
+ ValidationError,
15
+ )
16
+ from .models import (
17
+ Account,
18
+ AccountSummary,
19
+ APIKey,
20
+ APIKeyCreated,
21
+ BillingPackage,
22
+ CheckoutSession,
23
+ CreditBalance,
24
+ CreditTransaction,
25
+ Job,
26
+ JobOutput,
27
+ Model,
28
+ NotificationPreferences,
29
+ Page,
30
+ Payment,
31
+ Quote,
32
+ SavedAOI,
33
+ SceneSearchResponse,
34
+ SceneSearchResult,
35
+ )
36
+
37
+ __all__ = [
38
+ "__version__",
39
+ "APIError",
40
+ "APIKey",
41
+ "APIKeyCreated",
42
+ "Account",
43
+ "AccountSummary",
44
+ "AuthenticationError",
45
+ "BillingPackage",
46
+ "ConflictError",
47
+ "CheckoutSession",
48
+ "CreditBalance",
49
+ "CreditTransaction",
50
+ "HyperSR",
51
+ "HyperSRError",
52
+ "Job",
53
+ "JobOutput",
54
+ "Model",
55
+ "NotFoundError",
56
+ "NotificationPreferences",
57
+ "Page",
58
+ "Payment",
59
+ "Quote",
60
+ "RateLimitError",
61
+ "RequestError",
62
+ "SavedAOI",
63
+ "SceneSearchResponse",
64
+ "SceneSearchResult",
65
+ "TimeoutError",
66
+ "ValidationError",
67
+ ]
hypersr/_version.py ADDED
@@ -0,0 +1,3 @@
1
+ """SDK release version, shared by package metadata and client identification."""
2
+
3
+ __version__ = "0.1.0"
hypersr/client.py ADDED
@@ -0,0 +1,573 @@
1
+ """Synchronous HyperSR API client."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import builtins
6
+ import hashlib
7
+ import os
8
+ import tempfile
9
+ import time
10
+ from collections.abc import Mapping
11
+ from datetime import UTC, date, datetime
12
+ from pathlib import Path
13
+ from typing import Any
14
+ from urllib.parse import urlparse
15
+ from uuid import uuid4
16
+
17
+ import httpx
18
+
19
+ from ._version import __version__
20
+ from .exceptions import RequestError, TimeoutError, from_response
21
+ from .models import (
22
+ Account,
23
+ AccountSummary,
24
+ APIKey,
25
+ APIKeyCreated,
26
+ BillingPackage,
27
+ CheckoutSession,
28
+ CreditBalance,
29
+ CreditTransaction,
30
+ Job,
31
+ JobOutput,
32
+ Model,
33
+ NotificationPreferences,
34
+ Page,
35
+ Payment,
36
+ Quote,
37
+ SavedAOI,
38
+ SceneSearchResponse,
39
+ parse_page,
40
+ )
41
+
42
+ _RETRYABLE = frozenset({408, 425, 429, 500, 502, 503, 504})
43
+
44
+
45
+ class HyperSR:
46
+ """Typed client for ``https://api.hypersr.com/v1``.
47
+
48
+ The client is reusable and should be closed, preferably with ``with HyperSR(...)``.
49
+ Mutating requests are retried only when an idempotency key is provided.
50
+ """
51
+
52
+ def __init__(
53
+ self,
54
+ api_key: str,
55
+ *,
56
+ base_url: str = "https://api.hypersr.com/v1",
57
+ timeout: float | httpx.Timeout = 30.0,
58
+ max_retries: int = 2,
59
+ transport: httpx.BaseTransport | None = None,
60
+ download_transport: httpx.BaseTransport | None = None,
61
+ user_agent: str | None = None,
62
+ ) -> None:
63
+ if not api_key:
64
+ raise ValueError("api_key must not be empty")
65
+ if max_retries < 0:
66
+ raise ValueError("max_retries must be non-negative")
67
+ self._api_key = api_key
68
+ self._max_retries = max_retries
69
+ self._download_transport = download_transport
70
+ self._base_url = base_url.rstrip("/")
71
+ self._http = httpx.Client(
72
+ base_url=self._base_url,
73
+ timeout=timeout,
74
+ headers={
75
+ "Authorization": f"Bearer {api_key}",
76
+ "User-Agent": user_agent or f"hypersr-python/{__version__}",
77
+ "Accept": "application/json",
78
+ },
79
+ transport=transport,
80
+ )
81
+ self.jobs = Jobs(self)
82
+ self.scenes = Scenes(self)
83
+
84
+ def __repr__(self) -> str:
85
+ return f"HyperSR(base_url={self._base_url!r})"
86
+
87
+ def __enter__(self) -> HyperSR:
88
+ return self
89
+
90
+ def __exit__(self, *_: object) -> None:
91
+ self.close()
92
+
93
+ def close(self) -> None:
94
+ self._http.close()
95
+
96
+ def models(self) -> list[Model]:
97
+ data = self._request("GET", "/models")
98
+ values = data.get("items", data.get("models", [])) if isinstance(data, dict) else data
99
+ values = values if isinstance(values, list) else []
100
+ return [Model.model_validate(item) for item in values]
101
+
102
+ def credits(self) -> CreditBalance:
103
+ data = self._request("GET", "/credits")
104
+ if isinstance(data, dict) and "available" not in data and "balance" in data:
105
+ data = {**data, "available": data["balance"]}
106
+ return CreditBalance.model_validate(data)
107
+
108
+ def billing_packages(self) -> list[BillingPackage]:
109
+ """Return the server-configured prepaid credit packages."""
110
+ data = self._request("GET", "/billing/packages")
111
+ values = data.get("items", []) if isinstance(data, dict) else data
112
+ return (
113
+ [BillingPackage.model_validate(item) for item in values]
114
+ if isinstance(values, list)
115
+ else []
116
+ )
117
+
118
+ def account_summary(self) -> AccountSummary:
119
+ return AccountSummary.model_validate(self._request("GET", "/account/summary"))
120
+
121
+ def aois(self, *, offset: int = 0, limit: int = 50) -> Page[SavedAOI]:
122
+ return parse_page(
123
+ self._request("GET", "/aois", params={"offset": offset, "limit": limit}),
124
+ SavedAOI,
125
+ offset=offset,
126
+ limit=limit,
127
+ )
128
+
129
+ def get_aoi(self, aoi_id: str) -> SavedAOI:
130
+ return SavedAOI.model_validate(self._request("GET", f"/aois/{aoi_id}"))
131
+
132
+ def create_aoi(
133
+ self,
134
+ name: str,
135
+ bbox: list[float] | tuple[float, float, float, float],
136
+ *,
137
+ description: str = "",
138
+ idempotency_key: str | None = None,
139
+ ) -> SavedAOI:
140
+ return SavedAOI.model_validate(
141
+ self._request(
142
+ "POST",
143
+ "/aois",
144
+ json={"name": name, "description": description, "bbox": list(bbox)},
145
+ idempotency_key=idempotency_key,
146
+ retry_mutation=False,
147
+ )
148
+ )
149
+
150
+ def update_aoi(
151
+ self,
152
+ aoi_id: str,
153
+ *,
154
+ name: str | None = None,
155
+ description: str | None = None,
156
+ bbox: list[float] | tuple[float, float, float, float] | None = None,
157
+ idempotency_key: str | None = None,
158
+ ) -> SavedAOI:
159
+ payload: dict[str, Any] = {}
160
+ if name is not None:
161
+ payload["name"] = name
162
+ if description is not None:
163
+ payload["description"] = description
164
+ if bbox is not None:
165
+ payload["bbox"] = list(bbox)
166
+ return SavedAOI.model_validate(
167
+ self._request("PATCH", f"/aois/{aoi_id}", json=payload, idempotency_key=idempotency_key)
168
+ )
169
+
170
+ def delete_aoi(self, aoi_id: str, *, idempotency_key: str | None = None) -> None:
171
+ self._request("DELETE", f"/aois/{aoi_id}", idempotency_key=idempotency_key)
172
+
173
+ def notification_preferences(self) -> NotificationPreferences:
174
+ return NotificationPreferences.model_validate(
175
+ self._request("GET", "/account/notifications")
176
+ )
177
+
178
+ def update_notification_preferences(
179
+ self,
180
+ *,
181
+ job_completed: bool | None = None,
182
+ job_failed: bool | None = None,
183
+ idempotency_key: str | None = None,
184
+ ) -> NotificationPreferences:
185
+ payload = {
186
+ key: value
187
+ for key, value in {
188
+ "job_completed": job_completed,
189
+ "job_failed": job_failed,
190
+ }.items()
191
+ if value is not None
192
+ }
193
+ return NotificationPreferences.model_validate(
194
+ self._request(
195
+ "PATCH",
196
+ "/account/notifications",
197
+ json=payload,
198
+ idempotency_key=idempotency_key,
199
+ )
200
+ )
201
+
202
+ def credit_transactions(self, *, offset: int = 0, limit: int = 100) -> Page[CreditTransaction]:
203
+ params = {"offset": offset, "limit": limit}
204
+ return parse_page(
205
+ self._request("GET", "/credits/transactions", params=params),
206
+ CreditTransaction,
207
+ offset=offset,
208
+ limit=limit,
209
+ )
210
+
211
+ def api_keys(self) -> list[APIKey]:
212
+ data = self._request("GET", "/api-keys")
213
+ raw_values = data.get("items", data.get("keys", data)) if isinstance(data, dict) else data
214
+ values = raw_values if isinstance(raw_values, list) else []
215
+ return [APIKey.model_validate(item) for item in values]
216
+
217
+ def create_api_key(self, name: str, *, idempotency_key: str | None = None) -> APIKeyCreated:
218
+ return APIKeyCreated.model_validate(
219
+ self._request(
220
+ "POST",
221
+ "/api-keys",
222
+ json={"name": name},
223
+ idempotency_key=idempotency_key,
224
+ retry_mutation=False,
225
+ )
226
+ )
227
+
228
+ def revoke_api_key(self, key_id: str, *, idempotency_key: str | None = None) -> None:
229
+ self._request("DELETE", f"/api-keys/{key_id}", idempotency_key=idempotency_key)
230
+
231
+ def account(self) -> Account:
232
+ return Account.model_validate(self._request("GET", "/account"))
233
+
234
+ def update_account(
235
+ self, *, display_name: str | None = None, idempotency_key: str | None = None
236
+ ) -> Account:
237
+ return Account.model_validate(
238
+ self._request(
239
+ "PATCH",
240
+ "/account",
241
+ json={"display_name": display_name},
242
+ idempotency_key=idempotency_key,
243
+ )
244
+ )
245
+
246
+ def checkout(self, package: str, *, idempotency_key: str) -> CheckoutSession:
247
+ return CheckoutSession.model_validate(
248
+ self._request(
249
+ "POST",
250
+ "/billing/checkout",
251
+ json={"package_id": package},
252
+ idempotency_key=idempotency_key,
253
+ )
254
+ )
255
+
256
+ def billing_history(self, *, offset: int = 0, limit: int = 100) -> Page[Payment]:
257
+ return parse_page(
258
+ self._request("GET", "/billing/history", params={"offset": offset, "limit": limit}),
259
+ Payment,
260
+ offset=offset,
261
+ limit=limit,
262
+ )
263
+
264
+ def _request(
265
+ self,
266
+ method: str,
267
+ path: str,
268
+ *,
269
+ params: Mapping[str, Any] | None = None,
270
+ json: Any = None,
271
+ idempotency_key: str | None = None,
272
+ timeout: float | None = None,
273
+ retry_mutation: bool = True,
274
+ ) -> Any:
275
+ safe_read = method.upper() in {"GET", "HEAD", "OPTIONS"}
276
+ attempts = self._max_retries + 1 if safe_read or (idempotency_key and retry_mutation) else 1
277
+ headers = {"Idempotency-Key": idempotency_key} if idempotency_key else {}
278
+ deadline = time.monotonic() + timeout if timeout is not None else None
279
+ for attempt in range(attempts):
280
+ if deadline is not None and time.monotonic() >= deadline:
281
+ raise TimeoutError("HyperSR request timed out")
282
+ try:
283
+ request_kwargs: dict[str, Any] = {
284
+ "params": params,
285
+ "json": json,
286
+ "headers": headers,
287
+ }
288
+ if timeout is not None:
289
+ request_kwargs["timeout"] = (
290
+ max(0.001, deadline - time.monotonic()) if deadline else timeout
291
+ )
292
+ response = self._http.request(method, path, **request_kwargs)
293
+ except httpx.TimeoutException as exc:
294
+ if attempt + 1 >= attempts:
295
+ raise TimeoutError("HyperSR request timed out") from exc
296
+ self._backoff(attempt, deadline=deadline)
297
+ continue
298
+ except httpx.HTTPError as exc:
299
+ if attempt + 1 >= attempts:
300
+ raise RequestError("HyperSR request failed") from exc
301
+ self._backoff(attempt, deadline=deadline)
302
+ continue
303
+ if response.status_code in _RETRYABLE and attempt + 1 < attempts:
304
+ self._backoff(attempt, response, deadline)
305
+ continue
306
+ if response.is_error:
307
+ try:
308
+ payload = response.json()
309
+ except ValueError:
310
+ payload = {}
311
+ raise from_response(response.status_code, payload, dict(response.headers))
312
+ if not response.content:
313
+ return None
314
+ try:
315
+ return response.json()
316
+ except ValueError as exc:
317
+ raise RequestError("HyperSR returned invalid JSON") from exc
318
+ raise RequestError("HyperSR request failed") # pragma: no cover
319
+
320
+ @staticmethod
321
+ def _backoff(
322
+ attempt: int, response: httpx.Response | None = None, deadline: float | None = None
323
+ ) -> None:
324
+ delay = min(8.0, 0.25 * (2**attempt))
325
+ if response is not None and response.headers.get("Retry-After", "").isdigit():
326
+ delay = min(8.0, float(response.headers["Retry-After"]))
327
+ if deadline is not None:
328
+ delay = min(delay, max(0.0, deadline - time.monotonic()))
329
+ time.sleep(delay)
330
+
331
+ def _download(
332
+ self,
333
+ url: str,
334
+ destination: str | os.PathLike[str],
335
+ *,
336
+ checksum: str | None = None,
337
+ expected_size: int | None = None,
338
+ ) -> Path:
339
+ parsed = urlparse(url)
340
+ if parsed.scheme not in {"http", "https"} or not parsed.netloc:
341
+ raise ValueError("download_url must be an absolute HTTP(S) URL")
342
+ if expected_size is not None and expected_size < 0:
343
+ raise RequestError("Output size metadata is invalid")
344
+ target = Path(destination)
345
+ target.parent.mkdir(parents=True, exist_ok=True)
346
+ digest = hashlib.sha256()
347
+ temporary: Path | None = None
348
+ try:
349
+ with (
350
+ httpx.Client(
351
+ follow_redirects=True,
352
+ timeout=self._http.timeout,
353
+ transport=self._download_transport,
354
+ ) as download_client,
355
+ download_client.stream("GET", url) as response,
356
+ ):
357
+ if response.is_error:
358
+ raise from_response(response.status_code, {}, dict(response.headers))
359
+ with tempfile.NamedTemporaryFile(
360
+ dir=target.parent, prefix=f".{target.name}.", delete=False
361
+ ) as temp:
362
+ temporary = Path(temp.name)
363
+ try:
364
+ for chunk in response.iter_bytes():
365
+ exceeds_size = (
366
+ expected_size is not None
367
+ and temp.tell() + len(chunk) > expected_size
368
+ )
369
+ if exceeds_size:
370
+ raise RequestError(
371
+ "Downloaded output exceeds the API size metadata"
372
+ )
373
+ temp.write(chunk)
374
+ digest.update(chunk)
375
+ temp.flush()
376
+ os.fsync(temp.fileno())
377
+ except BaseException:
378
+ temporary.unlink(missing_ok=True)
379
+ raise
380
+ actual = digest.hexdigest()
381
+ if temporary is None:
382
+ raise RequestError("Output download did not create a temporary file")
383
+ if expected_size is not None and temporary.stat().st_size != expected_size:
384
+ temporary.unlink(missing_ok=True)
385
+ raise RequestError("Downloaded output size does not match the API metadata")
386
+ if checksum and actual.lower() != checksum.lower().removeprefix("sha256:"):
387
+ temporary.unlink(missing_ok=True)
388
+ raise RequestError("Downloaded output checksum does not match the API checksum")
389
+ os.replace(temporary, target)
390
+ return target
391
+ except httpx.TimeoutException as exc:
392
+ if temporary:
393
+ temporary.unlink(missing_ok=True)
394
+ raise TimeoutError("Output download timed out") from exc
395
+ except httpx.HTTPError as exc:
396
+ if temporary:
397
+ temporary.unlink(missing_ok=True)
398
+ raise RequestError("Output download failed") from exc
399
+ except BaseException:
400
+ if temporary:
401
+ temporary.unlink(missing_ok=True)
402
+ raise
403
+
404
+
405
+ class Jobs:
406
+ """Job operations exposed as ``client.jobs``."""
407
+
408
+ def __init__(self, client: HyperSR) -> None:
409
+ self._client = client
410
+
411
+ def quote(
412
+ self,
413
+ *,
414
+ scene_id: str,
415
+ bbox: list[float] | tuple[float, float, float, float],
416
+ model: str,
417
+ bands: list[str] | None = None,
418
+ output_format: str = "cog",
419
+ ) -> Quote:
420
+ payload = {
421
+ "scene_id": scene_id,
422
+ "bbox": list(bbox),
423
+ "model": model,
424
+ "output_format": output_format,
425
+ }
426
+ if bands is not None:
427
+ payload["bands"] = bands
428
+ return Quote.model_validate(self._client._request("POST", "/jobs/quote", json=payload))
429
+
430
+ def submit(self, *, quote_id: str, idempotency_key: str | None = None) -> Job:
431
+ stable_key = idempotency_key or str(uuid4())
432
+ return Job.model_validate(
433
+ self._client._request(
434
+ "POST", "/jobs", json={"quote_id": quote_id}, idempotency_key=stable_key
435
+ )
436
+ )
437
+
438
+ def list(
439
+ self,
440
+ *,
441
+ offset: int = 0,
442
+ limit: int = 100,
443
+ status: str | None = None,
444
+ search: str | None = None,
445
+ ) -> Page[Job]:
446
+ params: dict[str, Any] = {"offset": offset, "limit": limit}
447
+ if status is not None:
448
+ params["status"] = status
449
+ if search is not None:
450
+ params["search"] = search
451
+ return parse_page(
452
+ self._client._request("GET", "/jobs", params=params),
453
+ Job,
454
+ offset=offset,
455
+ limit=limit,
456
+ )
457
+
458
+ def get(self, job_id: str) -> Job:
459
+ return Job.model_validate(self._client._request("GET", f"/jobs/{job_id}"))
460
+
461
+ def cancel(self, job_id: str, *, idempotency_key: str | None = None) -> Job:
462
+ return Job.model_validate(
463
+ self._client._request("POST", f"/jobs/{job_id}/cancel", idempotency_key=idempotency_key)
464
+ )
465
+
466
+ def wait(self, job_id: str, *, timeout: float = 3600.0, poll_interval: float = 2.0) -> Job:
467
+ if timeout <= 0 or poll_interval <= 0:
468
+ raise ValueError("timeout and poll_interval must be positive")
469
+ deadline = time.monotonic() + timeout
470
+ while True:
471
+ remaining = deadline - time.monotonic()
472
+ if remaining <= 0:
473
+ raise TimeoutError(f"Timed out waiting for job {job_id}")
474
+ job = Job.model_validate(
475
+ self._client._request("GET", f"/jobs/{job_id}", timeout=remaining)
476
+ )
477
+ if job.status in {"completed", "failed", "cancelled"}:
478
+ return job
479
+ remaining = deadline - time.monotonic()
480
+ if remaining <= 0:
481
+ raise TimeoutError(f"Timed out waiting for job {job_id}")
482
+ time.sleep(min(poll_interval, remaining))
483
+
484
+ def outputs(self, job_id: str) -> builtins.list[JobOutput]:
485
+ data = self._client._request("GET", f"/jobs/{job_id}/outputs")
486
+ values = data.get("items", data.get("outputs", [])) if isinstance(data, dict) else data
487
+ values = values if isinstance(values, list) else []
488
+ return [JobOutput.model_validate(item) for item in values]
489
+
490
+ def _download_output(self, output: JobOutput, destination: str | os.PathLike[str]) -> Path:
491
+ if not output.download_url:
492
+ raise RequestError("Output has no download URL")
493
+ if output.expires_at:
494
+ expiry = output.expires_at
495
+ if expiry.tzinfo is None:
496
+ expiry = expiry.replace(tzinfo=UTC)
497
+ if expiry <= datetime.now(UTC):
498
+ raise RequestError("Output download URL has expired")
499
+ if output.checksum and output.checksum_algorithm.lower() != "sha256":
500
+ raise RequestError("Unsupported output checksum algorithm")
501
+ url = str(self._client._http.base_url.join(output.download_url))
502
+ return self._client._download(
503
+ url,
504
+ destination,
505
+ checksum=output.checksum,
506
+ expected_size=output.size_bytes,
507
+ )
508
+
509
+ def download(
510
+ self, job_id: str, destination: str | os.PathLike[str], *, output_index: int = 0
511
+ ) -> Path:
512
+ outputs = self.outputs(job_id)
513
+ if output_index < 0 or output_index >= len(outputs):
514
+ raise IndexError("output_index is outside the available outputs")
515
+ return self._download_output(outputs[output_index], destination)
516
+
517
+ def download_role(
518
+ self,
519
+ job_id: str,
520
+ role: str,
521
+ destination: str | os.PathLike[str],
522
+ ) -> Path:
523
+ """Download the completed output with a stable product role."""
524
+ outputs = self.outputs(job_id)
525
+ for output in outputs:
526
+ if output.role == role:
527
+ return self._download_output(output, destination)
528
+ raise RequestError(f"Job has no output with role {role!r}")
529
+
530
+
531
+ class Scenes:
532
+ """Read-only scene discovery operations."""
533
+
534
+ def __init__(self, client: HyperSR) -> None:
535
+ self._client = client
536
+
537
+ def search(
538
+ self,
539
+ *,
540
+ bbox: list[float] | tuple[float, float, float, float],
541
+ target_date: str | date,
542
+ days_before: int = 7,
543
+ days_after: int = 3,
544
+ max_cloud_cover: float = 100,
545
+ selection: str = "nearest",
546
+ ) -> SceneSearchResponse:
547
+ """Find available acquisitions near a target date for an AOI.
548
+
549
+ Discovery is read-only and never creates a quote or reserves credits.
550
+ """
551
+ if not 0 <= days_before <= 90:
552
+ raise ValueError("days_before must be between 0 and 90")
553
+ if not 0 <= days_after <= 3:
554
+ raise ValueError("days_after must be between 0 and 3")
555
+ if not 0 <= max_cloud_cover <= 100:
556
+ raise ValueError("max_cloud_cover must be between 0 and 100")
557
+ if selection not in {"nearest", "clearest"}:
558
+ raise ValueError("selection must be 'nearest' or 'clearest'")
559
+ if isinstance(target_date, datetime):
560
+ date_value = target_date.date().isoformat()
561
+ else:
562
+ date_value = target_date.isoformat() if isinstance(target_date, date) else target_date
563
+ payload = {
564
+ "bbox": list(bbox),
565
+ "target_date": date_value,
566
+ "days_before": days_before,
567
+ "days_after": days_after,
568
+ "max_cloud_cover": max_cloud_cover,
569
+ "selection": selection,
570
+ }
571
+ return SceneSearchResponse.model_validate(
572
+ self._client._request("POST", "/scenes/search", json=payload, retry_mutation=False)
573
+ )
hypersr/exceptions.py ADDED
@@ -0,0 +1,69 @@
1
+ """Exception hierarchy and API error parsing."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+
8
+ class HyperSRError(Exception):
9
+ """Base class for all SDK errors."""
10
+
11
+
12
+ class RequestError(HyperSRError):
13
+ """Transport-level failure."""
14
+
15
+
16
+ class TimeoutError(RequestError):
17
+ """Request or polling timeout."""
18
+
19
+
20
+ class APIError(HyperSRError):
21
+ """An HTTP API error with a safe, structured code and request ID."""
22
+
23
+ def __init__(
24
+ self, status_code: int, code: str, message: str, request_id: str | None = None
25
+ ) -> None:
26
+ self.status_code = status_code
27
+ self.code = code
28
+ self.request_id = request_id
29
+ super().__init__(message)
30
+
31
+ def __repr__(self) -> str:
32
+ return f"{type(self).__name__}(status_code={self.status_code}, code={self.code!r})"
33
+
34
+
35
+ class AuthenticationError(APIError): ...
36
+
37
+
38
+ class ValidationError(APIError): ...
39
+
40
+
41
+ class NotFoundError(APIError): ...
42
+
43
+
44
+ class ConflictError(APIError): ...
45
+
46
+
47
+ class RateLimitError(APIError): ...
48
+
49
+
50
+ def from_response(status_code: int, payload: Any, headers: dict[str, str]) -> APIError:
51
+ """Build a typed error without exposing response bodies containing secrets."""
52
+ body = payload.get("error", payload) if isinstance(payload, dict) else {}
53
+ code = str(body.get("code", "HTTP_ERROR"))
54
+ message = str(body.get("message", f"HyperSR request failed ({status_code})"))
55
+ request_id = body.get("request_id") or headers.get("x-request-id")
56
+ cls: type[APIError]
57
+ if status_code in (401, 403):
58
+ cls = AuthenticationError
59
+ elif status_code == 404:
60
+ cls = NotFoundError
61
+ elif status_code == 409:
62
+ cls = ConflictError
63
+ elif status_code == 429:
64
+ cls = RateLimitError
65
+ elif 400 <= status_code < 500:
66
+ cls = ValidationError
67
+ else:
68
+ cls = APIError
69
+ return cls(status_code, code, message, request_id)
hypersr/models.py ADDED
@@ -0,0 +1,221 @@
1
+ """Pydantic models for HyperSR API resources."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from datetime import date, datetime
6
+ from typing import Any, Generic, Literal, TypeVar
7
+
8
+ from pydantic import AliasChoices, BaseModel, ConfigDict, Field
9
+
10
+
11
+ class _Model(BaseModel):
12
+ model_config = ConfigDict(extra="allow", populate_by_name=True)
13
+
14
+
15
+ class Model(_Model):
16
+ bundle_sha256: str | None = None
17
+ id: str
18
+ slug: str | None = None
19
+ version: str | None = None
20
+ display_name: str | None = None
21
+ description: str | None = None
22
+ supported_bands: list[str] = Field(default_factory=list)
23
+ output_resolution: float | None = None
24
+ enabled: bool = True
25
+
26
+
27
+ class BillingPackage(_Model):
28
+ id: str
29
+ name: str
30
+ amount_cents: int
31
+ credits: int
32
+ currency: str
33
+
34
+ @property
35
+ def amount(self) -> int:
36
+ """Backward-friendly alias for the integer minor-unit amount."""
37
+ return self.amount_cents
38
+
39
+
40
+ class Quote(_Model):
41
+ id: str = Field(validation_alias="quote_id", serialization_alias="quote_id")
42
+ model: str
43
+ area_km2: float
44
+ required_credits: int
45
+ expires_at: datetime
46
+
47
+ @property
48
+ def quote_id(self) -> str:
49
+ return self.id
50
+
51
+
52
+ class JobOutput(_Model):
53
+ format: str
54
+ filename: str | None = None
55
+ size_bytes: int | None = None
56
+ download_url: str | None = None
57
+ expires_at: datetime | None = None
58
+ checksum: str | None = None
59
+ checksum_algorithm: str = "sha256"
60
+ role: Literal["reflectance", "scl", "cloud_mask", "provenance"] | None = None
61
+
62
+
63
+ class Job(_Model):
64
+ id: str = Field(validation_alias="job_id", serialization_alias="job_id")
65
+ status: str
66
+ progress: float | None = None
67
+ input_scene_id: str | None = None
68
+ model: str | None = None
69
+ model_id: str | None = None
70
+ model_version: str | None = None
71
+ bbox: list[float] | None = None
72
+ requested_bands: list[str] = Field(default_factory=list)
73
+ reserved_credits: int | None = None
74
+ charged_credits: int | None = None
75
+ quoted_credits: int | None = None
76
+ created_at: datetime | None = None
77
+ started_at: datetime | None = None
78
+ completed_at: datetime | None = None
79
+ error_code: str | None = None
80
+ error_message: str | None = None
81
+ outputs: list[JobOutput] = Field(default_factory=list)
82
+
83
+ @property
84
+ def job_id(self) -> str:
85
+ return self.id
86
+
87
+
88
+ class CreditBalance(_Model):
89
+ available: int = 0
90
+ reserved: int = 0
91
+ total: int | None = None
92
+ credit_lots: list[dict[str, Any]] = Field(default_factory=list)
93
+ next_expiry: dict[str, Any] | None = None
94
+
95
+
96
+ class CreditTransaction(_Model):
97
+ id: str
98
+ amount: int
99
+ transaction_type: str
100
+ created_at: datetime | None = None
101
+ job_id: str | None = None
102
+ payment_id: str | None = None
103
+ metadata: dict[str, Any] = Field(default_factory=dict)
104
+
105
+
106
+ class AccountSummary(_Model):
107
+ available_credits: int = 0
108
+ reserved_credits: int = 0
109
+ total_credits: int = 0
110
+ processed_area_km2: float = 0.0
111
+ active_jobs: int = 0
112
+ completed_jobs: int = 0
113
+ worker_available: bool = False
114
+
115
+
116
+ class SavedAOI(_Model):
117
+ id: str
118
+ name: str
119
+ description: str = ""
120
+ bbox: list[float]
121
+ area_km2: float
122
+ created_at: datetime | None = None
123
+ updated_at: datetime | None = None
124
+
125
+
126
+ class SceneSearchResult(_Model):
127
+ scene_id: str
128
+ acquired_at: datetime
129
+ cloud_cover: float | None = None
130
+
131
+
132
+ class SceneSearchResponse(_Model):
133
+ selected: SceneSearchResult
134
+ candidates: list[SceneSearchResult] = Field(default_factory=list)
135
+ target_date: date
136
+ searched_start: datetime
137
+ searched_end: datetime
138
+ cloud_cover_scope: Literal["scene"]
139
+ selection: Literal["nearest", "clearest"]
140
+
141
+
142
+ class NotificationPreferences(_Model):
143
+ job_completed: bool = True
144
+ job_failed: bool = True
145
+
146
+
147
+ class APIKey(_Model):
148
+ id: str = Field(validation_alias=AliasChoices("id", "key_id"), serialization_alias="id")
149
+ name: str
150
+ key_prefix: str
151
+ created_at: datetime | None = None
152
+ last_used_at: datetime | None = None
153
+ revoked_at: datetime | None = None
154
+
155
+
156
+ class APIKeyCreated(APIKey):
157
+ key: str = Field(validation_alias=AliasChoices("key", "secret"), repr=False)
158
+
159
+ def __repr__(self) -> str:
160
+ return f"APIKeyCreated(id={self.id!r}, name={self.name!r}, key_prefix={self.key_prefix!r})"
161
+
162
+
163
+ class Account(_Model):
164
+ id: str | None = None
165
+ email: str | None = None
166
+ display_name: str | None = None
167
+ created_at: datetime | None = None
168
+
169
+
170
+ class Payment(_Model):
171
+ id: str
172
+ amount: int
173
+ credits: int
174
+ currency: str
175
+ status: str
176
+ created_at: datetime | None = None
177
+
178
+
179
+ class CheckoutSession(_Model):
180
+ checkout_url: str
181
+ session_id: str
182
+
183
+
184
+ T = TypeVar("T", bound=BaseModel)
185
+
186
+
187
+ class Page(BaseModel, Generic[T]):
188
+ """A paginated API response; supports both common backend envelope shapes."""
189
+
190
+ model_config = ConfigDict(extra="allow")
191
+ items: list[T] = Field(default_factory=list)
192
+ total: int | None = None
193
+ offset: int = 0
194
+ limit: int | None = None
195
+ next_cursor: str | None = None
196
+ has_more: bool = False
197
+
198
+
199
+ def parse_page(
200
+ data: Any, item_type: type[T], *, offset: int = 0, limit: int | None = None
201
+ ) -> Page[T]:
202
+ """Normalize either an envelope or a plain list into a page."""
203
+ if isinstance(data, list):
204
+ return Page[T](
205
+ items=[item_type.model_validate(item) for item in data], offset=offset, limit=limit
206
+ )
207
+ raw_values = data.get("items", data.get("data", [])) if isinstance(data, dict) else []
208
+ values = raw_values if isinstance(raw_values, list) else []
209
+ return Page[T](
210
+ items=[item_type.model_validate(item) for item in values],
211
+ total=data.get("total") if isinstance(data, dict) else None,
212
+ offset=offset,
213
+ limit=limit,
214
+ next_cursor=data.get("next_cursor") if isinstance(data, dict) else None,
215
+ has_more=(
216
+ bool(data.get("has_more", False))
217
+ or (isinstance(data.get("total"), int) and offset + len(values) < data["total"])
218
+ )
219
+ if isinstance(data, dict)
220
+ else False,
221
+ )
hypersr/py.typed ADDED
File without changes
@@ -0,0 +1,162 @@
1
+ Metadata-Version: 2.5
2
+ Name: hypersr
3
+ Version: 0.1.0
4
+ Summary: Typed Python client for the HyperSR multispectral super-resolution API.
5
+ Project-URL: Homepage, https://hypersr.com
6
+ Project-URL: Documentation, https://github.com/HyperalisLabs/hypersr/blob/main/packages/sdk-python/README.md
7
+ Project-URL: Repository, https://github.com/HyperalisLabs/hypersr
8
+ Project-URL: Issues, https://github.com/HyperalisLabs/hypersr/issues
9
+ Author: Hyperalis Labs
10
+ License-Expression: LicenseRef-Proprietary
11
+ Keywords: api-client,geospatial,satellite,sentinel-2,super-resolution
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Intended Audience :: Science/Research
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3 :: Only
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Programming Language :: Python :: 3.13
21
+ Classifier: Programming Language :: Python :: 3.14
22
+ Classifier: Typing :: Typed
23
+ Requires-Python: >=3.11
24
+ Requires-Dist: httpx<1,>=0.27
25
+ Requires-Dist: pydantic<3,>=2.7
26
+ Provides-Extra: dev
27
+ Requires-Dist: mypy<2,>=1.11; extra == 'dev'
28
+ Requires-Dist: pytest-cov<6,>=5; extra == 'dev'
29
+ Requires-Dist: pytest<10,>=9.0.3; extra == 'dev'
30
+ Requires-Dist: ruff<1,>=0.6; extra == 'dev'
31
+ Provides-Extra: rasterio
32
+ Requires-Dist: rasterio<2,>=1.3; extra == 'rasterio'
33
+ Description-Content-Type: text/markdown
34
+
35
+ # HyperSR Python SDK
36
+
37
+ `hypersr` is a typed, synchronous Python client for the HyperSR asynchronous
38
+ Sentinel-2 super-resolution API. It requires Python 3.11 or newer.
39
+
40
+ ## Install
41
+
42
+ ```bash
43
+ python -m pip install hypersr
44
+ # or, in a uv-managed project:
45
+ uv add hypersr
46
+ ```
47
+
48
+ Set an API key through the environment or a secret manager:
49
+
50
+ ```bash
51
+ export HYPERSR_API_KEY="hs_live_..."
52
+ export HYPERSR_SCENE_ID="<provider scene identifier>"
53
+ export HYPERSR_BBOX='[2.10, 41.30, 2.11, 41.31]'
54
+ ```
55
+
56
+ The default endpoint is `https://api.hypersr.com/v1`. Pass `base_url` to use a
57
+ local or staging API, for example `HyperSR(api_key=key,
58
+ base_url="http://localhost:8000/v1")`.
59
+ Replace the example bounding box with `[west, south, east, north]` coordinates
60
+ covered by your selected scene. Installing the client does not activate the
61
+ hosted service; a reachable API and an account with an API key are required.
62
+
63
+ ## Discover, quote, submit, and poll
64
+
65
+ The server owns model availability and pricing. Discover enabled models first,
66
+ then request a quote for a provider scene and WGS84 bounding box. A quote
67
+ contains integer `required_credits`; the client never calculates or submits a
68
+ billable amount. Confirmation is an explicit `jobs.submit` call using the
69
+ quote ID and an idempotency key.
70
+
71
+ ```python
72
+ import json
73
+ import os
74
+ from uuid import uuid4
75
+
76
+ from hypersr import HyperSR, HyperSRError
77
+
78
+ with HyperSR(
79
+ os.environ["HYPERSR_API_KEY"],
80
+ base_url=os.environ.get("HYPERSR_BASE_URL", "https://api.hypersr.com/v1"),
81
+ ) as client:
82
+ bbox = json.loads(os.environ["HYPERSR_BBOX"])
83
+ models = client.models()
84
+ model = next(item for item in models if item.slug == "hypersr_v1" and item.enabled)
85
+ quote = client.jobs.quote(
86
+ scene_id=os.environ["HYPERSR_SCENE_ID"],
87
+ bbox=bbox,
88
+ model=model.slug,
89
+ )
90
+ print(f"quote {quote.id}: {quote.required_credits} internal units")
91
+ try:
92
+ job = client.jobs.submit(quote_id=quote.id, idempotency_key=f"quickstart-{uuid4()}")
93
+ result = client.jobs.wait(job.id, timeout=1800)
94
+ except HyperSRError as exc:
95
+ print(f"HyperSR request failed: {exc}")
96
+ else:
97
+ print(result.status, result.error_code, result.error_message)
98
+ ```
99
+
100
+ `wait` returns all service terminal outcomes: `completed`, `failed`, and
101
+ `cancelled`. It raises `hypersr.TimeoutError` when its deadline expires. A
102
+ failed or cancelled queued job does not consume the reserved processing
103
+ credits. One displayed credit equals **1,000 internal units**; for example,
104
+ `client.credits().available / 1000` gives the displayed balance. Credit expiry
105
+ is available through `credit_lots` and `next_expiry` on the balance response.
106
+
107
+ ## Download the product bundle
108
+
109
+ Completed jobs expose four typed artifacts: `reflectance`, `scl`, `cloud_mask`,
110
+ and `provenance`. Each has its own signed URL and checksum. The URLs are
111
+ short-lived bearer capabilities; do not log or share them.
112
+
113
+ ```python
114
+ import os
115
+ from pathlib import Path
116
+
117
+ from hypersr import HyperSR
118
+
119
+ with HyperSR(
120
+ os.environ["HYPERSR_API_KEY"],
121
+ base_url=os.environ.get("HYPERSR_BASE_URL", "https://api.hypersr.com/v1"),
122
+ ) as client:
123
+ job = client.jobs.get(os.environ["HYPERSR_JOB_ID"])
124
+ if job.status == "completed":
125
+ output_dir = Path("hypersr-output")
126
+ for role in ("reflectance", "scl", "cloud_mask", "provenance"):
127
+ suffix = ".json" if role == "provenance" else ".tif"
128
+ client.jobs.download_role(job.id, role, output_dir / f"{role}{suffix}")
129
+ ```
130
+
131
+ Set `HYPERSR_JOB_ID` to the ID returned by submission. Downloads use a separate
132
+ HTTP client without the API key, stream to a temporary file, verify available
133
+ size/SHA-256 metadata and replace the destination only after success.
134
+
135
+ Rasterio is optional. Install `hypersr[rasterio]` to inspect a downloaded
136
+ reflectance COG; see `examples/rasterio_metadata.py`.
137
+
138
+ ## Retries, errors, and service limits
139
+
140
+ Safe reads retry transient HTTP failures. Mutations retry only when an
141
+ idempotency key is present and the server operation supports replay; reuse the
142
+ same key when retrying a submission. Key creation and saved-area creation are
143
+ never automatically retried because their secrets/results cannot be replayed.
144
+ `HyperSRError` is the common exception, with typed `APIError` subclasses for
145
+ authentication, validation, not-found, conflict, and rate-limit responses.
146
+ Retries are bounded (`max_retries=2` by default), and each `wait` call has a
147
+ deadline.
148
+
149
+ The service validates scene identifiers, WGS84 boxes, supported bands, model
150
+ availability, quote expiry, area and queue limits. It may reject a well-formed
151
+ request when a model or provider scene is unavailable. The initial release is
152
+ asynchronous and supports Sentinel-2 Level-2A scenes covered by an enabled
153
+ model; a 2.5 m output grid is reconstructed output spacing, not a native 2.5 m
154
+ observation. See the repository API guide for the current contract and
155
+ `examples/` for runnable scripts.
156
+
157
+ The client also exposes saved AOIs (`aois`, `get_aoi`, `create_aoi`,
158
+ `update_aoi`, `delete_aoi`), notification preferences, account summaries,
159
+ server-configured billing packages, and filtered/paginated job history.
160
+ Use `client.scenes.search(bbox=bbox, target_date="2026-11-01")` to discover
161
+ provider acquisitions before requesting a quote. Search returns a selected
162
+ scene plus candidates and does not create a job or reserve credits.
@@ -0,0 +1,9 @@
1
+ hypersr/__init__.py,sha256=Z2Jk4QEIvhB6WExwSudFymwbzuLAw4AkGHPKNBO1jtA,1221
2
+ hypersr/_version.py,sha256=5_7LsFmZUGzEAaaDVLwS25PP7rA4eV3CJsza3TguvPI,104
3
+ hypersr/client.py,sha256=XRpQzrZlYvXBnscJXsjSsV0BpS5wtLMT4_WEz-UvmDc,21528
4
+ hypersr/exceptions.py,sha256=M5kQBXz7LEh_n0hM8h1DRX8kXgv3bhPIWsUgjRlZ4zg,1875
5
+ hypersr/models.py,sha256=YbhitImhP3X_VS0wCi9Tes3OcISQeMb1P3quqarvLQE,6051
6
+ hypersr/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
7
+ hypersr-0.1.0.dist-info/METADATA,sha256=cMLG2wI7H3IRFfSx7dTbcJ8AuYm-6evMAA3lJR1ItWo,6833
8
+ hypersr-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
9
+ hypersr-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any