importly 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.
- importly/__init__.py +78 -0
- importly/_base.py +160 -0
- importly/_client.py +363 -0
- importly/_errors.py +198 -0
- importly/_types.py +302 -0
- importly/_version.py +1 -0
- importly/py.typed +0 -0
- importly/webhooks.py +116 -0
- importly-0.1.0.dist-info/METADATA +143 -0
- importly-0.1.0.dist-info/RECORD +12 -0
- importly-0.1.0.dist-info/WHEEL +4 -0
- importly-0.1.0.dist-info/licenses/LICENSE +21 -0
importly/__init__.py
ADDED
|
@@ -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
|
+
]
|
importly/_base.py
ADDED
|
@@ -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
|
importly/_client.py
ADDED
|
@@ -0,0 +1,363 @@
|
|
|
1
|
+
"""Sync (``Importly``) and async (``AsyncImportly``) clients for the Importly API.
|
|
2
|
+
|
|
3
|
+
Every job is asynchronous on the server. Each job type has three calls:
|
|
4
|
+
|
|
5
|
+
- ``start_<job>(url, ...)`` queues it and returns a ``QueuedJob`` (use this with
|
|
6
|
+
``webhook_url``);
|
|
7
|
+
- ``get_<job>(job_id)`` returns one ``JobStatus`` poll;
|
|
8
|
+
- ``wait_for_<job>(job_id)`` polls until it finishes and returns the typed
|
|
9
|
+
result, raising ``JobFailedError`` or ``JobTimeoutError``.
|
|
10
|
+
|
|
11
|
+
The one-call helpers ``import_media``, ``transcribe``, ``metadata`` and
|
|
12
|
+
``basic_metadata`` start a job and wait for it.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import asyncio
|
|
18
|
+
import time
|
|
19
|
+
from typing import Any, Callable, Dict, List, Optional
|
|
20
|
+
|
|
21
|
+
import httpx
|
|
22
|
+
|
|
23
|
+
from ._base import (
|
|
24
|
+
DEFAULT_POLL_INTERVAL,
|
|
25
|
+
DEFAULT_TIMEOUT,
|
|
26
|
+
DEFAULT_WAIT_TIMEOUT,
|
|
27
|
+
ENDPOINTS,
|
|
28
|
+
ClientConfig,
|
|
29
|
+
build_body,
|
|
30
|
+
parse_response,
|
|
31
|
+
result_or_raise,
|
|
32
|
+
retry_delay,
|
|
33
|
+
status_or_raise,
|
|
34
|
+
)
|
|
35
|
+
from ._errors import APIConnectionError, JobTimeoutError
|
|
36
|
+
from ._types import (
|
|
37
|
+
Balance,
|
|
38
|
+
BasicMetadata,
|
|
39
|
+
ImportResult,
|
|
40
|
+
JobStatus,
|
|
41
|
+
Metadata,
|
|
42
|
+
QueuedJob,
|
|
43
|
+
Transcript,
|
|
44
|
+
)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class Importly:
|
|
48
|
+
"""Synchronous client.
|
|
49
|
+
|
|
50
|
+
>>> client = Importly() # reads IMPORTLY_API_KEY
|
|
51
|
+
>>> transcript = client.transcribe("https://www.youtube.com/watch?v=jNQXAC9IVRw")
|
|
52
|
+
>>> transcript.text
|
|
53
|
+
"""
|
|
54
|
+
|
|
55
|
+
def __init__(
|
|
56
|
+
self,
|
|
57
|
+
api_key: Optional[str] = None,
|
|
58
|
+
*,
|
|
59
|
+
base_url: Optional[str] = None,
|
|
60
|
+
timeout: float = DEFAULT_TIMEOUT,
|
|
61
|
+
max_retries: int = 2,
|
|
62
|
+
max_retry_wait: float = 60.0,
|
|
63
|
+
http_client: Optional[httpx.Client] = None,
|
|
64
|
+
sleep: Callable[[float], None] = time.sleep,
|
|
65
|
+
) -> None:
|
|
66
|
+
self._config = ClientConfig(api_key, base_url, timeout, max_retries, max_retry_wait)
|
|
67
|
+
self._owns_client = http_client is None
|
|
68
|
+
self._http = http_client or httpx.Client(timeout=timeout)
|
|
69
|
+
self._sleep = sleep
|
|
70
|
+
|
|
71
|
+
def close(self) -> None:
|
|
72
|
+
if self._owns_client:
|
|
73
|
+
self._http.close()
|
|
74
|
+
|
|
75
|
+
def __enter__(self) -> "Importly":
|
|
76
|
+
return self
|
|
77
|
+
|
|
78
|
+
def __exit__(self, *exc: Any) -> None:
|
|
79
|
+
self.close()
|
|
80
|
+
|
|
81
|
+
# -- transport -----------------------------------------------------
|
|
82
|
+
|
|
83
|
+
def _request(self, method: str, path: str, *, params: Optional[Dict[str, Any]] = None, json: Any = None) -> Any:
|
|
84
|
+
attempt = 0
|
|
85
|
+
while True:
|
|
86
|
+
try:
|
|
87
|
+
response = self._http.request(
|
|
88
|
+
method,
|
|
89
|
+
self._config.base_url + path,
|
|
90
|
+
params=params,
|
|
91
|
+
json=json,
|
|
92
|
+
headers=self._config.headers,
|
|
93
|
+
timeout=self._config.timeout,
|
|
94
|
+
)
|
|
95
|
+
return parse_response(response)
|
|
96
|
+
except Exception as error: # noqa: BLE001 - re-raised below
|
|
97
|
+
delay = retry_delay(error, attempt, method, self._config.max_retry_wait) if attempt < self._config.max_retries else None
|
|
98
|
+
if delay is None:
|
|
99
|
+
if isinstance(error, httpx.TransportError):
|
|
100
|
+
raise APIConnectionError(f"Could not reach the Importly API: {error}") from error
|
|
101
|
+
raise
|
|
102
|
+
attempt += 1
|
|
103
|
+
self._sleep(delay)
|
|
104
|
+
|
|
105
|
+
def _start(self, job_type: str, url: str, options: Dict[str, Any]) -> QueuedJob:
|
|
106
|
+
data = self._request("POST", ENDPOINTS[job_type][0], json=build_body(job_type, url, options))
|
|
107
|
+
return QueuedJob.from_dict(data)
|
|
108
|
+
|
|
109
|
+
def get_job(self, job_type: str, job_id: str) -> JobStatus:
|
|
110
|
+
"""Poll any job by type (``import``, ``transcribe``, ``metadata``, ``basic-metadata``)."""
|
|
111
|
+
data = self._request("GET", ENDPOINTS[job_type][1], params={"id": job_id})
|
|
112
|
+
return status_or_raise(job_type, job_id, data)
|
|
113
|
+
|
|
114
|
+
def wait_for_job(
|
|
115
|
+
self,
|
|
116
|
+
job_type: str,
|
|
117
|
+
job_id: str,
|
|
118
|
+
*,
|
|
119
|
+
timeout: float = DEFAULT_WAIT_TIMEOUT,
|
|
120
|
+
poll_interval: float = DEFAULT_POLL_INTERVAL,
|
|
121
|
+
) -> Any:
|
|
122
|
+
"""Poll until the job is final. Returns the typed result or raises ``JobFailedError``."""
|
|
123
|
+
deadline = time.monotonic() + timeout
|
|
124
|
+
while True:
|
|
125
|
+
status = self.get_job(job_type, job_id)
|
|
126
|
+
if status.is_done:
|
|
127
|
+
return result_or_raise(status)
|
|
128
|
+
if time.monotonic() + poll_interval > deadline:
|
|
129
|
+
raise JobTimeoutError(
|
|
130
|
+
f"{job_type} job {job_id} still {status.status} after {timeout:.0f}s. "
|
|
131
|
+
"It may still finish: poll get_job() later or use a webhook.",
|
|
132
|
+
job_id=job_id,
|
|
133
|
+
job_type=job_type,
|
|
134
|
+
)
|
|
135
|
+
self._sleep(poll_interval)
|
|
136
|
+
|
|
137
|
+
# -- import ----------------------------------------------------------
|
|
138
|
+
|
|
139
|
+
def start_import(self, url: str, **options: Any) -> QueuedJob:
|
|
140
|
+
"""Queue a download. Options: ``include_video``, ``include_audio``, ``video_quality``,
|
|
141
|
+
``audio_quality``, ``max_cost_dollars``, ``webhook_url``, ``include_transcript``,
|
|
142
|
+
``transcript_provider``, ``transcript_api_key``, ``transcript_language``,
|
|
143
|
+
``transcript_options``, ``store``, ``storage_path``, ``storage_filename``,
|
|
144
|
+
``storage_bucket``, ``storage_class``."""
|
|
145
|
+
return self._start("import", url, options)
|
|
146
|
+
|
|
147
|
+
def get_import(self, job_id: str) -> JobStatus:
|
|
148
|
+
return self.get_job("import", job_id)
|
|
149
|
+
|
|
150
|
+
def wait_for_import(self, job_id: str, **wait: Any) -> ImportResult:
|
|
151
|
+
return self.wait_for_job("import", job_id, **wait)
|
|
152
|
+
|
|
153
|
+
def import_media(
|
|
154
|
+
self, url: str, *, timeout: float = DEFAULT_WAIT_TIMEOUT, poll_interval: float = DEFAULT_POLL_INTERVAL, **options: Any
|
|
155
|
+
) -> ImportResult:
|
|
156
|
+
"""Download the media and wait. ``result.media_url`` is a signed link valid for 7 days."""
|
|
157
|
+
job = self.start_import(url, **options)
|
|
158
|
+
return self.wait_for_import(job.job_id, timeout=timeout, poll_interval=poll_interval)
|
|
159
|
+
|
|
160
|
+
# -- transcribe ------------------------------------------------------
|
|
161
|
+
|
|
162
|
+
def start_transcription(self, url: str, **options: Any) -> QueuedJob:
|
|
163
|
+
"""Queue a transcription. Options: ``language``, ``provider`` (``importly``,
|
|
164
|
+
``assemblyai``, ``deepgram``, ``openai``), ``api_key``, ``provider_options``,
|
|
165
|
+
``max_cost_dollars``, ``webhook_url``. Without ``provider`` it uses the media's captions."""
|
|
166
|
+
return self._start("transcribe", url, options)
|
|
167
|
+
|
|
168
|
+
def get_transcription(self, job_id: str) -> JobStatus:
|
|
169
|
+
return self.get_job("transcribe", job_id)
|
|
170
|
+
|
|
171
|
+
def wait_for_transcription(self, job_id: str, **wait: Any) -> Transcript:
|
|
172
|
+
return self.wait_for_job("transcribe", job_id, **wait)
|
|
173
|
+
|
|
174
|
+
def transcribe(
|
|
175
|
+
self, url: str, *, timeout: float = DEFAULT_WAIT_TIMEOUT, poll_interval: float = DEFAULT_POLL_INTERVAL, **options: Any
|
|
176
|
+
) -> Transcript:
|
|
177
|
+
"""Transcribe and wait. Raises ``TranscriptionProviderRequiredError`` (with a ``quote``)
|
|
178
|
+
when the media has no captions and no ``provider`` was set."""
|
|
179
|
+
job = self.start_transcription(url, **options)
|
|
180
|
+
return self.wait_for_transcription(job.job_id, timeout=timeout, poll_interval=poll_interval)
|
|
181
|
+
|
|
182
|
+
# -- metadata --------------------------------------------------------
|
|
183
|
+
|
|
184
|
+
def start_metadata(self, url: str, *, webhook_url: Optional[str] = None) -> QueuedJob:
|
|
185
|
+
return self._start("metadata", url, {"webhook_url": webhook_url})
|
|
186
|
+
|
|
187
|
+
def get_metadata(self, job_id: str) -> JobStatus:
|
|
188
|
+
return self.get_job("metadata", job_id)
|
|
189
|
+
|
|
190
|
+
def wait_for_metadata(self, job_id: str, **wait: Any) -> Metadata:
|
|
191
|
+
return self.wait_for_job("metadata", job_id, **wait)
|
|
192
|
+
|
|
193
|
+
def metadata(self, url: str, *, timeout: float = DEFAULT_WAIT_TIMEOUT, poll_interval: float = 2.0) -> Metadata:
|
|
194
|
+
"""Full metadata (title, description, uploader, stats, formats, ...) without downloading."""
|
|
195
|
+
job = self.start_metadata(url)
|
|
196
|
+
return self.wait_for_metadata(job.job_id, timeout=timeout, poll_interval=poll_interval)
|
|
197
|
+
|
|
198
|
+
def start_basic_metadata(self, url: str, *, webhook_url: Optional[str] = None) -> QueuedJob:
|
|
199
|
+
return self._start("basic-metadata", url, {"webhook_url": webhook_url})
|
|
200
|
+
|
|
201
|
+
def get_basic_metadata(self, job_id: str) -> JobStatus:
|
|
202
|
+
return self.get_job("basic-metadata", job_id)
|
|
203
|
+
|
|
204
|
+
def wait_for_basic_metadata(self, job_id: str, **wait: Any) -> BasicMetadata:
|
|
205
|
+
return self.wait_for_job("basic-metadata", job_id, **wait)
|
|
206
|
+
|
|
207
|
+
def basic_metadata(self, url: str, *, timeout: float = DEFAULT_WAIT_TIMEOUT, poll_interval: float = 1.0) -> BasicMetadata:
|
|
208
|
+
"""Title, duration and thumbnail only: faster, for link previews and import forms."""
|
|
209
|
+
job = self.start_basic_metadata(url)
|
|
210
|
+
return self.wait_for_basic_metadata(job.job_id, timeout=timeout, poll_interval=poll_interval)
|
|
211
|
+
|
|
212
|
+
# -- account ---------------------------------------------------------
|
|
213
|
+
|
|
214
|
+
def balance(self) -> Balance:
|
|
215
|
+
return Balance.from_dict(self._request("GET", "/balance"))
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
class AsyncImportly:
|
|
219
|
+
"""Asynchronous client with the same methods as ``Importly``, as coroutines.
|
|
220
|
+
|
|
221
|
+
>>> async with AsyncImportly() as client:
|
|
222
|
+
... transcripts = await asyncio.gather(*(client.transcribe(u) for u in urls))
|
|
223
|
+
"""
|
|
224
|
+
|
|
225
|
+
def __init__(
|
|
226
|
+
self,
|
|
227
|
+
api_key: Optional[str] = None,
|
|
228
|
+
*,
|
|
229
|
+
base_url: Optional[str] = None,
|
|
230
|
+
timeout: float = DEFAULT_TIMEOUT,
|
|
231
|
+
max_retries: int = 2,
|
|
232
|
+
max_retry_wait: float = 60.0,
|
|
233
|
+
http_client: Optional[httpx.AsyncClient] = None,
|
|
234
|
+
sleep: Optional[Callable[[float], Any]] = None,
|
|
235
|
+
) -> None:
|
|
236
|
+
self._config = ClientConfig(api_key, base_url, timeout, max_retries, max_retry_wait)
|
|
237
|
+
self._owns_client = http_client is None
|
|
238
|
+
self._http = http_client or httpx.AsyncClient(timeout=timeout)
|
|
239
|
+
self._sleep = sleep or asyncio.sleep
|
|
240
|
+
|
|
241
|
+
async def aclose(self) -> None:
|
|
242
|
+
if self._owns_client:
|
|
243
|
+
await self._http.aclose()
|
|
244
|
+
|
|
245
|
+
async def __aenter__(self) -> "AsyncImportly":
|
|
246
|
+
return self
|
|
247
|
+
|
|
248
|
+
async def __aexit__(self, *exc: Any) -> None:
|
|
249
|
+
await self.aclose()
|
|
250
|
+
|
|
251
|
+
async def _request(self, method: str, path: str, *, params: Optional[Dict[str, Any]] = None, json: Any = None) -> Any:
|
|
252
|
+
attempt = 0
|
|
253
|
+
while True:
|
|
254
|
+
try:
|
|
255
|
+
response = await self._http.request(
|
|
256
|
+
method,
|
|
257
|
+
self._config.base_url + path,
|
|
258
|
+
params=params,
|
|
259
|
+
json=json,
|
|
260
|
+
headers=self._config.headers,
|
|
261
|
+
timeout=self._config.timeout,
|
|
262
|
+
)
|
|
263
|
+
return parse_response(response)
|
|
264
|
+
except Exception as error: # noqa: BLE001 - re-raised below
|
|
265
|
+
delay = retry_delay(error, attempt, method, self._config.max_retry_wait) if attempt < self._config.max_retries else None
|
|
266
|
+
if delay is None:
|
|
267
|
+
if isinstance(error, httpx.TransportError):
|
|
268
|
+
raise APIConnectionError(f"Could not reach the Importly API: {error}") from error
|
|
269
|
+
raise
|
|
270
|
+
attempt += 1
|
|
271
|
+
await self._sleep(delay)
|
|
272
|
+
|
|
273
|
+
async def _start(self, job_type: str, url: str, options: Dict[str, Any]) -> QueuedJob:
|
|
274
|
+
data = await self._request("POST", ENDPOINTS[job_type][0], json=build_body(job_type, url, options))
|
|
275
|
+
return QueuedJob.from_dict(data)
|
|
276
|
+
|
|
277
|
+
async def get_job(self, job_type: str, job_id: str) -> JobStatus:
|
|
278
|
+
data = await self._request("GET", ENDPOINTS[job_type][1], params={"id": job_id})
|
|
279
|
+
return status_or_raise(job_type, job_id, data)
|
|
280
|
+
|
|
281
|
+
async def wait_for_job(
|
|
282
|
+
self,
|
|
283
|
+
job_type: str,
|
|
284
|
+
job_id: str,
|
|
285
|
+
*,
|
|
286
|
+
timeout: float = DEFAULT_WAIT_TIMEOUT,
|
|
287
|
+
poll_interval: float = DEFAULT_POLL_INTERVAL,
|
|
288
|
+
) -> Any:
|
|
289
|
+
deadline = time.monotonic() + timeout
|
|
290
|
+
while True:
|
|
291
|
+
status = await self.get_job(job_type, job_id)
|
|
292
|
+
if status.is_done:
|
|
293
|
+
return result_or_raise(status)
|
|
294
|
+
if time.monotonic() + poll_interval > deadline:
|
|
295
|
+
raise JobTimeoutError(
|
|
296
|
+
f"{job_type} job {job_id} still {status.status} after {timeout:.0f}s. "
|
|
297
|
+
"It may still finish: poll get_job() later or use a webhook.",
|
|
298
|
+
job_id=job_id,
|
|
299
|
+
job_type=job_type,
|
|
300
|
+
)
|
|
301
|
+
await self._sleep(poll_interval)
|
|
302
|
+
|
|
303
|
+
async def start_import(self, url: str, **options: Any) -> QueuedJob:
|
|
304
|
+
return await self._start("import", url, options)
|
|
305
|
+
|
|
306
|
+
async def get_import(self, job_id: str) -> JobStatus:
|
|
307
|
+
return await self.get_job("import", job_id)
|
|
308
|
+
|
|
309
|
+
async def wait_for_import(self, job_id: str, **wait: Any) -> ImportResult:
|
|
310
|
+
return await self.wait_for_job("import", job_id, **wait)
|
|
311
|
+
|
|
312
|
+
async def import_media(
|
|
313
|
+
self, url: str, *, timeout: float = DEFAULT_WAIT_TIMEOUT, poll_interval: float = DEFAULT_POLL_INTERVAL, **options: Any
|
|
314
|
+
) -> ImportResult:
|
|
315
|
+
job = await self.start_import(url, **options)
|
|
316
|
+
return await self.wait_for_import(job.job_id, timeout=timeout, poll_interval=poll_interval)
|
|
317
|
+
|
|
318
|
+
async def start_transcription(self, url: str, **options: Any) -> QueuedJob:
|
|
319
|
+
return await self._start("transcribe", url, options)
|
|
320
|
+
|
|
321
|
+
async def get_transcription(self, job_id: str) -> JobStatus:
|
|
322
|
+
return await self.get_job("transcribe", job_id)
|
|
323
|
+
|
|
324
|
+
async def wait_for_transcription(self, job_id: str, **wait: Any) -> Transcript:
|
|
325
|
+
return await self.wait_for_job("transcribe", job_id, **wait)
|
|
326
|
+
|
|
327
|
+
async def transcribe(
|
|
328
|
+
self, url: str, *, timeout: float = DEFAULT_WAIT_TIMEOUT, poll_interval: float = DEFAULT_POLL_INTERVAL, **options: Any
|
|
329
|
+
) -> Transcript:
|
|
330
|
+
job = await self.start_transcription(url, **options)
|
|
331
|
+
return await self.wait_for_transcription(job.job_id, timeout=timeout, poll_interval=poll_interval)
|
|
332
|
+
|
|
333
|
+
async def start_metadata(self, url: str, *, webhook_url: Optional[str] = None) -> QueuedJob:
|
|
334
|
+
return await self._start("metadata", url, {"webhook_url": webhook_url})
|
|
335
|
+
|
|
336
|
+
async def get_metadata(self, job_id: str) -> JobStatus:
|
|
337
|
+
return await self.get_job("metadata", job_id)
|
|
338
|
+
|
|
339
|
+
async def wait_for_metadata(self, job_id: str, **wait: Any) -> Metadata:
|
|
340
|
+
return await self.wait_for_job("metadata", job_id, **wait)
|
|
341
|
+
|
|
342
|
+
async def metadata(self, url: str, *, timeout: float = DEFAULT_WAIT_TIMEOUT, poll_interval: float = 2.0) -> Metadata:
|
|
343
|
+
job = await self.start_metadata(url)
|
|
344
|
+
return await self.wait_for_metadata(job.job_id, timeout=timeout, poll_interval=poll_interval)
|
|
345
|
+
|
|
346
|
+
async def start_basic_metadata(self, url: str, *, webhook_url: Optional[str] = None) -> QueuedJob:
|
|
347
|
+
return await self._start("basic-metadata", url, {"webhook_url": webhook_url})
|
|
348
|
+
|
|
349
|
+
async def get_basic_metadata(self, job_id: str) -> JobStatus:
|
|
350
|
+
return await self.get_job("basic-metadata", job_id)
|
|
351
|
+
|
|
352
|
+
async def wait_for_basic_metadata(self, job_id: str, **wait: Any) -> BasicMetadata:
|
|
353
|
+
return await self.wait_for_job("basic-metadata", job_id, **wait)
|
|
354
|
+
|
|
355
|
+
async def basic_metadata(self, url: str, *, timeout: float = DEFAULT_WAIT_TIMEOUT, poll_interval: float = 1.0) -> BasicMetadata:
|
|
356
|
+
job = await self.start_basic_metadata(url)
|
|
357
|
+
return await self.wait_for_basic_metadata(job.job_id, timeout=timeout, poll_interval=poll_interval)
|
|
358
|
+
|
|
359
|
+
async def balance(self) -> Balance:
|
|
360
|
+
return Balance.from_dict(await self._request("GET", "/balance"))
|
|
361
|
+
|
|
362
|
+
|
|
363
|
+
__all__: List[str] = ["Importly", "AsyncImportly"]
|