importly 0.1.0__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.
@@ -0,0 +1,6 @@
1
+ .venv/
2
+ __pycache__/
3
+ .pytest_cache/
4
+ *.egg-info/
5
+ dist/
6
+ build/
importly-0.1.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Importly
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,143 @@
1
+ Metadata-Version: 2.5
2
+ Name: importly
3
+ Version: 0.1.0
4
+ Summary: Turn any video or audio link into files, transcripts and metadata from your Python app. Works from servers where downloads get blocked.
5
+ Project-URL: Homepage, https://www.importly.io/?utm_source=pypi&utm_medium=package&utm_campaign=guerrilla-2026-11
6
+ Project-URL: Documentation, https://www.importly.io/docs?utm_source=pypi&utm_medium=package&utm_campaign=guerrilla-2026-11
7
+ Project-URL: Repository, https://github.com/importly-io/importly-integrations/tree/main/python/importly
8
+ Project-URL: Issues, https://github.com/importly-io/importly-integrations/issues
9
+ Author-email: Importly <support@importly.io>
10
+ License-Expression: MIT
11
+ License-File: LICENSE
12
+ Keywords: api,audio,download,metadata,podcast,tiktok,transcript,video,youtube
13
+ Classifier: Development Status :: 4 - Beta
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Topic :: Multimedia :: Sound/Audio
17
+ Classifier: Topic :: Multimedia :: Video
18
+ Classifier: Typing :: Typed
19
+ Requires-Python: >=3.9
20
+ Requires-Dist: httpx<1,>=0.24
21
+ Provides-Extra: test
22
+ Requires-Dist: pytest-asyncio>=0.23; extra == 'test'
23
+ Requires-Dist: pytest>=7; extra == 'test'
24
+ Description-Content-Type: text/markdown
25
+
26
+ # importly
27
+
28
+ Turn any video or audio link into files, transcripts and metadata from your Python app.
29
+
30
+ Send a link from YouTube, TikTok, X, Instagram, a podcast or 1,000+ other sites, and get back the file, a timestamped transcript or the metadata. It works from servers and agent sandboxes, where downloads usually get blocked. Free to try, no card required: [get an API key](https://www.importly.io/login?mode=signup&utm_source=pypi&utm_medium=package&utm_campaign=guerrilla-2026-11).
31
+
32
+ ```bash
33
+ pip install importly
34
+ export IMPORTLY_API_KEY=...
35
+ ```
36
+
37
+ ## Transcript
38
+
39
+ ```python
40
+ from importly import Importly
41
+
42
+ client = Importly() # reads IMPORTLY_API_KEY
43
+
44
+ transcript = client.transcribe("https://www.youtube.com/watch?v=jNQXAC9IVRw")
45
+ print(transcript.text)
46
+ for segment in transcript.segments:
47
+ print(segment.start, segment.end, segment.text)
48
+
49
+ # Group segments into ~2-minute chunks for RAG, each with start/end times
50
+ for chunk in transcript.chunks(120):
51
+ print(chunk.start_timestamp, chunk.text[:80])
52
+ ```
53
+
54
+ By default the transcript comes from the media's captions. If there are none, `transcribe` raises `TranscriptionProviderRequiredError` with a `quote`; pass `provider="importly"` to use built-in speech-to-text, optionally with `max_cost_dollars`.
55
+
56
+ ## File
57
+
58
+ ```python
59
+ result = client.import_media(
60
+ "https://www.tiktok.com/@scout2015/video/6718335390845095173",
61
+ video_quality="720p",
62
+ max_cost_dollars=0.10,
63
+ )
64
+ print(result.media_url) # signed download link, valid for 7 days
65
+ ```
66
+
67
+ Audio only: `include_video=False`. Copy straight to your own S3-compatible bucket: `store=True` (set up your bucket in the dashboard first).
68
+
69
+ ## Metadata
70
+
71
+ ```python
72
+ preview = client.basic_metadata(url) # title, duration, thumbnail
73
+ meta = client.metadata(url) # description, uploader, stats, formats, ...
74
+ print(meta.title, meta.uploader, meta.view_count)
75
+ print(meta.raw) # every field the source returned
76
+ ```
77
+
78
+ ## Async
79
+
80
+ ```python
81
+ import asyncio
82
+ from importly import AsyncImportly
83
+
84
+ async def main(urls):
85
+ async with AsyncImportly() as client:
86
+ return await asyncio.gather(*(client.transcribe(u) for u in urls))
87
+ ```
88
+
89
+ ## Webhooks instead of waiting
90
+
91
+ Every job runs in the background. The one-call helpers above poll until it's done. In a web app, start the job with a `webhook_url` and handle the result when it arrives:
92
+
93
+ ```python
94
+ job = client.start_transcription(url, webhook_url="https://your-app.com/webhooks/importly?token=" + WEBHOOK_TOKEN)
95
+ save(job.job_id)
96
+ ```
97
+
98
+ ```python
99
+ from importly.webhooks import parse_webhook, token_matches
100
+
101
+ @app.post("/webhooks/importly") # Flask
102
+ def importly_webhook():
103
+ if not token_matches(request.args.get("token"), WEBHOOK_TOKEN):
104
+ abort(401)
105
+ event = parse_webhook(request.get_data())
106
+ if event.succeeded and event.job_type == "transcribe":
107
+ store_transcript(event.job_id, event.result.text)
108
+ elif event.failed:
109
+ mark_failed(event.job_id, event.code, event.message)
110
+ return "", 204
111
+ ```
112
+
113
+ Each job gets one delivery and no retries, so keep a fallback: `client.get_job(job_type, job_id)` returns the job's current state. Webhooks aren't signed; use a secret token in the URL as above, and only act on job ids you started.
114
+
115
+ You can also do it in steps yourself: `start_import` / `get_import` / `wait_for_import`, and the same for `transcription`, `metadata` and `basic_metadata`.
116
+
117
+ ## Errors
118
+
119
+ | Exception | When | What to do |
120
+ | --- | --- | --- |
121
+ | `AuthenticationError` (401) | Missing or wrong API key | Check `IMPORTLY_API_KEY` |
122
+ | `InsufficientBalanceError` (402) | Balance too low to start the job (`balance_required`) | Add credits |
123
+ | `InvalidURLError` (400, `INVALID_URL`) | The link isn't a valid or supported media URL | Fix the URL |
124
+ | `InvalidRequestError` (400) | Another bad parameter | Fix the request |
125
+ | `RateLimitError` (429) | Over the hourly limit (`retry_after` seconds) | Retried automatically when the wait is under a minute |
126
+ | `InternalServerError` (5xx) | Something broke on Importly's side | Status calls are retried; job starts are not, so they can't start twice |
127
+ | `JobFailedError` | The job ran and failed, e.g. `VIDEO_PRIVATE`, `MAX_COST_EXCEEDED` (`.code`, `.documentation_url`) | See the linked page |
128
+ | `TranscriptionProviderRequiredError` | No captions and no `provider` (`.quote`) | Retry with `provider="importly"` |
129
+ | `JobTimeoutError` | Still running when `timeout` ran out | Poll later or use a webhook |
130
+
131
+ All of them inherit from `ImportlyError`.
132
+
133
+ ## Pricing
134
+
135
+ Pay as you go from a credit balance: transcripts from captions and metadata are $0.003 per link, downloads $0.002 per MB (min $0.01). See [pricing](https://www.importly.io/pricing?utm_source=pypi&utm_medium=package&utm_campaign=guerrilla-2026-11).
136
+
137
+ ## Links
138
+
139
+ - [Docs](https://www.importly.io/docs?utm_source=pypi&utm_medium=package&utm_campaign=guerrilla-2026-11) and [API reference](https://www.importly.io/docs/api-reference?utm_source=pypi&utm_medium=package&utm_campaign=guerrilla-2026-11)
140
+ - LangChain: [`langchain-importly`](https://pypi.org/project/langchain-importly/). LlamaIndex: [`llama-index-readers-importly`](https://pypi.org/project/llama-index-readers-importly/)
141
+ - Support: support@importly.io
142
+
143
+ MIT licensed.
@@ -0,0 +1,118 @@
1
+ # importly
2
+
3
+ Turn any video or audio link into files, transcripts and metadata from your Python app.
4
+
5
+ Send a link from YouTube, TikTok, X, Instagram, a podcast or 1,000+ other sites, and get back the file, a timestamped transcript or the metadata. It works from servers and agent sandboxes, where downloads usually get blocked. Free to try, no card required: [get an API key](https://www.importly.io/login?mode=signup&utm_source=pypi&utm_medium=package&utm_campaign=guerrilla-2026-11).
6
+
7
+ ```bash
8
+ pip install importly
9
+ export IMPORTLY_API_KEY=...
10
+ ```
11
+
12
+ ## Transcript
13
+
14
+ ```python
15
+ from importly import Importly
16
+
17
+ client = Importly() # reads IMPORTLY_API_KEY
18
+
19
+ transcript = client.transcribe("https://www.youtube.com/watch?v=jNQXAC9IVRw")
20
+ print(transcript.text)
21
+ for segment in transcript.segments:
22
+ print(segment.start, segment.end, segment.text)
23
+
24
+ # Group segments into ~2-minute chunks for RAG, each with start/end times
25
+ for chunk in transcript.chunks(120):
26
+ print(chunk.start_timestamp, chunk.text[:80])
27
+ ```
28
+
29
+ By default the transcript comes from the media's captions. If there are none, `transcribe` raises `TranscriptionProviderRequiredError` with a `quote`; pass `provider="importly"` to use built-in speech-to-text, optionally with `max_cost_dollars`.
30
+
31
+ ## File
32
+
33
+ ```python
34
+ result = client.import_media(
35
+ "https://www.tiktok.com/@scout2015/video/6718335390845095173",
36
+ video_quality="720p",
37
+ max_cost_dollars=0.10,
38
+ )
39
+ print(result.media_url) # signed download link, valid for 7 days
40
+ ```
41
+
42
+ Audio only: `include_video=False`. Copy straight to your own S3-compatible bucket: `store=True` (set up your bucket in the dashboard first).
43
+
44
+ ## Metadata
45
+
46
+ ```python
47
+ preview = client.basic_metadata(url) # title, duration, thumbnail
48
+ meta = client.metadata(url) # description, uploader, stats, formats, ...
49
+ print(meta.title, meta.uploader, meta.view_count)
50
+ print(meta.raw) # every field the source returned
51
+ ```
52
+
53
+ ## Async
54
+
55
+ ```python
56
+ import asyncio
57
+ from importly import AsyncImportly
58
+
59
+ async def main(urls):
60
+ async with AsyncImportly() as client:
61
+ return await asyncio.gather(*(client.transcribe(u) for u in urls))
62
+ ```
63
+
64
+ ## Webhooks instead of waiting
65
+
66
+ Every job runs in the background. The one-call helpers above poll until it's done. In a web app, start the job with a `webhook_url` and handle the result when it arrives:
67
+
68
+ ```python
69
+ job = client.start_transcription(url, webhook_url="https://your-app.com/webhooks/importly?token=" + WEBHOOK_TOKEN)
70
+ save(job.job_id)
71
+ ```
72
+
73
+ ```python
74
+ from importly.webhooks import parse_webhook, token_matches
75
+
76
+ @app.post("/webhooks/importly") # Flask
77
+ def importly_webhook():
78
+ if not token_matches(request.args.get("token"), WEBHOOK_TOKEN):
79
+ abort(401)
80
+ event = parse_webhook(request.get_data())
81
+ if event.succeeded and event.job_type == "transcribe":
82
+ store_transcript(event.job_id, event.result.text)
83
+ elif event.failed:
84
+ mark_failed(event.job_id, event.code, event.message)
85
+ return "", 204
86
+ ```
87
+
88
+ Each job gets one delivery and no retries, so keep a fallback: `client.get_job(job_type, job_id)` returns the job's current state. Webhooks aren't signed; use a secret token in the URL as above, and only act on job ids you started.
89
+
90
+ You can also do it in steps yourself: `start_import` / `get_import` / `wait_for_import`, and the same for `transcription`, `metadata` and `basic_metadata`.
91
+
92
+ ## Errors
93
+
94
+ | Exception | When | What to do |
95
+ | --- | --- | --- |
96
+ | `AuthenticationError` (401) | Missing or wrong API key | Check `IMPORTLY_API_KEY` |
97
+ | `InsufficientBalanceError` (402) | Balance too low to start the job (`balance_required`) | Add credits |
98
+ | `InvalidURLError` (400, `INVALID_URL`) | The link isn't a valid or supported media URL | Fix the URL |
99
+ | `InvalidRequestError` (400) | Another bad parameter | Fix the request |
100
+ | `RateLimitError` (429) | Over the hourly limit (`retry_after` seconds) | Retried automatically when the wait is under a minute |
101
+ | `InternalServerError` (5xx) | Something broke on Importly's side | Status calls are retried; job starts are not, so they can't start twice |
102
+ | `JobFailedError` | The job ran and failed, e.g. `VIDEO_PRIVATE`, `MAX_COST_EXCEEDED` (`.code`, `.documentation_url`) | See the linked page |
103
+ | `TranscriptionProviderRequiredError` | No captions and no `provider` (`.quote`) | Retry with `provider="importly"` |
104
+ | `JobTimeoutError` | Still running when `timeout` ran out | Poll later or use a webhook |
105
+
106
+ All of them inherit from `ImportlyError`.
107
+
108
+ ## Pricing
109
+
110
+ Pay as you go from a credit balance: transcripts from captions and metadata are $0.003 per link, downloads $0.002 per MB (min $0.01). See [pricing](https://www.importly.io/pricing?utm_source=pypi&utm_medium=package&utm_campaign=guerrilla-2026-11).
111
+
112
+ ## Links
113
+
114
+ - [Docs](https://www.importly.io/docs?utm_source=pypi&utm_medium=package&utm_campaign=guerrilla-2026-11) and [API reference](https://www.importly.io/docs/api-reference?utm_source=pypi&utm_medium=package&utm_campaign=guerrilla-2026-11)
115
+ - LangChain: [`langchain-importly`](https://pypi.org/project/langchain-importly/). LlamaIndex: [`llama-index-readers-importly`](https://pypi.org/project/llama-index-readers-importly/)
116
+ - Support: support@importly.io
117
+
118
+ MIT licensed.
@@ -0,0 +1,40 @@
1
+ [build-system]
2
+ requires = ["hatchling>=1.24"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "importly"
7
+ version = "0.1.0"
8
+ description = "Turn any video or audio link into files, transcripts and metadata from your Python app. Works from servers where downloads get blocked."
9
+ readme = "README.md"
10
+ requires-python = ">=3.9"
11
+ license = "MIT"
12
+ license-files = ["LICENSE"]
13
+ authors = [{ name = "Importly", email = "support@importly.io" }]
14
+ keywords = ["video", "audio", "transcript", "youtube", "tiktok", "podcast", "metadata", "download", "api"]
15
+ classifiers = [
16
+ "Development Status :: 4 - Beta",
17
+ "Intended Audience :: Developers",
18
+ "Programming Language :: Python :: 3",
19
+ "Topic :: Multimedia :: Video",
20
+ "Topic :: Multimedia :: Sound/Audio",
21
+ "Typing :: Typed",
22
+ ]
23
+ dependencies = ["httpx>=0.24,<1"]
24
+
25
+ [project.optional-dependencies]
26
+ test = ["pytest>=7", "pytest-asyncio>=0.23"]
27
+
28
+ [project.urls]
29
+ Homepage = "https://www.importly.io/?utm_source=pypi&utm_medium=package&utm_campaign=guerrilla-2026-11"
30
+ Documentation = "https://www.importly.io/docs?utm_source=pypi&utm_medium=package&utm_campaign=guerrilla-2026-11"
31
+ Repository = "https://github.com/importly-io/importly-integrations/tree/main/python/importly"
32
+ Issues = "https://github.com/importly-io/importly-integrations/issues"
33
+
34
+ [tool.hatch.build.targets.wheel]
35
+ packages = ["src/importly"]
36
+
37
+ [tool.pytest.ini_options]
38
+ asyncio_mode = "auto"
39
+ asyncio_default_fixture_loop_scope = "function"
40
+ markers = ["live: calls the real Importly API (needs IMPORTLY_LIVE_TEST=1 and IMPORTLY_API_KEY)"]
@@ -0,0 +1,78 @@
1
+ """Importly: turn any video or audio link into files, transcripts and metadata.
2
+
3
+ from importly import Importly
4
+
5
+ client = Importly() # reads IMPORTLY_API_KEY
6
+ transcript = client.transcribe("https://www.youtube.com/watch?v=jNQXAC9IVRw")
7
+ print(transcript.text)
8
+
9
+ Docs: https://www.importly.io/docs
10
+ """
11
+
12
+ from ._client import AsyncImportly, Importly
13
+ from ._errors import (
14
+ APIConnectionError,
15
+ APIError,
16
+ AuthenticationError,
17
+ ImportlyError,
18
+ InsufficientBalanceError,
19
+ InternalServerError,
20
+ InvalidRequestError,
21
+ InvalidURLError,
22
+ JobFailedError,
23
+ JobTimeoutError,
24
+ MissingAPIKeyError,
25
+ NotFoundError,
26
+ RateLimitError,
27
+ TranscriptionProviderRequiredError,
28
+ )
29
+ from ._types import (
30
+ Balance,
31
+ BasicMetadata,
32
+ ImportResult,
33
+ JobStatus,
34
+ Metadata,
35
+ QueuedJob,
36
+ S3Location,
37
+ Transcript,
38
+ TranscriptChunk,
39
+ TranscriptSegment,
40
+ format_timestamp,
41
+ )
42
+ from ._version import __version__
43
+ from .webhooks import InvalidWebhookError, WebhookEvent, parse_webhook, token_matches
44
+
45
+ __all__ = [
46
+ "Importly",
47
+ "AsyncImportly",
48
+ "ImportlyError",
49
+ "MissingAPIKeyError",
50
+ "APIConnectionError",
51
+ "APIError",
52
+ "InvalidRequestError",
53
+ "InvalidURLError",
54
+ "AuthenticationError",
55
+ "InsufficientBalanceError",
56
+ "NotFoundError",
57
+ "RateLimitError",
58
+ "InternalServerError",
59
+ "JobFailedError",
60
+ "TranscriptionProviderRequiredError",
61
+ "JobTimeoutError",
62
+ "Balance",
63
+ "BasicMetadata",
64
+ "ImportResult",
65
+ "JobStatus",
66
+ "Metadata",
67
+ "QueuedJob",
68
+ "S3Location",
69
+ "Transcript",
70
+ "TranscriptChunk",
71
+ "TranscriptSegment",
72
+ "format_timestamp",
73
+ "WebhookEvent",
74
+ "InvalidWebhookError",
75
+ "parse_webhook",
76
+ "token_matches",
77
+ "__version__",
78
+ ]
@@ -0,0 +1,160 @@
1
+ """Pieces shared by the sync and async clients: config, request bodies, retries."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ from typing import Any, Dict, Mapping, Optional, Tuple
7
+
8
+ import httpx
9
+
10
+ from ._errors import (
11
+ MissingAPIKeyError,
12
+ RateLimitError,
13
+ error_from_response,
14
+ job_failed_error,
15
+ )
16
+ from ._types import JobStatus, parse_job_status
17
+ from ._version import __version__
18
+
19
+ DEFAULT_BASE_URL = "https://api.importly.io"
20
+ DEFAULT_TIMEOUT = 30.0
21
+ DEFAULT_WAIT_TIMEOUT = 600.0
22
+ DEFAULT_POLL_INTERVAL = 3.0
23
+
24
+ # job type -> (start path, status path)
25
+ ENDPOINTS: Dict[str, Tuple[str, str]] = {
26
+ "import": ("/import", "/import/status"),
27
+ "transcribe": ("/transcribe", "/transcribe/status"),
28
+ "metadata": ("/metadata", "/metadata/status"),
29
+ "basic-metadata": ("/metadata/basic", "/metadata/basic/status"),
30
+ }
31
+
32
+ _IMPORT_FIELDS = {
33
+ "include_video": "includeVideo",
34
+ "include_audio": "includeAudio",
35
+ "video_quality": "videoQuality",
36
+ "audio_quality": "audioQuality",
37
+ "max_cost_dollars": "maxCostDollars",
38
+ "webhook_url": "webhookUrl",
39
+ "include_transcript": "includeTranscript",
40
+ "transcript_provider": "transcriptProvider",
41
+ "transcript_api_key": "transcriptApiKey",
42
+ "transcript_language": "transcriptLanguage",
43
+ "transcript_options": "transcriptOptions",
44
+ "store": "store",
45
+ "storage_path": "storagePath",
46
+ "storage_filename": "storageFilename",
47
+ "storage_bucket": "storageBucket",
48
+ "storage_class": "storageClass",
49
+ }
50
+
51
+ _TRANSCRIBE_FIELDS = {
52
+ "language": "language",
53
+ "provider": "provider",
54
+ "api_key": "apiKey",
55
+ "provider_options": "providerOptions",
56
+ "max_cost_dollars": "maxCostDollars",
57
+ "webhook_url": "webhookUrl",
58
+ }
59
+
60
+ _METADATA_FIELDS = {"webhook_url": "webhookUrl"}
61
+
62
+ FIELDS_BY_TYPE = {
63
+ "import": _IMPORT_FIELDS,
64
+ "transcribe": _TRANSCRIBE_FIELDS,
65
+ "metadata": _METADATA_FIELDS,
66
+ "basic-metadata": _METADATA_FIELDS,
67
+ }
68
+
69
+
70
+ def build_body(job_type: str, url: str, options: Mapping[str, Any]) -> Dict[str, Any]:
71
+ """Turn snake_case keyword options into the API's camelCase JSON body.
72
+
73
+ ``None`` values are left out so the API's defaults apply. Unknown options
74
+ raise ``TypeError``, like a wrong keyword argument would.
75
+ """
76
+ fields = FIELDS_BY_TYPE[job_type]
77
+ unknown = set(options) - set(fields)
78
+ if unknown:
79
+ raise TypeError(f"Unknown option(s) for {job_type}: {', '.join(sorted(unknown))}")
80
+ body: Dict[str, Any] = {"url": url}
81
+ for name, value in options.items():
82
+ if value is not None:
83
+ body[fields[name]] = value
84
+ return body
85
+
86
+
87
+ class ClientConfig:
88
+ def __init__(
89
+ self,
90
+ api_key: Optional[str],
91
+ base_url: Optional[str],
92
+ timeout: float,
93
+ max_retries: int,
94
+ max_retry_wait: float,
95
+ ) -> None:
96
+ key = api_key or os.environ.get("IMPORTLY_API_KEY")
97
+ if not key:
98
+ raise MissingAPIKeyError(
99
+ "No API key. Pass api_key=... or set IMPORTLY_API_KEY. "
100
+ "Get one at https://www.importly.io/dashboard/api-key (free to try, no card required).",
101
+ code="UNAUTHORIZED",
102
+ )
103
+ self.api_key = key
104
+ self.base_url = (base_url or os.environ.get("IMPORTLY_BASE_URL") or DEFAULT_BASE_URL).rstrip("/")
105
+ self.timeout = timeout
106
+ self.max_retries = max(0, max_retries)
107
+ self.max_retry_wait = max_retry_wait
108
+
109
+ @property
110
+ def headers(self) -> Dict[str, str]:
111
+ return {
112
+ "Authorization": f"Bearer {self.api_key}",
113
+ "Accept": "application/json",
114
+ "User-Agent": f"importly-python/{__version__}",
115
+ }
116
+
117
+
118
+ def parse_response(response: httpx.Response) -> Any:
119
+ """Return ``data`` from a success envelope, or raise the matching error."""
120
+ try:
121
+ body = response.json()
122
+ except ValueError:
123
+ body = {"error": response.text[:500] or f"HTTP {response.status_code}"}
124
+ if response.status_code >= 400 or (isinstance(body, dict) and body.get("success") is False):
125
+ raise error_from_response(response.status_code if response.status_code >= 400 else 500, body)
126
+ if isinstance(body, dict) and "data" in body:
127
+ return body["data"]
128
+ return body
129
+
130
+
131
+ def retry_delay(error: Exception, attempt: int, method: str, max_retry_wait: float) -> Optional[float]:
132
+ """Seconds to wait before retrying, or ``None`` to give up.
133
+
134
+ - 429 is retried for any method (the request was refused before a job
135
+ existed), if the wait is no longer than ``max_retry_wait``.
136
+ - 5xx and dropped connections are retried for GET only: a POST that
137
+ reached the server may already have started a (billed) job.
138
+ - Connection failures before anything was sent are safe for any method.
139
+ """
140
+ from ._errors import InternalServerError
141
+
142
+ if isinstance(error, RateLimitError):
143
+ wait = error.retry_after if error.retry_after is not None else 2.0 ** attempt
144
+ return wait if wait <= max_retry_wait else None
145
+ backoff = min(0.5 * 2 ** attempt, 8.0)
146
+ if isinstance(error, (httpx.ConnectError, httpx.ConnectTimeout)):
147
+ return backoff
148
+ if method == "GET" and isinstance(error, (InternalServerError, httpx.TransportError)):
149
+ return backoff
150
+ return None
151
+
152
+
153
+ def status_or_raise(job_type: str, job_id: str, data: Mapping[str, Any]) -> JobStatus:
154
+ return parse_job_status(job_type, {"jobId": job_id, **data})
155
+
156
+
157
+ def result_or_raise(status: JobStatus) -> Any:
158
+ if status.failed:
159
+ raise job_failed_error(status.job_type, status.job_id, status.raw)
160
+ return status.result