voicemint 0.3.1__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.
voicemint/__init__.py ADDED
@@ -0,0 +1,43 @@
1
+ """Official Python SDK for the VoiceMint public API."""
2
+
3
+ from ._client import DEFAULT_BASE_URL, AsyncVoiceMint, VoiceMint
4
+ from ._errors import (
5
+ APIConnectionError,
6
+ APIError,
7
+ APITimeoutError,
8
+ AuthenticationError,
9
+ BadRequestError,
10
+ InsufficientCreditsError,
11
+ InternalServerError,
12
+ NotFoundError,
13
+ PermissionDeniedError,
14
+ RateLimitError,
15
+ ValidationError,
16
+ VoiceMintError,
17
+ )
18
+ from ._version import __version__
19
+ from .resources import IMAGE_TOOLS, ISOLATION_PRESETS, AudioResponse, JobFailedError, WaitTimeoutError
20
+
21
+ __all__ = [
22
+ "__version__",
23
+ "VoiceMint",
24
+ "AsyncVoiceMint",
25
+ "DEFAULT_BASE_URL",
26
+ "AudioResponse",
27
+ "VoiceMintError",
28
+ "APIError",
29
+ "BadRequestError",
30
+ "AuthenticationError",
31
+ "InsufficientCreditsError",
32
+ "PermissionDeniedError",
33
+ "NotFoundError",
34
+ "ValidationError",
35
+ "RateLimitError",
36
+ "InternalServerError",
37
+ "APIConnectionError",
38
+ "APITimeoutError",
39
+ "WaitTimeoutError",
40
+ "JobFailedError",
41
+ "ISOLATION_PRESETS",
42
+ "IMAGE_TOOLS",
43
+ ]
voicemint/_client.py ADDED
@@ -0,0 +1,407 @@
1
+ """HTTP clients: auth, base URL, error mapping and retries."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import os
7
+ import random
8
+ import time
9
+ from typing import Any, Dict, Mapping, Optional, Union
10
+
11
+ import httpx
12
+
13
+ from ._errors import (
14
+ APIConnectionError,
15
+ APIError,
16
+ APITimeoutError,
17
+ RateLimitError,
18
+ VoiceMintError,
19
+ make_status_error,
20
+ )
21
+ from ._version import __version__
22
+
23
+ DEFAULT_BASE_URL = "https://api.voicemint.io/api/v1"
24
+ DEFAULT_TIMEOUT = 60.0
25
+ DEFAULT_MAX_RETRIES = 2
26
+
27
+ #: Longest we will wait on a 429's Retry-After before trying again.
28
+ MAX_RETRY_AFTER = 60.0
29
+ #: Exponential backoff for 5xx / connection errors: 0.5s, 1s, 2s ... up to 8s.
30
+ INITIAL_BACKOFF = 0.5
31
+ MAX_BACKOFF = 8.0
32
+
33
+ IDEMPOTENT_METHODS = frozenset({"GET", "HEAD", "PUT", "DELETE", "OPTIONS"})
34
+
35
+ USER_AGENT = f"voicemint-python/{__version__}"
36
+
37
+ Timeout = Union[float, httpx.Timeout, None]
38
+
39
+
40
+ def _clean(mapping: Optional[Mapping[str, Any]]) -> Optional[Dict[str, Any]]:
41
+ """Drop ``None`` values so optional arguments are simply not sent."""
42
+ if mapping is None:
43
+ return None
44
+ return {k: v for k, v in mapping.items() if v is not None}
45
+
46
+
47
+ class _BaseClient:
48
+ def __init__(
49
+ self,
50
+ *,
51
+ api_key: Optional[str],
52
+ base_url: Optional[str],
53
+ timeout: Timeout,
54
+ max_retries: int,
55
+ default_headers: Optional[Mapping[str, str]],
56
+ ) -> None:
57
+ api_key = api_key or os.environ.get("VOICEMINT_API_KEY")
58
+ if not api_key:
59
+ raise VoiceMintError(
60
+ "No API key. Pass api_key=... or set the VOICEMINT_API_KEY environment variable."
61
+ )
62
+ self.api_key = api_key
63
+ self.base_url = (base_url or os.environ.get("VOICEMINT_BASE_URL") or DEFAULT_BASE_URL).rstrip("/")
64
+ self.timeout = timeout
65
+ self.max_retries = max(int(max_retries), 0)
66
+ self._default_headers = dict(default_headers or {})
67
+
68
+ # -- building requests -------------------------------------------------
69
+
70
+ def _url(self, path: str) -> str:
71
+ if path.startswith(("http://", "https://")):
72
+ return path
73
+ return f"{self.base_url}/{path.lstrip('/')}"
74
+
75
+ def _headers(self, extra: Optional[Mapping[str, str]]) -> Dict[str, str]:
76
+ headers = {
77
+ "Authorization": f"Bearer {self.api_key}",
78
+ "User-Agent": USER_AGENT,
79
+ "Accept": "application/json",
80
+ }
81
+ headers.update(self._default_headers)
82
+ if extra:
83
+ headers.update(extra)
84
+ return headers
85
+
86
+ # -- responses ---------------------------------------------------------
87
+
88
+ @staticmethod
89
+ def _body(response: httpx.Response) -> Any:
90
+ if not response.content:
91
+ return None
92
+ ctype = response.headers.get("content-type", "")
93
+ if "json" in ctype:
94
+ try:
95
+ return response.json()
96
+ except ValueError:
97
+ return response.text
98
+ if ctype.startswith("text/"):
99
+ return response.text
100
+ return response.content
101
+
102
+ def _parse(self, response: httpx.Response, raw: bool) -> Any:
103
+ if raw:
104
+ return response
105
+ return self._body(response)
106
+
107
+ def _error(self, response: httpx.Response) -> APIError:
108
+ return make_status_error(response.status_code, self._body(response), response.headers)
109
+
110
+ # -- retries -----------------------------------------------------------
111
+
112
+ @staticmethod
113
+ def _backoff(attempt: int) -> float:
114
+ delay = min(INITIAL_BACKOFF * (2 ** attempt), MAX_BACKOFF)
115
+ return delay * random.uniform(0.75, 1.25)
116
+
117
+ def _status_retry_delay(self, method: str, attempt: int, error: APIError) -> Optional[float]:
118
+ """Seconds to wait before retrying after an error status, or ``None``.
119
+
120
+ 429 is retried for every method (the limit is checked before the
121
+ endpoint runs, so nothing happened). 5xx is retried only for
122
+ idempotent methods: a POST may already have done its work (and
123
+ charged credits) before failing.
124
+ """
125
+ if attempt >= self.max_retries:
126
+ return None
127
+ if isinstance(error, RateLimitError):
128
+ wait = error.retry_after if error.retry_after is not None else self._backoff(attempt)
129
+ return min(wait, MAX_RETRY_AFTER)
130
+ if error.status >= 500 and method in IDEMPOTENT_METHODS:
131
+ return self._backoff(attempt)
132
+ return None
133
+
134
+ def _connection_retry_delay(self, method: str, attempt: int) -> Optional[float]:
135
+ if attempt >= self.max_retries or method not in IDEMPOTENT_METHODS:
136
+ return None
137
+ return self._backoff(attempt)
138
+
139
+ @staticmethod
140
+ def _connection_error(exc: Exception) -> APIConnectionError:
141
+ if isinstance(exc, httpx.TimeoutException):
142
+ return APITimeoutError(f"Request timed out: {exc}")
143
+ return APIConnectionError(f"Connection error: {exc}")
144
+
145
+
146
+ class VoiceMint(_BaseClient):
147
+ """Synchronous VoiceMint client.
148
+
149
+ >>> from voicemint import VoiceMint
150
+ >>> client = VoiceMint() # reads VOICEMINT_API_KEY
151
+ >>> client.agents.chat("agent_id", "Hello!")["reply"]
152
+ """
153
+
154
+ def __init__(
155
+ self,
156
+ api_key: Optional[str] = None,
157
+ *,
158
+ base_url: Optional[str] = None,
159
+ timeout: Timeout = DEFAULT_TIMEOUT,
160
+ max_retries: int = DEFAULT_MAX_RETRIES,
161
+ default_headers: Optional[Mapping[str, str]] = None,
162
+ http_client: Optional[httpx.Client] = None,
163
+ ) -> None:
164
+ super().__init__(
165
+ api_key=api_key,
166
+ base_url=base_url,
167
+ timeout=timeout,
168
+ max_retries=max_retries,
169
+ default_headers=default_headers,
170
+ )
171
+ self._owns_http = http_client is None
172
+ self._http = http_client or httpx.Client(timeout=timeout)
173
+ self._sleep = time.sleep
174
+
175
+ from .resources import (
176
+ Agents,
177
+ Audio,
178
+ Calls,
179
+ Campaigns,
180
+ Credits,
181
+ Image,
182
+ Jobs,
183
+ Knowledge,
184
+ LiveSessions,
185
+ Meet,
186
+ Music,
187
+ Numbers,
188
+ SpeechToText,
189
+ Telephony,
190
+ TextToSpeech,
191
+ Translation,
192
+ Video,
193
+ Voices,
194
+ )
195
+
196
+ self.agents = Agents(self)
197
+ self.knowledge = Knowledge(self)
198
+ self.text_to_speech = TextToSpeech(self)
199
+ self.speech_to_text = SpeechToText(self)
200
+ self.credits = Credits(self)
201
+ self.calls = Calls(self)
202
+ self.numbers = Numbers(self)
203
+ self.telephony = Telephony(self)
204
+ self.campaigns = Campaigns(self)
205
+ self.live_sessions = LiveSessions(self)
206
+ # Voice Lab, Music, Video, Image, Meet (0.3.0)
207
+ self.voices = Voices(self)
208
+ self.translation = Translation(self)
209
+ self.audio = Audio(self)
210
+ self.music = Music(self)
211
+ self.video = Video(self)
212
+ self.image = Image(self)
213
+ self.jobs = Jobs(self)
214
+ self.meet = Meet(self)
215
+
216
+ def request(
217
+ self,
218
+ method: str,
219
+ path: str,
220
+ *,
221
+ json: Any = None,
222
+ params: Optional[Mapping[str, Any]] = None,
223
+ files: Any = None,
224
+ data: Optional[Mapping[str, Any]] = None,
225
+ headers: Optional[Mapping[str, str]] = None,
226
+ timeout: Timeout = None,
227
+ raw: bool = False,
228
+ ) -> Any:
229
+ """Call any endpoint of the API.
230
+
231
+ ``path`` is relative to the base URL (``/agents``, ``/credits/balance``).
232
+ ``json`` is sent as a JSON body; ``files`` (httpx's format, e.g.
233
+ ``{"file": ("a.pdf", b"...", "application/pdf")}``) and ``data``
234
+ (form fields) as multipart. Returns the parsed JSON, ``bytes`` for
235
+ binary responses (audio), ``str`` for text, ``None`` for an empty
236
+ body — or the ``httpx.Response`` itself when ``raw=True``.
237
+ """
238
+ method = method.upper()
239
+ url = self._url(path)
240
+ req_headers = self._headers(headers)
241
+ req_params = _clean(params)
242
+ attempt = 0
243
+ while True:
244
+ try:
245
+ response = self._http.request(
246
+ method,
247
+ url,
248
+ json=json,
249
+ params=req_params,
250
+ files=files,
251
+ data=_clean(data),
252
+ headers=req_headers,
253
+ timeout=timeout if timeout is not None else self.timeout,
254
+ )
255
+ except httpx.TransportError as exc:
256
+ delay = self._connection_retry_delay(method, attempt)
257
+ if delay is None:
258
+ raise self._connection_error(exc) from exc
259
+ self._sleep(delay)
260
+ attempt += 1
261
+ continue
262
+
263
+ if response.status_code < 400:
264
+ return self._parse(response, raw)
265
+ error = self._error(response)
266
+ delay = self._status_retry_delay(method, attempt, error)
267
+ if delay is None:
268
+ raise error
269
+ response.close()
270
+ self._sleep(delay)
271
+ attempt += 1
272
+
273
+ def close(self) -> None:
274
+ if self._owns_http:
275
+ self._http.close()
276
+
277
+ def __enter__(self) -> "VoiceMint":
278
+ return self
279
+
280
+ def __exit__(self, *exc: Any) -> None:
281
+ self.close()
282
+
283
+
284
+ class AsyncVoiceMint(_BaseClient):
285
+ """Asyncio VoiceMint client; same surface as :class:`VoiceMint`, every
286
+ method is awaited."""
287
+
288
+ def __init__(
289
+ self,
290
+ api_key: Optional[str] = None,
291
+ *,
292
+ base_url: Optional[str] = None,
293
+ timeout: Timeout = DEFAULT_TIMEOUT,
294
+ max_retries: int = DEFAULT_MAX_RETRIES,
295
+ default_headers: Optional[Mapping[str, str]] = None,
296
+ http_client: Optional[httpx.AsyncClient] = None,
297
+ ) -> None:
298
+ super().__init__(
299
+ api_key=api_key,
300
+ base_url=base_url,
301
+ timeout=timeout,
302
+ max_retries=max_retries,
303
+ default_headers=default_headers,
304
+ )
305
+ self._owns_http = http_client is None
306
+ self._http = http_client or httpx.AsyncClient(timeout=timeout)
307
+ self._sleep = asyncio.sleep
308
+
309
+ from .resources import (
310
+ AsyncAgents,
311
+ AsyncAudio,
312
+ AsyncCalls,
313
+ AsyncCampaigns,
314
+ AsyncCredits,
315
+ AsyncImage,
316
+ AsyncJobs,
317
+ AsyncKnowledge,
318
+ AsyncLiveSessions,
319
+ AsyncMeet,
320
+ AsyncMusic,
321
+ AsyncNumbers,
322
+ AsyncSpeechToText,
323
+ AsyncTelephony,
324
+ AsyncTextToSpeech,
325
+ AsyncTranslation,
326
+ AsyncVideo,
327
+ AsyncVoices,
328
+ )
329
+
330
+ self.agents = AsyncAgents(self)
331
+ self.knowledge = AsyncKnowledge(self)
332
+ self.text_to_speech = AsyncTextToSpeech(self)
333
+ self.speech_to_text = AsyncSpeechToText(self)
334
+ self.credits = AsyncCredits(self)
335
+ self.calls = AsyncCalls(self)
336
+ self.numbers = AsyncNumbers(self)
337
+ self.telephony = AsyncTelephony(self)
338
+ self.campaigns = AsyncCampaigns(self)
339
+ self.live_sessions = AsyncLiveSessions(self)
340
+ # Voice Lab, Music, Video, Image, Meet (0.3.0)
341
+ self.voices = AsyncVoices(self)
342
+ self.translation = AsyncTranslation(self)
343
+ self.audio = AsyncAudio(self)
344
+ self.music = AsyncMusic(self)
345
+ self.video = AsyncVideo(self)
346
+ self.image = AsyncImage(self)
347
+ self.jobs = AsyncJobs(self)
348
+ self.meet = AsyncMeet(self)
349
+
350
+ async def request(
351
+ self,
352
+ method: str,
353
+ path: str,
354
+ *,
355
+ json: Any = None,
356
+ params: Optional[Mapping[str, Any]] = None,
357
+ files: Any = None,
358
+ data: Optional[Mapping[str, Any]] = None,
359
+ headers: Optional[Mapping[str, str]] = None,
360
+ timeout: Timeout = None,
361
+ raw: bool = False,
362
+ ) -> Any:
363
+ """Async twin of :meth:`VoiceMint.request`."""
364
+ method = method.upper()
365
+ url = self._url(path)
366
+ req_headers = self._headers(headers)
367
+ req_params = _clean(params)
368
+ attempt = 0
369
+ while True:
370
+ try:
371
+ response = await self._http.request(
372
+ method,
373
+ url,
374
+ json=json,
375
+ params=req_params,
376
+ files=files,
377
+ data=_clean(data),
378
+ headers=req_headers,
379
+ timeout=timeout if timeout is not None else self.timeout,
380
+ )
381
+ except httpx.TransportError as exc:
382
+ delay = self._connection_retry_delay(method, attempt)
383
+ if delay is None:
384
+ raise self._connection_error(exc) from exc
385
+ await self._sleep(delay)
386
+ attempt += 1
387
+ continue
388
+
389
+ if response.status_code < 400:
390
+ return self._parse(response, raw)
391
+ error = self._error(response)
392
+ delay = self._status_retry_delay(method, attempt, error)
393
+ if delay is None:
394
+ raise error
395
+ await response.aclose()
396
+ await self._sleep(delay)
397
+ attempt += 1
398
+
399
+ async def aclose(self) -> None:
400
+ if self._owns_http:
401
+ await self._http.aclose()
402
+
403
+ async def __aenter__(self) -> "AsyncVoiceMint":
404
+ return self
405
+
406
+ async def __aexit__(self, *exc: Any) -> None:
407
+ await self.aclose()
voicemint/_errors.py ADDED
@@ -0,0 +1,172 @@
1
+ """Exceptions raised by the VoiceMint SDK."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from typing import Any, Mapping, Optional
7
+
8
+ __all__ = [
9
+ "VoiceMintError",
10
+ "APIError",
11
+ "BadRequestError",
12
+ "AuthenticationError",
13
+ "InsufficientCreditsError",
14
+ "PermissionDeniedError",
15
+ "NotFoundError",
16
+ "ValidationError",
17
+ "RateLimitError",
18
+ "InternalServerError",
19
+ "APIConnectionError",
20
+ "APITimeoutError",
21
+ ]
22
+
23
+
24
+ class VoiceMintError(Exception):
25
+ """Base class for every error this SDK raises."""
26
+
27
+
28
+ class APIError(VoiceMintError):
29
+ """The API answered with an error status.
30
+
31
+ ``status`` is the HTTP status, ``message`` the readable text taken from
32
+ the response's ``detail`` field, ``body`` the parsed JSON body (or the raw
33
+ text when the body is not JSON) and ``headers`` the response headers.
34
+ """
35
+
36
+ def __init__(
37
+ self,
38
+ message: str,
39
+ *,
40
+ status: int,
41
+ body: Any = None,
42
+ headers: Optional[Mapping[str, str]] = None,
43
+ ) -> None:
44
+ super().__init__(message)
45
+ self.message = message
46
+ self.status = status
47
+ self.status_code = status
48
+ self.body = body
49
+ self.headers = dict(headers or {})
50
+
51
+ def __str__(self) -> str:
52
+ return f"{self.status}: {self.message}"
53
+
54
+
55
+ class BadRequestError(APIError):
56
+ """400 — the request was understood but rejected (e.g. a bad reference)."""
57
+
58
+
59
+ class AuthenticationError(APIError):
60
+ """401 — missing, wrong, revoked or expired API key."""
61
+
62
+
63
+ class InsufficientCreditsError(APIError):
64
+ """402 — the key owner's account does not have enough credits."""
65
+
66
+
67
+ class PermissionDeniedError(APIError):
68
+ """403 — endpoint not available to API keys, outside the key's
69
+ permissions, or the owner's account is inactive."""
70
+
71
+
72
+ class NotFoundError(APIError):
73
+ """404 — the resource does not exist or is not yours."""
74
+
75
+
76
+ class ValidationError(APIError):
77
+ """422 — the request body or parameters failed validation."""
78
+
79
+
80
+ class RateLimitError(APIError):
81
+ """429 — over the key's per-minute limit. ``retry_after`` is the number of
82
+ seconds the server asked us to wait (``None`` if it did not say)."""
83
+
84
+ def __init__(self, message: str, *, retry_after: Optional[float] = None, **kwargs: Any) -> None:
85
+ super().__init__(message, **kwargs)
86
+ self.retry_after = retry_after
87
+
88
+
89
+ class InternalServerError(APIError):
90
+ """5xx — the server failed. Idempotent requests are retried automatically."""
91
+
92
+
93
+ class APIConnectionError(VoiceMintError):
94
+ """The request never got an HTTP answer (DNS, refused connection, reset...)."""
95
+
96
+
97
+ class APITimeoutError(APIConnectionError):
98
+ """The request timed out."""
99
+
100
+
101
+ _BY_STATUS = {
102
+ 400: BadRequestError,
103
+ 401: AuthenticationError,
104
+ 402: InsufficientCreditsError,
105
+ 403: PermissionDeniedError,
106
+ 404: NotFoundError,
107
+ 422: ValidationError,
108
+ }
109
+
110
+
111
+ def _message_from_detail(detail: Any) -> str:
112
+ """Readable text from FastAPI's ``detail`` (a string, a validation error
113
+ list, or an arbitrary object)."""
114
+ if isinstance(detail, str):
115
+ return detail
116
+ if isinstance(detail, list):
117
+ parts = []
118
+ for item in detail:
119
+ if isinstance(item, Mapping) and "msg" in item:
120
+ loc = ".".join(str(x) for x in item.get("loc", ()) if x != "body")
121
+ parts.append(f"{loc}: {item['msg']}" if loc else str(item["msg"]))
122
+ else:
123
+ parts.append(str(item))
124
+ return "; ".join(parts)
125
+ if isinstance(detail, Mapping):
126
+ for key in ("message", "error"):
127
+ if isinstance(detail.get(key), str):
128
+ return detail[key]
129
+ return json.dumps(detail, default=str)
130
+
131
+
132
+ def parse_retry_after(value: Optional[str]) -> Optional[float]:
133
+ """``Retry-After`` as seconds: either a number or an HTTP date."""
134
+ if not value:
135
+ return None
136
+ value = value.strip()
137
+ try:
138
+ return max(float(value), 0.0)
139
+ except ValueError:
140
+ pass
141
+ try:
142
+ import datetime as _dt
143
+ from email.utils import parsedate_to_datetime
144
+
145
+ when = parsedate_to_datetime(value)
146
+ if when.tzinfo is None:
147
+ when = when.replace(tzinfo=_dt.timezone.utc)
148
+ return max((when - _dt.datetime.now(_dt.timezone.utc)).total_seconds(), 0.0)
149
+ except Exception: # noqa: BLE001
150
+ return None
151
+
152
+
153
+ def make_status_error(status: int, body: Any, headers: Mapping[str, str]) -> APIError:
154
+ if isinstance(body, Mapping) and "detail" in body:
155
+ message = _message_from_detail(body["detail"])
156
+ elif isinstance(body, str) and body.strip():
157
+ message = body.strip()[:500]
158
+ else:
159
+ message = f"HTTP {status}"
160
+
161
+ if status == 429:
162
+ return RateLimitError(
163
+ message,
164
+ status=status,
165
+ body=body,
166
+ headers=headers,
167
+ retry_after=parse_retry_after(headers.get("retry-after")),
168
+ )
169
+ cls = _BY_STATUS.get(status)
170
+ if cls is None:
171
+ cls = InternalServerError if status >= 500 else APIError
172
+ return cls(message, status=status, body=body, headers=headers)
voicemint/_files.py ADDED
@@ -0,0 +1,58 @@
1
+ """Turning the many ways a caller can name a file into one multipart part."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import mimetypes
6
+ import os
7
+ from typing import IO, Optional, Tuple, Union
8
+
9
+ FileInput = Union[str, "os.PathLike[str]", bytes, bytearray, IO[bytes], Tuple]
10
+ """A path, raw bytes, an open binary file, or an httpx-style
11
+ ``(filename, content[, content_type])`` tuple."""
12
+
13
+ FilePart = Tuple[str, bytes, str]
14
+
15
+
16
+ def to_file_part(
17
+ file: FileInput,
18
+ filename: Optional[str] = None,
19
+ content_type: Optional[str] = None,
20
+ default_name: str = "upload",
21
+ ) -> FilePart:
22
+ """Read ``file`` fully into memory and return ``(name, bytes, type)``.
23
+
24
+ Reading up front means the same body can be sent again if the request
25
+ is retried (e.g. after a 429). Uploads are capped at 25 MB by the API.
26
+ """
27
+ name = filename
28
+ if isinstance(file, tuple):
29
+ if len(file) < 2:
30
+ raise TypeError("A file tuple must be (filename, content[, content_type])")
31
+ name = name or file[0]
32
+ content = file[1]
33
+ if len(file) > 2 and not content_type:
34
+ content_type = file[2]
35
+ if hasattr(content, "read"):
36
+ content = content.read()
37
+ elif isinstance(file, (bytes, bytearray)):
38
+ content = bytes(file)
39
+ elif isinstance(file, (str, os.PathLike)):
40
+ path = os.fspath(file)
41
+ with open(path, "rb") as fh:
42
+ content = fh.read()
43
+ name = name or os.path.basename(path)
44
+ elif hasattr(file, "read"):
45
+ content = file.read()
46
+ if isinstance(content, str):
47
+ raise TypeError("Open the file in binary mode ('rb').")
48
+ if not name:
49
+ raw_name = getattr(file, "name", None)
50
+ if isinstance(raw_name, str):
51
+ name = os.path.basename(raw_name)
52
+ else:
53
+ raise TypeError(f"Unsupported file input: {type(file).__name__}")
54
+
55
+ name = name or default_name
56
+ if not content_type:
57
+ content_type = mimetypes.guess_type(name)[0] or "application/octet-stream"
58
+ return name, bytes(content), content_type