astro96-api 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.
Files changed (42) hide show
  1. astro96_api/__init__.py +40 -0
  2. astro96_api/_client.py +577 -0
  3. astro96_api/_errors.py +62 -0
  4. astro96_api/_generated/__init__.py +1 -0
  5. astro96_api/_generated/client.py +901 -0
  6. astro96_api/_generated/families/__init__.py +1 -0
  7. astro96_api/_generated/families/ai.py +780 -0
  8. astro96_api/_generated/families/bnn.py +1087 -0
  9. astro96_api/_generated/families/chinese.py +155 -0
  10. astro96_api/_generated/families/dashas.py +1138 -0
  11. astro96_api/_generated/families/doshas_yogas.py +4180 -0
  12. astro96_api/_generated/families/face_reading.py +1281 -0
  13. astro96_api/_generated/families/festivals_muhurta.py +657 -0
  14. astro96_api/_generated/families/human_design.py +390 -0
  15. astro96_api/_generated/families/jaimini.py +985 -0
  16. astro96_api/_generated/families/kp.py +678 -0
  17. astro96_api/_generated/families/lal_kitab.py +893 -0
  18. astro96_api/_generated/families/location_astrology.py +1098 -0
  19. astro96_api/_generated/families/matching.py +1307 -0
  20. astro96_api/_generated/families/mundane.py +1037 -0
  21. astro96_api/_generated/families/numerology.py +1073 -0
  22. astro96_api/_generated/families/palmistry.py +978 -0
  23. astro96_api/_generated/families/panchang.py +4652 -0
  24. astro96_api/_generated/families/predictions.py +1995 -0
  25. astro96_api/_generated/families/remedies.py +497 -0
  26. astro96_api/_generated/families/reports.py +2033 -0
  27. astro96_api/_generated/families/strengths.py +2273 -0
  28. astro96_api/_generated/families/tajika.py +748 -0
  29. astro96_api/_generated/families/tarot.py +743 -0
  30. astro96_api/_generated/families/utilities.py +523 -0
  31. astro96_api/_generated/families/vastu.py +670 -0
  32. astro96_api/_generated/families/vedic_charts.py +3951 -0
  33. astro96_api/_generated/families/western.py +3245 -0
  34. astro96_api/_generated/schemas.py +5688 -0
  35. astro96_api/_types.py +44 -0
  36. astro96_api/_version.py +1 -0
  37. astro96_api/_webhooks.py +58 -0
  38. astro96_api/py.typed +0 -0
  39. astro96_api-0.1.0.dist-info/METADATA +147 -0
  40. astro96_api-0.1.0.dist-info/RECORD +42 -0
  41. astro96_api-0.1.0.dist-info/WHEEL +4 -0
  42. astro96_api-0.1.0.dist-info/licenses/LICENSE +24 -0
@@ -0,0 +1,40 @@
1
+ """Official Python client for the 96Astro API.
2
+
3
+ >>> from astro96_api import Astro96Client
4
+ >>> astro = Astro96Client() # reads ASTRO_API_KEY
5
+ >>> res = astro.vedic_charts.planet_positions(
6
+ ... {"datetime": "1990-10-18T14:30:00", "timezone": "Asia/Kolkata", "latitude": 28.6139, "longitude": 77.209}
7
+ ... )
8
+ """
9
+
10
+ from ._client import AsyncAstro96Client, Astro96Client, idempotency_key, parse_rate_limit, parse_retry_after, should_retry
11
+ from ._errors import ApiConnectionError, ApiError, Astro96Error, JobError
12
+ from ._generated import schemas
13
+ from ._generated.client import API_VERSION, CAPABILITY_FAMILIES, DEFAULT_BASE_URL, PdfCapability
14
+ from ._types import ApiResponse, RateLimitInfo, RequestOptions
15
+ from ._version import __version__
16
+ from ._webhooks import WebhookSignatureError, verify_webhook
17
+
18
+ __all__ = [
19
+ "API_VERSION",
20
+ "CAPABILITY_FAMILIES",
21
+ "DEFAULT_BASE_URL",
22
+ "ApiConnectionError",
23
+ "ApiError",
24
+ "ApiResponse",
25
+ "Astro96Client",
26
+ "Astro96Error",
27
+ "AsyncAstro96Client",
28
+ "JobError",
29
+ "PdfCapability",
30
+ "RateLimitInfo",
31
+ "RequestOptions",
32
+ "WebhookSignatureError",
33
+ "__version__",
34
+ "idempotency_key",
35
+ "parse_rate_limit",
36
+ "parse_retry_after",
37
+ "schemas",
38
+ "should_retry",
39
+ "verify_webhook",
40
+ ]
astro96_api/_client.py ADDED
@@ -0,0 +1,577 @@
1
+ """The hand-written transport: base URL, authentication, timeout, retries with backoff, idempotency
2
+ keys, error mapping, rate-limit headers and the PDF job helpers. Generated code calls ``_call()``."""
3
+
4
+ import asyncio
5
+ import email.utils
6
+ import json as _json
7
+ import os
8
+ import random
9
+ import re
10
+ import time
11
+ import uuid
12
+ from dataclasses import dataclass
13
+ from typing import Any, Callable, Dict, Mapping, Optional, Union
14
+
15
+ import httpx
16
+ from typing_extensions import Literal, Unpack
17
+
18
+ from ._errors import ApiConnectionError, ApiError, Astro96Error, JobError
19
+ from ._generated.client import DEFAULT_BASE_URL, AsyncGeneratedFamilies, GeneratedFamilies
20
+ from ._generated.schemas import Branding
21
+ from ._types import ApiResponse, RateLimitInfo, RequestOptions
22
+ from ._version import __version__
23
+
24
+ _ABSOLUTE = re.compile(r"^https?://", re.I)
25
+
26
+
27
+ def idempotency_key() -> str:
28
+ """A new idempotency key (a random UUID). Generate one per logical operation and reuse it only to
29
+ retry that same operation: the API then replays the stored result and charges once."""
30
+ return str(uuid.uuid4())
31
+
32
+
33
+ def parse_rate_limit(headers: Mapping[str, str]) -> Optional[RateLimitInfo]:
34
+ def num(name: str) -> Optional[int]:
35
+ v = headers.get(name)
36
+ try:
37
+ return int(float(v)) if v not in (None, "") else None
38
+ except ValueError:
39
+ return None
40
+
41
+ info = RateLimitInfo(num("RateLimit-Limit"), num("RateLimit-Remaining"), num("RateLimit-Reset"))
42
+ return None if info.limit is None and info.remaining is None and info.reset is None else info
43
+
44
+
45
+ def parse_retry_after(headers: Mapping[str, str], now: Optional[float] = None) -> Optional[float]:
46
+ """``Retry-After`` in seconds (delta-seconds or an HTTP date), or None."""
47
+ v = headers.get("Retry-After")
48
+ if not v:
49
+ return None
50
+ v = v.strip()
51
+ try:
52
+ return max(0.0, float(v))
53
+ except ValueError:
54
+ pass
55
+ try:
56
+ at = email.utils.parsedate_to_datetime(v).timestamp()
57
+ except (TypeError, ValueError):
58
+ return None
59
+ return max(0.0, at - (time.time() if now is None else now))
60
+
61
+
62
+ def should_retry(err: ApiError, method: str, key: Optional[str]) -> bool:
63
+ """429 ``rate_limited`` and 503 never ran the calculation, so they are always safe to retry. Other
64
+ ``retryable`` errors (500, 502, 504, an idempotency key still in progress) are retried only when the
65
+ request carries an idempotency key, so a retry can never be charged twice. ``quota_exhausted``,
66
+ ``spend_cap_reached`` and ``project_budget_exceeded`` (also 429) are never retried."""
67
+ if err.code in ("quota_exhausted", "spend_cap_reached", "project_budget_exceeded"):
68
+ return False
69
+ if err.status in (429, 503):
70
+ return True
71
+ return err.retryable and (method == "GET" or bool(key))
72
+
73
+
74
+ @dataclass
75
+ class _Prepared:
76
+ method: str
77
+ url: str
78
+ headers: Dict[str, str]
79
+ content: Optional[bytes]
80
+ key: Optional[str]
81
+ timeout: float
82
+ max_retries: int
83
+ expect: str
84
+
85
+
86
+ class _BaseClient:
87
+ def __init__(
88
+ self,
89
+ api_key: Optional[str] = None,
90
+ *,
91
+ base_url: Optional[str] = None,
92
+ auth: Literal["bearer", "x-api-key"] = "bearer",
93
+ timeout: float = 60.0,
94
+ max_retries: int = 2,
95
+ max_retry_delay: float = 30.0,
96
+ auto_idempotency: bool = True,
97
+ headers: Optional[Dict[str, str]] = None,
98
+ ) -> None:
99
+ key = api_key or os.environ.get("ASTRO_API_KEY")
100
+ if not key:
101
+ raise Astro96Error("No API key: pass api_key=... or set the ASTRO_API_KEY environment variable.")
102
+ if auth not in ("bearer", "x-api-key"):
103
+ raise ValueError("auth must be 'bearer' or 'x-api-key'")
104
+ self._api_key = key
105
+ self.base_url = (base_url or DEFAULT_BASE_URL).rstrip("/")
106
+ self._auth = auth
107
+ self._timeout = timeout
108
+ self._max_retries = max(0, max_retries)
109
+ self._max_retry_delay = max_retry_delay
110
+ self._auto_idempotency = auto_idempotency
111
+ self._headers = dict(headers or {})
112
+
113
+ def _prepare(self, method: str, path: str, body: Any, auth: bool, expect: str, options: RequestOptions) -> _Prepared:
114
+ url = path if _ABSOLUTE.match(path) else f"{self.base_url}/{path.lstrip('/')}"
115
+ key = options.get("idempotency_key")
116
+ if key is None and method == "POST" and self._auto_idempotency:
117
+ key = idempotency_key()
118
+ headers = {
119
+ "Accept": "application/pdf, application/json" if expect == "bytes" else "application/json",
120
+ "User-Agent": f"96astro-python/{__version__}",
121
+ **self._headers,
122
+ }
123
+ if auth:
124
+ if self._auth == "x-api-key":
125
+ headers["X-API-Key"] = self._api_key
126
+ else:
127
+ headers["Authorization"] = f"Bearer {self._api_key}"
128
+ content = None
129
+ if body is not None:
130
+ headers["Content-Type"] = "application/json"
131
+ content = _json.dumps(body, separators=(",", ":"), ensure_ascii=False).encode("utf-8")
132
+ if key:
133
+ headers["Idempotency-Key"] = key
134
+ headers.update(options.get("headers") or {})
135
+ return _Prepared(
136
+ method=method,
137
+ url=url,
138
+ headers=headers,
139
+ content=content,
140
+ key=key,
141
+ timeout=options.get("timeout", self._timeout),
142
+ max_retries=max(0, options.get("max_retries", self._max_retries)),
143
+ expect=expect,
144
+ )
145
+
146
+ def _backoff(self, attempt: int, retry_after: Optional[float]) -> Optional[float]:
147
+ if retry_after is not None:
148
+ return None if retry_after > self._max_retry_delay else retry_after
149
+ cap: float = min(self._max_retry_delay, 0.5 * (2.0**attempt))
150
+ return cap / 2 + random.random() * cap / 2 # exponential backoff with jitter
151
+
152
+ def _retry_after_error(self, attempt: int, err: ApiError, p: _Prepared) -> Optional[float]:
153
+ if attempt >= p.max_retries or not should_retry(err, p.method, p.key):
154
+ return None
155
+ return self._backoff(attempt, err.retry_after)
156
+
157
+ def _retry_after_connection(self, attempt: int, p: _Prepared) -> Optional[float]:
158
+ # Without an idempotency key a POST may have run on the server: never repeat it blindly.
159
+ if attempt >= p.max_retries or not (p.method == "GET" or p.key):
160
+ return None
161
+ return self._backoff(attempt, None)
162
+
163
+ @staticmethod
164
+ def _success(resp: httpx.Response, p: _Prepared) -> ApiResponse[Any]:
165
+ rate_limit = parse_rate_limit(resp.headers)
166
+ request_id = resp.headers.get("X-Request-Id")
167
+ if p.expect == "bytes":
168
+ return ApiResponse(resp.content, {}, resp.status_code, request_id, rate_limit, False, p.key, resp.headers)
169
+ body = resp.json()
170
+ meta = body.get("meta") or {}
171
+ return ApiResponse(
172
+ data=body.get("data"),
173
+ meta=meta,
174
+ status=resp.status_code,
175
+ request_id=request_id or meta.get("request_id"),
176
+ rate_limit=rate_limit,
177
+ replayed=resp.headers.get("Idempotent-Replayed") == "true" or meta.get("replayed") is True,
178
+ idempotency_key=p.key,
179
+ headers=resp.headers,
180
+ )
181
+
182
+ @staticmethod
183
+ def _error(resp: httpx.Response) -> ApiError:
184
+ text = resp.text
185
+ try:
186
+ body: Any = _json.loads(text) if text else None
187
+ except ValueError:
188
+ body = text
189
+ e: Dict[str, Any] = {}
190
+ if isinstance(body, dict) and isinstance(body.get("error"), dict):
191
+ e = body["error"]
192
+ status = resp.status_code
193
+ default_code = "rate_limited" if status == 429 else "unavailable" if status >= 500 else "http_error"
194
+
195
+ def s(v: Any) -> Optional[str]:
196
+ return v if isinstance(v, str) else None
197
+
198
+ retryable = e.get("retryable")
199
+ return ApiError(
200
+ status=status,
201
+ code=s(e.get("code")) or default_code,
202
+ message=s(e.get("message")) or resp.reason_phrase or f"HTTP {status}",
203
+ field=s(e.get("field")),
204
+ retryable=retryable if isinstance(retryable, bool) else status in (429, 502, 503, 504),
205
+ request_id=s(e.get("request_id")) or resp.headers.get("X-Request-Id"),
206
+ retry_after=parse_retry_after(resp.headers),
207
+ rate_limit=parse_rate_limit(resp.headers),
208
+ headers=resp.headers,
209
+ body=body,
210
+ )
211
+
212
+ @staticmethod
213
+ def _pdf_body(capability: str, input: Dict[str, Any], branding: Optional[Branding], language: Optional[str]) -> Dict[str, Any]:
214
+ body: Dict[str, Any] = {"capability": capability, "input": input}
215
+ if branding is not None:
216
+ body["branding"] = branding
217
+ if language is not None:
218
+ body["language"] = language
219
+ return body
220
+
221
+
222
+ class Astro96Client(_BaseClient, GeneratedFamilies):
223
+ """The 96Astro API client (synchronous).
224
+
225
+ >>> astro = Astro96Client(api_key="sk_test_...")
226
+ >>> res = astro.vedic_charts.planet_positions(
227
+ ... {"datetime": "1990-10-18T14:30:00", "timezone": "Asia/Kolkata", "latitude": 28.6139, "longitude": 77.209}
228
+ ... )
229
+ >>> res.data["planets"][0]["sign"]
230
+
231
+ Pass ``http_client=httpx.Client(...)`` to control proxies, connection pooling or transports.
232
+ """
233
+
234
+ def __init__(
235
+ self,
236
+ api_key: Optional[str] = None,
237
+ *,
238
+ base_url: Optional[str] = None,
239
+ auth: Literal["bearer", "x-api-key"] = "bearer",
240
+ timeout: float = 60.0,
241
+ max_retries: int = 2,
242
+ max_retry_delay: float = 30.0,
243
+ auto_idempotency: bool = True,
244
+ headers: Optional[Dict[str, str]] = None,
245
+ http_client: Optional[httpx.Client] = None,
246
+ ) -> None:
247
+ super().__init__(
248
+ api_key,
249
+ base_url=base_url,
250
+ auth=auth,
251
+ timeout=timeout,
252
+ max_retries=max_retries,
253
+ max_retry_delay=max_retry_delay,
254
+ auto_idempotency=auto_idempotency,
255
+ headers=headers,
256
+ )
257
+ self._owns_http = http_client is None
258
+ self._http = http_client or httpx.Client()
259
+ self._init_families()
260
+
261
+ def close(self) -> None:
262
+ if self._owns_http:
263
+ self._http.close()
264
+
265
+ def __enter__(self) -> "Astro96Client":
266
+ return self
267
+
268
+ def __exit__(self, *exc: Any) -> None:
269
+ self.close()
270
+
271
+ def request(
272
+ self, method: str, path: str, *, json: Any = None, auth: bool = True, expect: str = "json", **options: Unpack[RequestOptions]
273
+ ) -> ApiResponse[Any]:
274
+ """Low-level request; returns the parsed envelope, or the raw bytes with ``expect="bytes"``."""
275
+ p = self._prepare(method, path, json, auth, expect, options)
276
+ attempt = 0
277
+ while True:
278
+ try:
279
+ resp = self._http.request(p.method, p.url, headers=p.headers, content=p.content, timeout=p.timeout)
280
+ except httpx.TimeoutException as e:
281
+ delay = self._retry_after_connection(attempt, p)
282
+ if delay is None:
283
+ raise ApiConnectionError(f"request timed out after {p.timeout} s", timed_out=True) from e
284
+ except httpx.TransportError as e:
285
+ delay = self._retry_after_connection(attempt, p)
286
+ if delay is None:
287
+ raise ApiConnectionError(f"connection failed: {e}") from e
288
+ else:
289
+ if resp.is_success:
290
+ return self._success(resp, p)
291
+ err = self._error(resp)
292
+ delay = self._retry_after_error(attempt, err, p)
293
+ if delay is None:
294
+ raise err
295
+ time.sleep(delay)
296
+ attempt += 1
297
+
298
+ def _call(self, path: str, input: Any, **options: Unpack[RequestOptions]) -> ApiResponse[Any]:
299
+ return self.request("POST", path, json=input if input is not None else {}, **options)
300
+
301
+ # ------------------------------------------------------------------ PDF jobs
302
+
303
+ def create_audio_job(
304
+ self,
305
+ capability: str,
306
+ input: Dict[str, Any],
307
+ *,
308
+ language: Optional[str] = None,
309
+ minutes: Optional[int] = None,
310
+ tone: Optional[str] = None,
311
+ voice: Optional[str] = None,
312
+ listener_name: Optional[str] = None,
313
+ **options: Unpack[RequestOptions],
314
+ ) -> ApiResponse[Dict[str, Any]]:
315
+ """Queue a narrated MP3 of a report capability (``POST /v1/jobs/audio``). Answers 202 with the job."""
316
+ extra = {"language": language, "minutes": minutes, "tone": tone, "voice": voice, "listener_name": listener_name}
317
+ body = {"capability": capability, "input": input, **{k: v for k, v in extra.items() if v is not None}}
318
+ return self.request("POST", "/v1/jobs/audio", json=body, **options)
319
+
320
+ def create_pdf_job(
321
+ self,
322
+ capability: str,
323
+ input: Dict[str, Any],
324
+ *,
325
+ branding: Optional[Branding] = None,
326
+ language: Optional[str] = None,
327
+ **options: Unpack[RequestOptions],
328
+ ) -> ApiResponse[Dict[str, Any]]:
329
+ """Queue a PDF of a report capability (``POST /v1/jobs/pdf``). Answers 202 with the job."""
330
+ return self.request("POST", "/v1/jobs/pdf", json=self._pdf_body(capability, input, branding, language), **options)
331
+
332
+ def create_reading_pdf_job(
333
+ self,
334
+ capability: str,
335
+ reading: Dict[str, Any],
336
+ *,
337
+ branding: Optional[Branding] = None,
338
+ language: Optional[str] = None,
339
+ **options: Unpack[RequestOptions],
340
+ ) -> ApiResponse[Dict[str, Any]]:
341
+ """Queue a PDF of a palm or face reading you already have. No photo is sent, and it costs only the PDF."""
342
+ body = {**self._pdf_body(capability, {}, branding, language), "reading": reading}
343
+ return self.request("POST", "/v1/jobs/pdf", json=body, **options)
344
+
345
+ def get_job(self, job_id: str, **options: Unpack[RequestOptions]) -> ApiResponse[Dict[str, Any]]:
346
+ """Poll a job once (``GET /v1/jobs/{id}``). Free."""
347
+ return self.request("GET", f"/v1/jobs/{job_id}", **options)
348
+
349
+ def wait_for_job(
350
+ self,
351
+ job: Union[str, Dict[str, Any]],
352
+ *,
353
+ interval: float = 2.0,
354
+ max_interval: float = 10.0,
355
+ timeout: float = 300.0,
356
+ on_poll: Optional[Callable[[Dict[str, Any]], None]] = None,
357
+ ) -> Dict[str, Any]:
358
+ """Poll until the job is final. Returns the succeeded job (``download_url`` is set); raises
359
+ JobError when it failed, expired or did not finish within ``timeout`` seconds."""
360
+ job_id = job if isinstance(job, str) else job["id"]
361
+ deadline = time.monotonic() + timeout
362
+ while True:
363
+ data = self.get_job(job_id).data
364
+ if on_poll:
365
+ on_poll(data)
366
+ if data["status"] == "succeeded":
367
+ return data
368
+ if data["status"] in ("failed", "expired"):
369
+ raise JobError(data, data["status"])
370
+ if time.monotonic() + interval > deadline:
371
+ raise JobError(data, "timeout")
372
+ time.sleep(interval)
373
+ interval = min(max_interval, interval * 1.5)
374
+
375
+ def download_file(self, source: Union[str, Dict[str, Any]], **options: Unpack[RequestOptions]) -> bytes:
376
+ """Download a succeeded job's PDF. Pass the job (or its id) so an expired link
377
+ (``410 link_expired``) can be refreshed by polling once; a bare URL is fetched as is."""
378
+ job: Optional[Dict[str, Any]]
379
+ if isinstance(source, str) and not _ABSOLUTE.match(source):
380
+ job = self.get_job(source, **options).data
381
+ else:
382
+ job = None if isinstance(source, str) else source
383
+ url = job.get("download_url") if job else source
384
+ if not isinstance(url, str) or not url:
385
+ raise Astro96Error(f"job {job and job.get('id')} has no download_url yet (status {job and job.get('status')})")
386
+ try:
387
+ return self.request("GET", url, auth=False, expect="bytes", **options).data # type: ignore[no-any-return]
388
+ except ApiError as e:
389
+ if e.code != "link_expired" or job is None:
390
+ raise
391
+ fresh = self.get_job(job["id"], **options).data.get("download_url")
392
+ if not fresh:
393
+ raise
394
+ return self.request("GET", fresh, auth=False, expect="bytes", **options).data # type: ignore[no-any-return]
395
+
396
+ def render_pdf(
397
+ self,
398
+ capability: str,
399
+ input: Dict[str, Any],
400
+ *,
401
+ branding: Optional[Branding] = None,
402
+ idempotency_key: Optional[str] = None,
403
+ timeout: float = 300.0,
404
+ ) -> bytes:
405
+ """create_pdf_job + wait_for_job + download_file in one call; returns the PDF bytes."""
406
+ opts: RequestOptions = {"idempotency_key": idempotency_key} if idempotency_key else {}
407
+ job = self.create_pdf_job(capability, input, branding=branding, **opts).data
408
+ return self.download_file(self.wait_for_job(job, timeout=timeout))
409
+
410
+
411
+ class AsyncAstro96Client(_BaseClient, AsyncGeneratedFamilies):
412
+ """The 96Astro API client (asyncio). Same options and methods as Astro96Client, awaited.
413
+
414
+ >>> async with AsyncAstro96Client(api_key="sk_test_...") as astro:
415
+ ... res = await astro.panchang.daily_panchang({...})
416
+ """
417
+
418
+ def __init__(
419
+ self,
420
+ api_key: Optional[str] = None,
421
+ *,
422
+ base_url: Optional[str] = None,
423
+ auth: Literal["bearer", "x-api-key"] = "bearer",
424
+ timeout: float = 60.0,
425
+ max_retries: int = 2,
426
+ max_retry_delay: float = 30.0,
427
+ auto_idempotency: bool = True,
428
+ headers: Optional[Dict[str, str]] = None,
429
+ http_client: Optional[httpx.AsyncClient] = None,
430
+ ) -> None:
431
+ super().__init__(
432
+ api_key,
433
+ base_url=base_url,
434
+ auth=auth,
435
+ timeout=timeout,
436
+ max_retries=max_retries,
437
+ max_retry_delay=max_retry_delay,
438
+ auto_idempotency=auto_idempotency,
439
+ headers=headers,
440
+ )
441
+ self._owns_http = http_client is None
442
+ self._http = http_client or httpx.AsyncClient()
443
+ self._init_families()
444
+
445
+ async def close(self) -> None:
446
+ if self._owns_http:
447
+ await self._http.aclose()
448
+
449
+ async def __aenter__(self) -> "AsyncAstro96Client":
450
+ return self
451
+
452
+ async def __aexit__(self, *exc: Any) -> None:
453
+ await self.close()
454
+
455
+ async def request(
456
+ self, method: str, path: str, *, json: Any = None, auth: bool = True, expect: str = "json", **options: Unpack[RequestOptions]
457
+ ) -> ApiResponse[Any]:
458
+ """Low-level request; returns the parsed envelope, or the raw bytes with ``expect="bytes"``."""
459
+ p = self._prepare(method, path, json, auth, expect, options)
460
+ attempt = 0
461
+ while True:
462
+ try:
463
+ resp = await self._http.request(p.method, p.url, headers=p.headers, content=p.content, timeout=p.timeout)
464
+ except httpx.TimeoutException as e:
465
+ delay = self._retry_after_connection(attempt, p)
466
+ if delay is None:
467
+ raise ApiConnectionError(f"request timed out after {p.timeout} s", timed_out=True) from e
468
+ except httpx.TransportError as e:
469
+ delay = self._retry_after_connection(attempt, p)
470
+ if delay is None:
471
+ raise ApiConnectionError(f"connection failed: {e}") from e
472
+ else:
473
+ if resp.is_success:
474
+ return self._success(resp, p)
475
+ err = self._error(resp)
476
+ delay = self._retry_after_error(attempt, err, p)
477
+ if delay is None:
478
+ raise err
479
+ await asyncio.sleep(delay)
480
+ attempt += 1
481
+
482
+ async def _call(self, path: str, input: Any, **options: Unpack[RequestOptions]) -> ApiResponse[Any]:
483
+ return await self.request("POST", path, json=input if input is not None else {}, **options)
484
+
485
+ # ------------------------------------------------------------------ PDF jobs
486
+
487
+ async def create_audio_job(
488
+ self,
489
+ capability: str,
490
+ input: Dict[str, Any],
491
+ *,
492
+ language: Optional[str] = None,
493
+ minutes: Optional[int] = None,
494
+ tone: Optional[str] = None,
495
+ voice: Optional[str] = None,
496
+ listener_name: Optional[str] = None,
497
+ **options: Unpack[RequestOptions],
498
+ ) -> ApiResponse[Dict[str, Any]]:
499
+ """Queue a narrated MP3 of a report capability (``POST /v1/jobs/audio``). Answers 202 with the job."""
500
+ extra = {"language": language, "minutes": minutes, "tone": tone, "voice": voice, "listener_name": listener_name}
501
+ body = {"capability": capability, "input": input, **{k: v for k, v in extra.items() if v is not None}}
502
+ return await self.request("POST", "/v1/jobs/audio", json=body, **options)
503
+
504
+ async def create_pdf_job(
505
+ self,
506
+ capability: str,
507
+ input: Dict[str, Any],
508
+ *,
509
+ branding: Optional[Branding] = None,
510
+ language: Optional[str] = None,
511
+ **options: Unpack[RequestOptions],
512
+ ) -> ApiResponse[Dict[str, Any]]:
513
+ """Queue a PDF of a report capability (``POST /v1/jobs/pdf``). Answers 202 with the job."""
514
+ return await self.request("POST", "/v1/jobs/pdf", json=self._pdf_body(capability, input, branding, language), **options)
515
+
516
+ async def get_job(self, job_id: str, **options: Unpack[RequestOptions]) -> ApiResponse[Dict[str, Any]]:
517
+ """Poll a job once (``GET /v1/jobs/{id}``). Free."""
518
+ return await self.request("GET", f"/v1/jobs/{job_id}", **options)
519
+
520
+ async def wait_for_job(
521
+ self,
522
+ job: Union[str, Dict[str, Any]],
523
+ *,
524
+ interval: float = 2.0,
525
+ max_interval: float = 10.0,
526
+ timeout: float = 300.0,
527
+ on_poll: Optional[Callable[[Dict[str, Any]], None]] = None,
528
+ ) -> Dict[str, Any]:
529
+ """Poll until the job is final; see Astro96Client.wait_for_job."""
530
+ job_id = job if isinstance(job, str) else job["id"]
531
+ deadline = time.monotonic() + timeout
532
+ while True:
533
+ data = (await self.get_job(job_id)).data
534
+ if on_poll:
535
+ on_poll(data)
536
+ if data["status"] == "succeeded":
537
+ return data
538
+ if data["status"] in ("failed", "expired"):
539
+ raise JobError(data, data["status"])
540
+ if time.monotonic() + interval > deadline:
541
+ raise JobError(data, "timeout")
542
+ await asyncio.sleep(interval)
543
+ interval = min(max_interval, interval * 1.5)
544
+
545
+ async def download_file(self, source: Union[str, Dict[str, Any]], **options: Unpack[RequestOptions]) -> bytes:
546
+ """Download a succeeded job's PDF; see Astro96Client.download_file."""
547
+ job: Optional[Dict[str, Any]]
548
+ if isinstance(source, str) and not _ABSOLUTE.match(source):
549
+ job = (await self.get_job(source, **options)).data
550
+ else:
551
+ job = None if isinstance(source, str) else source
552
+ url = job.get("download_url") if job else source
553
+ if not isinstance(url, str) or not url:
554
+ raise Astro96Error(f"job {job and job.get('id')} has no download_url yet (status {job and job.get('status')})")
555
+ try:
556
+ return (await self.request("GET", url, auth=False, expect="bytes", **options)).data # type: ignore[no-any-return]
557
+ except ApiError as e:
558
+ if e.code != "link_expired" or job is None:
559
+ raise
560
+ fresh = (await self.get_job(job["id"], **options)).data.get("download_url")
561
+ if not fresh:
562
+ raise
563
+ return (await self.request("GET", fresh, auth=False, expect="bytes", **options)).data # type: ignore[no-any-return]
564
+
565
+ async def render_pdf(
566
+ self,
567
+ capability: str,
568
+ input: Dict[str, Any],
569
+ *,
570
+ branding: Optional[Branding] = None,
571
+ idempotency_key: Optional[str] = None,
572
+ timeout: float = 300.0,
573
+ ) -> bytes:
574
+ """create_pdf_job + wait_for_job + download_file in one call; returns the PDF bytes."""
575
+ opts: RequestOptions = {"idempotency_key": idempotency_key} if idempotency_key else {}
576
+ job = (await self.create_pdf_job(capability, input, branding=branding, **opts)).data
577
+ return await self.download_file(await self.wait_for_job(job, timeout=timeout))
astro96_api/_errors.py ADDED
@@ -0,0 +1,62 @@
1
+ from typing import Any, Dict, Mapping, Optional
2
+
3
+ from ._types import RateLimitInfo
4
+
5
+
6
+ class Astro96Error(Exception):
7
+ """Base class of every error this SDK raises."""
8
+
9
+
10
+ class ApiError(Astro96Error):
11
+ """The API answered with an error envelope (``{"error": {...}}``) or an unparseable non-2xx status.
12
+
13
+ Program against ``code``, which is stable; ``message`` is for people.
14
+ """
15
+
16
+ def __init__(
17
+ self,
18
+ *,
19
+ status: int,
20
+ code: str,
21
+ message: str,
22
+ field: Optional[str] = None,
23
+ retryable: bool = False,
24
+ request_id: Optional[str] = None,
25
+ retry_after: Optional[float] = None,
26
+ rate_limit: Optional[RateLimitInfo] = None,
27
+ headers: Optional[Mapping[str, str]] = None,
28
+ body: Any = None,
29
+ ) -> None:
30
+ suffix = f" (request {request_id})" if request_id else ""
31
+ super().__init__(f"{status} {code}: {message}{suffix}")
32
+ self.status = status
33
+ self.code = code
34
+ self.message = message
35
+ self.field = field
36
+ self.retryable = retryable
37
+ self.request_id = request_id
38
+ self.retry_after = retry_after
39
+ self.rate_limit = rate_limit
40
+ self.headers: Mapping[str, str] = headers or {}
41
+ self.body = body
42
+
43
+
44
+ class ApiConnectionError(Astro96Error):
45
+ """The request never got an HTTP response: DNS, TLS, a dropped connection or the client timeout."""
46
+
47
+ def __init__(self, message: str, *, timed_out: bool = False) -> None:
48
+ super().__init__(message)
49
+ self.timed_out = timed_out
50
+
51
+
52
+ class JobError(Astro96Error):
53
+ """A PDF job ended ``failed`` or ``expired``, or did not finish within the wait timeout."""
54
+
55
+ def __init__(self, job: Dict[str, Any], reason: str) -> None:
56
+ err = job.get("error") or {}
57
+ detail = f": {err.get('code')}" + (f" ({err.get('message')})" if err.get("message") else "") if err.get("code") else ""
58
+ msg = f"job {job.get('id')} is still {job.get('status')}" if reason == "timeout" else f"job {job.get('id')} {reason}{detail}"
59
+ super().__init__(msg)
60
+ self.job = job
61
+ #: "failed", "expired" or "timeout".
62
+ self.reason = reason
@@ -0,0 +1 @@
1
+ # Generated by tools/sdk/generate_python.py from packages/registry/openapi/v1.openapi.json. Do not edit.