deapi-mcp 0.7.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.
@@ -0,0 +1,1195 @@
1
+ """Audio processing tools for deAPI MCP server."""
2
+
3
+ from typing import Annotated, Any, Literal, Optional
4
+
5
+ from pydantic import Field
6
+
7
+ from ..deapi_client import DeapiAPIError, get_client
8
+ from ..middleware import ensure_model_cache, get_cached_model
9
+ from ..polling_manager import PollingManager
10
+ from ..utils import form_bool, prepare_audio_upload_async, prepare_video_upload_async
11
+ from ._price_helpers import _to_number, get_model_defaults, get_model_features, get_model_limits
12
+ from ._responses import (
13
+ build_job_response,
14
+ build_price_response,
15
+ decode_transcript,
16
+ input_error_response,
17
+ )
18
+
19
+ # Each TTS model supports exactly one mode and rejects the others with a 422,
20
+ # so the mode can be derived from the model card instead of being asked for.
21
+ _TTS_MODE_BY_FEATURE = (
22
+ ("supports_voice_clone", "voice_clone"),
23
+ ("supports_voice_design", "voice_design"),
24
+ ("supports_custom_voice", "custom_voice"),
25
+ )
26
+
27
+
28
+ TimestampLevel = Literal["segment", "word", "char"]
29
+
30
+ _TS_LEVEL_HELP = (
31
+ "Timestamp granularity: 'segment', 'word' or 'char'; implies include_ts. Only the levels "
32
+ "a model lists under 'ts_level' in the model list are accepted (WhisperLargeV3: segment "
33
+ "only). Finer than segment costs 1.5x on models that price it"
34
+ )
35
+ _DIARIZE_HELP = (
36
+ "Label who is speaking; implies include_ts. Only on models marked 'diarize' in the model "
37
+ "list (WhisperLargeV3 rejects it). Costs 1.5x, not stacked with a finer ts_level"
38
+ )
39
+
40
+ # WhisperLargeV3 ignores `lang`; Ct2 costs the same, honours `lang`, returns segments
41
+ # and supports diarize and word timestamps.
42
+ DEFAULT_TRANSCRIPTION_MODEL = "WhisperLargeV3Ct2"
43
+ _MODEL_HELP = (
44
+ "Whisper model from the model list. Default WhisperLargeV3Ct2: honours lang, returns "
45
+ "segments, supports diarize and word timestamps"
46
+ )
47
+ _LANG_HELP = (
48
+ "Language of the recording as an ISO code, e.g. 'en', 'pl'. Set it whenever you know the "
49
+ "language: auto-detection can pick the wrong one, e.g. on short or accented audio. It forces "
50
+ "the output language, so a wrong code returns a translation instead of a transcript. "
51
+ "Auto-detected when unset"
52
+ )
53
+
54
+
55
+ def _add_transcription_params(
56
+ form_data: dict[str, Any],
57
+ ts_level: Optional[str] = None,
58
+ diarize: Optional[bool] = None,
59
+ lang: Optional[str] = None,
60
+ include_metadata: Optional[bool] = None,
61
+ ) -> dict[str, Any]:
62
+ """Add the optional transcription controls to a form payload.
63
+
64
+ Each is omitted when unset so the API applies its own default, and each is
65
+ supported only by some models — `ts_level='word'` and `diarize` in
66
+ particular are rejected by models that do not declare them in
67
+ `info.limits.timestamp_levels`.
68
+
69
+ A `ts_level` only means something with timestamps on: without `include_ts`
70
+ the API silently collapses it back to 'segment' and returns no timestamps
71
+ at all, so asking for a level turns them on.
72
+ """
73
+ if ts_level:
74
+ form_data["ts_level"] = ts_level
75
+ form_data["include_ts"] = form_bool(True)
76
+ if diarize is not None:
77
+ form_data["diarize"] = form_bool(diarize)
78
+ if lang:
79
+ form_data["lang"] = lang
80
+ if include_metadata is not None:
81
+ form_data["include_metadata"] = form_bool(include_metadata)
82
+ return form_data
83
+
84
+
85
+ def _pinned_limit(model_slug: str, key: str) -> Any:
86
+ """The value a model fixes a knob at (`min_<key>` == `max_<key>`), else None.
87
+
88
+ The music cards publish no defaults for steps or guidance, only a range
89
+ that every current model pins to one value (steps 8, guidance 1).
90
+ """
91
+ limits = get_model_limits(model_slug)
92
+ lo, hi = limits.get(f"min_{key}"), limits.get(f"max_{key}")
93
+ return _to_number(lo) if lo is not None and str(lo) == str(hi) else None
94
+
95
+
96
+ def _tts_defaults(model_slug: str, lang: Optional[str] = None) -> dict[str, Any]:
97
+ """Voice, language and format defaults from the model's own card.
98
+
99
+ These differ per model in ways a fixed default cannot satisfy: Kokoro
100
+ speaks "en-us" while the Qwen3 models want "English", and every current
101
+ TTS model emits mp3 only. A hardcoded lang/format sent the wrong value to
102
+ at least one model in every case, which the API rejected with a 422.
103
+
104
+ The voice has to belong to the language: the API checks it against that
105
+ language's own voice list, so Kokoro's default 'af_alloy' is a 422 with
106
+ lang='fr-fr'. Given a `lang`, the card default is kept only when that
107
+ language offers it, otherwise the language's first voice is used.
108
+ """
109
+ defaults = get_model_defaults(model_slug)
110
+ card = get_cached_model(model_slug)
111
+ languages = card.languages if card and card.languages else []
112
+
113
+ # When the card's defaults are silent, the first listed language and its
114
+ # first voice are at least values the model is known to accept.
115
+ resolved_lang = lang or defaults.get("lang") or (languages[0].slug if languages else None)
116
+ language = next((entry for entry in languages if entry.slug == resolved_lang), None)
117
+ if language is None and languages and not lang:
118
+ language = languages[0]
119
+ voices = [v.slug for v in language.voices] if language else []
120
+
121
+ voice = defaults.get("voice")
122
+ if voices and voice not in voices:
123
+ voice = voices[0]
124
+
125
+ return {
126
+ "voice": voice or (voices[0] if voices else None),
127
+ "lang": resolved_lang,
128
+ "format": defaults.get("format"),
129
+ "speed": _to_number(defaults.get("speed")),
130
+ "sample_rate": _to_number(defaults.get("sample_rate")),
131
+ }
132
+
133
+
134
+ def _music_format_default(model_slug: str) -> str:
135
+ """Output format for a music model when the caller leaves it unset.
136
+
137
+ The card's own default first, then the first format it lists as
138
+ supported, then mp3 — the one format every current model accepts.
139
+ """
140
+ fmt = get_model_defaults(model_slug).get("format")
141
+ if not fmt:
142
+ formats = get_model_limits(model_slug).get("output_formats")
143
+ if isinstance(formats, list) and formats:
144
+ fmt = formats[0]
145
+ return str(fmt) if fmt else "mp3"
146
+
147
+
148
+ def _resolve_tts_mode(model_slug: str) -> Optional[str]:
149
+ """Derive the TTS mode a model supports from its cached model card.
150
+
151
+ Returns None when the model card is unavailable or advertises nothing, in
152
+ which case the field is omitted and the API applies its own default
153
+ ('custom_voice').
154
+ """
155
+ features = get_model_features(model_slug)
156
+ for feature, mode in _TTS_MODE_BY_FEATURE:
157
+ value = features.get(feature)
158
+ # Feature flags arrive as "0"/"1" strings on some cards and as booleans
159
+ # on others; "0" is truthy as a string, so compare explicitly.
160
+ if value in (True, 1, "1", "true", "True"):
161
+ return mode
162
+ return None
163
+
164
+
165
+ async def audio_transcription(
166
+ audio: Annotated[str, Field(description="Audio file (base64 encoded or URL)")],
167
+ include_ts: Annotated[bool, Field(description="Include timestamps in transcription")],
168
+ model: Annotated[str, Field(description=_MODEL_HELP)] = DEFAULT_TRANSCRIPTION_MODEL,
169
+ ts_level: Annotated[Optional[TimestampLevel], Field(description=_TS_LEVEL_HELP)] = None,
170
+ diarize: Annotated[Optional[bool], Field(description=_DIARIZE_HELP)] = None,
171
+ lang: Annotated[
172
+ Optional[str],
173
+ Field(
174
+ max_length=16,
175
+ description=_LANG_HELP,
176
+ ),
177
+ ] = None,
178
+ return_result_in_response: Annotated[
179
+ bool,
180
+ Field(
181
+ description="Return transcription inline. Set to False for large files to get download URL instead"
182
+ ),
183
+ ] = True,
184
+ webhook_url: Annotated[
185
+ Optional[str],
186
+ Field(
187
+ description="HTTPS URL for deAPI to call when this job finishes. Notifies your own systems; the tool still returns the result here"
188
+ ),
189
+ ] = None,
190
+ webhook_secret: Annotated[
191
+ Optional[str],
192
+ Field(
193
+ description="32-255 char key deAPI signs the callback with (HMAC-SHA256). Needs webhook_url. A secret given in chat stays in the transcript"
194
+ ),
195
+ ] = None,
196
+ ) -> dict[str, Any]:
197
+ """Transcribe audio file to text using Whisper models.
198
+
199
+ Converts audio files to text transcription with optional timestamps.
200
+ Automatically polls until transcription is complete.
201
+
202
+ Returns:
203
+ dict: Contains 'success', 'job_id', 'result_url' and, inline, 'result' with
204
+ the transcript text. Models marked 'output=json' in the model list
205
+ (WhisperLargeV3Ct2) also return 'segments' (start/end in seconds, text,
206
+ speaker and words when asked for) and 'language'. Other models write
207
+ timestamps into the text itself, e.g. '[0:50 - 1:49] ...'
208
+ """
209
+ try:
210
+ client = get_client()
211
+ async with client:
212
+ # Prepare audio file for multipart upload
213
+ field_name, file_tuple = await prepare_audio_upload_async(audio, "source_file")
214
+
215
+ # Prepare form data (non-file parameters)
216
+ form_data = {
217
+ "include_ts": form_bool(include_ts),
218
+ "model": model,
219
+ "return_result_in_response": form_bool(return_result_in_response),
220
+ }
221
+ _add_transcription_params(form_data, ts_level, diarize, lang)
222
+
223
+ job_response = await client.submit_job(
224
+ endpoint="audio/transcriptions",
225
+ data=form_data,
226
+ files={field_name: file_tuple},
227
+ webhook_url=webhook_url,
228
+ webhook_secret=webhook_secret,
229
+ )
230
+ job_id = job_response.data.request_id
231
+
232
+ # Poll for completion
233
+ polling_manager = PollingManager(client, job_type="audio")
234
+ result = await polling_manager.poll_until_complete(job_id)
235
+
236
+ return decode_transcript(build_job_response(result, job_id))
237
+
238
+ except ValueError as e:
239
+ return {"success": False, "error": f"Invalid audio format: {str(e)}"}
240
+ except DeapiAPIError as e:
241
+ return {"success": False, "error": f"API error: {str(e)}"}
242
+ except Exception as e:
243
+ return {"success": False, "error": f"Unexpected error: {str(e)}"}
244
+
245
+
246
+ async def audio_transcription_price(
247
+ include_ts: Annotated[bool, Field(description="Include timestamps")],
248
+ duration_seconds: Annotated[
249
+ float, Field(gt=0, description="Length of the audio in seconds, which the price follows")
250
+ ],
251
+ model: Annotated[str, Field(description=_MODEL_HELP)] = DEFAULT_TRANSCRIPTION_MODEL,
252
+ ts_level: Annotated[Optional[TimestampLevel], Field(description=_TS_LEVEL_HELP)] = None,
253
+ diarize: Annotated[Optional[bool], Field(description=_DIARIZE_HELP)] = None,
254
+ lang: Annotated[Optional[str], Field(max_length=16, description=_LANG_HELP)] = None,
255
+ ) -> dict[str, Any]:
256
+ """Calculate price for audio transcription.
257
+
258
+ Quotes an uploaded audio file by its length. For a URL use
259
+ video_url_transcription_price or audio_url_transcription_price.
260
+
261
+ Returns:
262
+ dict: Contains 'success' and 'price' information
263
+ """
264
+ try:
265
+ client = get_client()
266
+ async with client:
267
+ form_data = {
268
+ "include_ts": form_bool(include_ts),
269
+ "model": model,
270
+ }
271
+ _add_transcription_params(form_data, ts_level, diarize, lang)
272
+
273
+ form_data["duration_seconds"] = str(duration_seconds)
274
+
275
+ price_response = await client.calculate_price(
276
+ endpoint="audio/transcriptions/price",
277
+ data=form_data,
278
+ )
279
+
280
+ return build_price_response(price_response)
281
+
282
+ except DeapiAPIError as e:
283
+ return {"success": False, "error": f"API error: {str(e)}"}
284
+ except Exception as e:
285
+ return {"success": False, "error": f"Unexpected error: {str(e)}"}
286
+
287
+
288
+ async def text_to_audio(
289
+ text: Annotated[str, Field(description="Text to convert to speech")],
290
+ model: Annotated[str, Field(description="TTS model name (e.g., 'Kokoro')")],
291
+ voice: Annotated[
292
+ Optional[str],
293
+ Field(
294
+ description="Voice name from the model list for the chosen lang (e.g. Kokoro en-us 'af_alloy'). Defaults to the model's default voice for that language"
295
+ ),
296
+ ] = None,
297
+ lang: Annotated[
298
+ Optional[str],
299
+ Field(
300
+ description="Language code as the model expects it (Kokoro: 'en-us'; Qwen3: 'English'). Defaults to the model's own"
301
+ ),
302
+ ] = None,
303
+ speed: Annotated[
304
+ Optional[float],
305
+ Field(
306
+ ge=0.5,
307
+ description="Speech speed. Per model (see 'speed' in the model list; most fix it at 1). Defaults to the model's own",
308
+ ),
309
+ ] = None,
310
+ audio_format: Annotated[
311
+ Optional[str],
312
+ Field(description="Output format. Defaults to the model's own; most models emit mp3 only"),
313
+ ] = None,
314
+ sample_rate: Annotated[
315
+ Optional[int], Field(description="Sample rate in Hz. Defaults to the model's own")
316
+ ] = None,
317
+ mode: Annotated[
318
+ Optional[str],
319
+ Field(
320
+ description="TTS mode: 'custom_voice', 'voice_clone' or 'voice_design'. Leave unset to use the mode the model supports"
321
+ ),
322
+ ] = None,
323
+ ref_audio: Annotated[
324
+ Optional[str],
325
+ Field(
326
+ description="Reference audio sample to clone (data URI, base64 or URL). Requires mode='voice_clone'"
327
+ ),
328
+ ] = None,
329
+ ref_text: Annotated[
330
+ Optional[str], Field(description="Transcript of ref_audio, improves cloning accuracy")
331
+ ] = None,
332
+ instruct: Annotated[
333
+ Optional[str],
334
+ Field(
335
+ description="Voice description for voice_design models (required there), or style/emotion control in custom_voice mode, e.g. 'speak slowly and warmly'"
336
+ ),
337
+ ] = None,
338
+ webhook_url: Annotated[
339
+ Optional[str],
340
+ Field(
341
+ description="HTTPS URL for deAPI to call when this job finishes. Notifies your own systems; the tool still returns the result here"
342
+ ),
343
+ ] = None,
344
+ webhook_secret: Annotated[
345
+ Optional[str],
346
+ Field(
347
+ description="32-255 char key deAPI signs the callback with (HMAC-SHA256). Needs webhook_url. A secret given in chat stays in the transcript"
348
+ ),
349
+ ] = None,
350
+ ) -> dict[str, Any]:
351
+ """Convert text to speech audio using TTS models.
352
+
353
+ Generates natural-sounding speech from text with customizable voice and parameters.
354
+
355
+ Supports three modes, and each model implements exactly one — passing the
356
+ wrong one is rejected with a 422. Leave `mode` unset and it is taken from
357
+ the model's own card:
358
+ - custom_voice: pick a preset `voice` (e.g. Kokoro, Chatterbox)
359
+ - voice_clone: reproduce the speaker in `ref_audio` (+ optional `ref_text`)
360
+ - voice_design: build a voice from an `instruct` description
361
+
362
+ `lang` and `voice` values are per-model and listed under each model in the
363
+ "Available models" section below (Kokoro: lang 'en-us', voice 'af_alloy';
364
+ Qwen3: lang 'English'). Leave them unset to use the model's own defaults.
365
+
366
+ Returns:
367
+ dict: Contains 'success', 'result_url' with audio URL, 'job_id'
368
+ """
369
+ try:
370
+ client = get_client()
371
+ async with client:
372
+ # Mode, lang and voice all come from the card; a cold cache (first call
373
+ # after a restart) would send Kokoro's lang to a Qwen3 model.
374
+ await ensure_model_cache(model=model)
375
+ resolved_mode = mode or _resolve_tts_mode(model)
376
+
377
+ card = _tts_defaults(model, lang)
378
+ request_data = {
379
+ "text": text,
380
+ "model": model,
381
+ "voice": voice if voice is not None else card["voice"],
382
+ "lang": lang if lang is not None else (card["lang"] or "en-us"),
383
+ "speed": speed if speed is not None else (card["speed"] or 1.0),
384
+ "format": audio_format if audio_format is not None else (card["format"] or "mp3"),
385
+ "sample_rate": (
386
+ sample_rate if sample_rate is not None else (card["sample_rate"] or 24000)
387
+ ),
388
+ }
389
+ if resolved_mode:
390
+ request_data["mode"] = resolved_mode
391
+ if ref_text:
392
+ request_data["ref_text"] = ref_text
393
+ if instruct:
394
+ request_data["instruct"] = instruct
395
+
396
+ if ref_audio:
397
+ # ref_audio is a file upload, so the whole request has to become
398
+ # multipart; JSON cannot carry it.
399
+ field_name, file_tuple = await prepare_audio_upload_async(
400
+ ref_audio, field_name="ref_audio"
401
+ )
402
+ form_data = {
403
+ key: form_bool(value) if isinstance(value, bool) else str(value)
404
+ for key, value in request_data.items()
405
+ }
406
+ job_response = await client.submit_job(
407
+ endpoint="audio/speech",
408
+ data=form_data,
409
+ files={field_name: file_tuple},
410
+ webhook_url=webhook_url,
411
+ webhook_secret=webhook_secret,
412
+ )
413
+ else:
414
+ job_response = await client.submit_job(
415
+ endpoint="audio/speech",
416
+ json_data=request_data,
417
+ webhook_url=webhook_url,
418
+ webhook_secret=webhook_secret,
419
+ )
420
+ job_id = job_response.data.request_id
421
+
422
+ polling_manager = PollingManager(client, job_type="audio")
423
+ result = await polling_manager.poll_until_complete(job_id)
424
+
425
+ return build_job_response(result, job_id)
426
+
427
+ except ValueError as e:
428
+ return {"success": False, "error": f"Invalid audio format: {str(e)}"}
429
+ except DeapiAPIError as e:
430
+ return {"success": False, "error": f"API error: {str(e)}"}
431
+ except Exception as e:
432
+ return {"success": False, "error": f"Unexpected error: {str(e)}"}
433
+
434
+
435
+ async def text_to_audio_price(
436
+ text: Annotated[str, Field(description="Text for price calculation")],
437
+ model: Annotated[str, Field(description="TTS model name (e.g., 'Kokoro')")],
438
+ voice: Annotated[
439
+ Optional[str],
440
+ Field(
441
+ description="Voice name from the model list for the chosen lang (e.g. Kokoro en-us 'af_alloy'). Defaults to the model's default voice for that language"
442
+ ),
443
+ ] = None,
444
+ lang: Annotated[
445
+ Optional[str],
446
+ Field(
447
+ description="Language code as the model expects it (Kokoro: 'en-us'; Qwen3: 'English'). Defaults to the model's own"
448
+ ),
449
+ ] = None,
450
+ speed: Annotated[
451
+ Optional[float],
452
+ Field(
453
+ ge=0.5,
454
+ description="Speech speed. Per model (see 'speed' in the model list; most fix it at 1). Defaults to the model's own",
455
+ ),
456
+ ] = None,
457
+ audio_format: Annotated[
458
+ Optional[str],
459
+ Field(description="Output format. Defaults to the model's own; most models emit mp3 only"),
460
+ ] = None,
461
+ sample_rate: Annotated[
462
+ Optional[int], Field(description="Sample rate in Hz. Defaults to the model's own")
463
+ ] = None,
464
+ mode: Annotated[
465
+ Optional[str],
466
+ Field(
467
+ description="TTS mode: 'custom_voice', 'voice_clone' or 'voice_design'. Leave unset to use the mode the model supports"
468
+ ),
469
+ ] = None,
470
+ instruct: Annotated[
471
+ Optional[str],
472
+ Field(
473
+ description="Voice description or style instruction, as the job will send it. Validated, not priced"
474
+ ),
475
+ ] = None,
476
+ count_text: Annotated[
477
+ Optional[int],
478
+ Field(ge=1, description="Price for this many characters instead of the given text"),
479
+ ] = None,
480
+ ) -> dict[str, Any]:
481
+ """Calculate price for text-to-audio generation.
482
+
483
+ The price follows the number of characters (text, or count_text), the
484
+ language and the speed. `mode`, `voice` and `instruct` are only validated,
485
+ so the quote fails where the job would. Left unset they are taken from the
486
+ model's card, exactly as text_to_audio does.
487
+
488
+ Returns:
489
+ dict: Contains 'success' and 'price' information
490
+ """
491
+ try:
492
+ client = get_client()
493
+ async with client:
494
+ # Mode, lang and voice all come from the card; a cold cache (first call
495
+ # after a restart) would send Kokoro's lang to a Qwen3 model.
496
+ await ensure_model_cache(model=model)
497
+ resolved_mode = mode or _resolve_tts_mode(model)
498
+
499
+ card = _tts_defaults(model, lang)
500
+ request_data = {
501
+ "text": text,
502
+ "model": model,
503
+ "voice": voice if voice is not None else card["voice"],
504
+ "lang": lang if lang is not None else (card["lang"] or "en-us"),
505
+ "speed": speed if speed is not None else (card["speed"] or 1.0),
506
+ "format": audio_format if audio_format is not None else (card["format"] or "mp3"),
507
+ "sample_rate": (
508
+ sample_rate if sample_rate is not None else (card["sample_rate"] or 24000)
509
+ ),
510
+ }
511
+ if resolved_mode:
512
+ request_data["mode"] = resolved_mode
513
+ if instruct:
514
+ request_data["instruct"] = instruct
515
+ if count_text is not None:
516
+ request_data["count_text"] = count_text
517
+
518
+ price_response = await client.calculate_price(
519
+ endpoint="audio/speech/price",
520
+ json_data=request_data,
521
+ )
522
+
523
+ return build_price_response(price_response)
524
+
525
+ except DeapiAPIError as e:
526
+ return {"success": False, "error": f"API error: {str(e)}"}
527
+ except Exception as e:
528
+ return {"success": False, "error": f"Unexpected error: {str(e)}"}
529
+
530
+
531
+ async def video_file_transcription(
532
+ video: Annotated[
533
+ str,
534
+ Field(
535
+ description="Video file as URL (preferred), data URI (data:video/mp4;base64,...), or base64 string. URLs are recommended to avoid base64 context bloat."
536
+ ),
537
+ ],
538
+ include_ts: Annotated[bool, Field(description="Include timestamps in transcription")],
539
+ model: Annotated[str, Field(description=_MODEL_HELP)] = DEFAULT_TRANSCRIPTION_MODEL,
540
+ ts_level: Annotated[Optional[TimestampLevel], Field(description=_TS_LEVEL_HELP)] = None,
541
+ diarize: Annotated[Optional[bool], Field(description=_DIARIZE_HELP)] = None,
542
+ lang: Annotated[
543
+ Optional[str],
544
+ Field(
545
+ max_length=16,
546
+ description=_LANG_HELP,
547
+ ),
548
+ ] = None,
549
+ return_result_in_response: Annotated[
550
+ bool,
551
+ Field(
552
+ description="Return transcription inline. Set to False for large files to get download URL instead"
553
+ ),
554
+ ] = True,
555
+ webhook_url: Annotated[
556
+ Optional[str],
557
+ Field(
558
+ description="HTTPS URL for deAPI to call when this job finishes. Notifies your own systems; the tool still returns the result here"
559
+ ),
560
+ ] = None,
561
+ webhook_secret: Annotated[
562
+ Optional[str],
563
+ Field(
564
+ description="32-255 char key deAPI signs the callback with (HMAC-SHA256). Needs webhook_url. A secret given in chat stays in the transcript"
565
+ ),
566
+ ] = None,
567
+ ) -> dict[str, Any]:
568
+ """Transcribe video file to text using Whisper models.
569
+
570
+ Extracts audio from video and converts it to text transcription with optional timestamps.
571
+ Accepts video files as URLs (preferred), data URIs, or base64 strings.
572
+ Automatically polls until transcription is complete.
573
+
574
+ Returns:
575
+ dict: Contains 'success', 'job_id', 'result_url' and, inline, 'result' with
576
+ the transcript text. Models marked 'output=json' in the model list
577
+ (WhisperLargeV3Ct2) also return 'segments' (start/end in seconds, text,
578
+ speaker and words when asked for) and 'language'. Other models write
579
+ timestamps into the text itself, e.g. '[0:50 - 1:49] ...'
580
+ """
581
+ try:
582
+ client = get_client()
583
+ async with client:
584
+ # v2 unified transcription endpoint takes the video as a multipart file upload
585
+ field_name, file_tuple = await prepare_video_upload_async(video, "source_file")
586
+
587
+ form_data = {
588
+ "include_ts": form_bool(include_ts),
589
+ "model": model,
590
+ "return_result_in_response": form_bool(return_result_in_response),
591
+ }
592
+ _add_transcription_params(form_data, ts_level, diarize, lang)
593
+
594
+ job_response = await client.submit_job(
595
+ endpoint="audio/transcriptions",
596
+ data=form_data,
597
+ files={field_name: file_tuple},
598
+ webhook_url=webhook_url,
599
+ webhook_secret=webhook_secret,
600
+ )
601
+ job_id = job_response.data.request_id
602
+
603
+ # Poll for completion using audio job type (same processing)
604
+ polling_manager = PollingManager(client, job_type="audio")
605
+ result = await polling_manager.poll_until_complete(job_id)
606
+
607
+ return decode_transcript(build_job_response(result, job_id))
608
+
609
+ except ValueError as e:
610
+ return {"success": False, "error": f"Invalid video format: {str(e)}"}
611
+ except DeapiAPIError as e:
612
+ return {"success": False, "error": f"API error: {str(e)}"}
613
+ except Exception as e:
614
+ return {"success": False, "error": f"Unexpected error: {str(e)}"}
615
+
616
+
617
+ async def video_file_transcription_price(
618
+ include_ts: Annotated[bool, Field(description="Include timestamps")],
619
+ duration_seconds: Annotated[
620
+ float, Field(gt=0, description="Length of the video in seconds, which the price follows")
621
+ ],
622
+ model: Annotated[str, Field(description=_MODEL_HELP)] = DEFAULT_TRANSCRIPTION_MODEL,
623
+ ts_level: Annotated[Optional[TimestampLevel], Field(description=_TS_LEVEL_HELP)] = None,
624
+ diarize: Annotated[Optional[bool], Field(description=_DIARIZE_HELP)] = None,
625
+ lang: Annotated[Optional[str], Field(max_length=16, description=_LANG_HELP)] = None,
626
+ ) -> dict[str, Any]:
627
+ """Calculate price for video file transcription.
628
+
629
+ Quotes an uploaded video file by its length. For a URL use
630
+ video_url_transcription_price.
631
+
632
+ Returns:
633
+ dict: Contains 'success' and 'price' information
634
+ """
635
+ try:
636
+ client = get_client()
637
+ async with client:
638
+ form_data = {
639
+ "include_ts": form_bool(include_ts),
640
+ "model": model,
641
+ }
642
+ _add_transcription_params(form_data, ts_level, diarize, lang)
643
+
644
+ form_data["duration_seconds"] = str(duration_seconds)
645
+
646
+ price_response = await client.calculate_price(
647
+ endpoint="audio/transcriptions/price",
648
+ data=form_data,
649
+ )
650
+
651
+ return build_price_response(price_response)
652
+
653
+ except DeapiAPIError as e:
654
+ return {"success": False, "error": f"API error: {str(e)}"}
655
+ except Exception as e:
656
+ return {"success": False, "error": f"Unexpected error: {str(e)}"}
657
+
658
+
659
+ async def video_url_transcription(
660
+ video_url: Annotated[
661
+ str,
662
+ Field(
663
+ description="URL of video to transcribe. Supports YouTube (e.g., 'https://www.youtube.com/watch?v=...'), Twitter/X (e.g., 'https://twitter.com/user/status/...' or 'https://x.com/user/status/...'), Twitch (e.g., 'https://www.twitch.tv/videos/...'), Kick (e.g., 'https://kick.com/video/...') and TikTok. A Twitter Spaces link is routed to audio transcription automatically"
664
+ ),
665
+ ],
666
+ include_ts: Annotated[bool, Field(description="Include timestamps in transcription")],
667
+ model: Annotated[str, Field(description=_MODEL_HELP)] = DEFAULT_TRANSCRIPTION_MODEL,
668
+ ts_level: Annotated[Optional[TimestampLevel], Field(description=_TS_LEVEL_HELP)] = None,
669
+ diarize: Annotated[Optional[bool], Field(description=_DIARIZE_HELP)] = None,
670
+ lang: Annotated[
671
+ Optional[str],
672
+ Field(
673
+ max_length=16,
674
+ description=_LANG_HELP,
675
+ ),
676
+ ] = None,
677
+ include_metadata: Annotated[
678
+ Optional[bool],
679
+ Field(
680
+ description="Include source metadata in the result. Carries a flat surcharge on models that price it"
681
+ ),
682
+ ] = None,
683
+ return_result_in_response: Annotated[
684
+ bool,
685
+ Field(
686
+ description="Return transcription inline. Set to False for large files to get download URL instead"
687
+ ),
688
+ ] = True,
689
+ webhook_url: Annotated[
690
+ Optional[str],
691
+ Field(
692
+ description="HTTPS URL for deAPI to call when this job finishes. Notifies your own systems; the tool still returns the result here"
693
+ ),
694
+ ] = None,
695
+ webhook_secret: Annotated[
696
+ Optional[str],
697
+ Field(
698
+ description="32-255 char key deAPI signs the callback with (HMAC-SHA256). Needs webhook_url. A secret given in chat stays in the transcript"
699
+ ),
700
+ ] = None,
701
+ ) -> dict[str, Any]:
702
+ """Transcribe video from URL to text using Whisper models.
703
+
704
+ Extracts audio from video URL and converts it to text transcription with optional timestamps.
705
+ Supports YouTube, Twitter/X, Twitch, Kick and TikTok videos.
706
+ Automatically polls until transcription is complete.
707
+
708
+ Returns:
709
+ dict: Contains 'success', 'job_id', 'result_url' and, inline, 'result' with
710
+ the transcript text. Models marked 'output=json' in the model list
711
+ (WhisperLargeV3Ct2) also return 'segments' (start/end in seconds, text,
712
+ speaker and words when asked for) and 'language'. Other models write
713
+ timestamps into the text itself, e.g. '[0:50 - 1:49] ...'
714
+ """
715
+ try:
716
+ client = get_client()
717
+ async with client:
718
+ form_data = {
719
+ "source_url": video_url,
720
+ "include_ts": form_bool(include_ts),
721
+ "model": model,
722
+ "return_result_in_response": form_bool(return_result_in_response),
723
+ }
724
+ _add_transcription_params(form_data, ts_level, diarize, lang, include_metadata)
725
+
726
+ job_response = await client.submit_job(
727
+ endpoint="audio/transcriptions",
728
+ data=form_data,
729
+ webhook_url=webhook_url,
730
+ webhook_secret=webhook_secret,
731
+ )
732
+ job_id = job_response.data.request_id
733
+
734
+ # Poll for completion using audio job type (same processing)
735
+ polling_manager = PollingManager(client, job_type="audio")
736
+ result = await polling_manager.poll_until_complete(job_id)
737
+
738
+ return decode_transcript(build_job_response(result, job_id))
739
+
740
+ except DeapiAPIError as e:
741
+ return {"success": False, "error": f"API error: {str(e)}"}
742
+ except Exception as e:
743
+ return {"success": False, "error": f"Unexpected error: {str(e)}"}
744
+
745
+
746
+ async def video_url_transcription_price(
747
+ include_ts: Annotated[bool, Field(description="Include timestamps")],
748
+ video_url: Annotated[
749
+ Optional[str],
750
+ Field(
751
+ description="URL of video. Provide this or duration_seconds, not both. TikTok URLs cannot be quoted: use duration_seconds with platform='tiktok'"
752
+ ),
753
+ ] = None,
754
+ duration_seconds: Annotated[
755
+ Optional[float],
756
+ Field(
757
+ gt=0,
758
+ description="Video duration in seconds, to quote without supplying a URL. Mutually exclusive with video_url",
759
+ ),
760
+ ] = None,
761
+ model: Annotated[str, Field(description=_MODEL_HELP)] = DEFAULT_TRANSCRIPTION_MODEL,
762
+ ts_level: Annotated[Optional[TimestampLevel], Field(description=_TS_LEVEL_HELP)] = None,
763
+ diarize: Annotated[Optional[bool], Field(description=_DIARIZE_HELP)] = None,
764
+ lang: Annotated[Optional[str], Field(max_length=16, description=_LANG_HELP)] = None,
765
+ include_metadata: Annotated[
766
+ Optional[bool],
767
+ Field(
768
+ description="Include source metadata. Carries a flat surcharge on models that price it"
769
+ ),
770
+ ] = None,
771
+ platform: Annotated[
772
+ Optional[str],
773
+ Field(
774
+ description="Source platform: 'youtube', 'twitter', 'twitch', 'kick' or 'tiktok'. Changes the price substantially — tiktok can be ~9x youtube. Only valid together with duration_seconds"
775
+ ),
776
+ ] = None,
777
+ ) -> dict[str, Any]:
778
+ """Calculate price for video URL transcription.
779
+
780
+ Quote either from a URL or from a duration. The API accepts exactly one:
781
+ given a URL it derives duration and platform from the source itself, so
782
+ `duration_seconds` and `platform` are rejected alongside it.
783
+
784
+ Returns:
785
+ dict: Contains 'success' and 'price' information
786
+ """
787
+ try:
788
+ client = get_client()
789
+ async with client:
790
+ if video_url and duration_seconds is not None:
791
+ return input_error_response(
792
+ "Pass either 'video_url' or 'duration_seconds', not both — the API rejects requests carrying both."
793
+ )
794
+ if not video_url and duration_seconds is None:
795
+ return input_error_response(
796
+ "Provide 'video_url' or 'duration_seconds' to calculate a price."
797
+ )
798
+ if platform and video_url:
799
+ return input_error_response(
800
+ "'platform' is only accepted with 'duration_seconds'; with a URL the API derives the platform from the source."
801
+ )
802
+
803
+ form_data = {
804
+ "include_ts": form_bool(include_ts),
805
+ "model": model,
806
+ }
807
+ _add_transcription_params(form_data, ts_level, diarize, lang, include_metadata)
808
+
809
+ if video_url:
810
+ form_data["source_url"] = video_url
811
+ if duration_seconds is not None:
812
+ form_data["duration_seconds"] = str(duration_seconds)
813
+ if platform:
814
+ form_data["platform"] = platform
815
+
816
+ price_response = await client.calculate_price(
817
+ endpoint="audio/transcriptions/price",
818
+ data=form_data,
819
+ )
820
+
821
+ return build_price_response(price_response)
822
+
823
+ except DeapiAPIError as e:
824
+ return {"success": False, "error": f"API error: {str(e)}"}
825
+ except Exception as e:
826
+ return {"success": False, "error": f"Unexpected error: {str(e)}"}
827
+
828
+
829
+ async def text_to_music(
830
+ caption: Annotated[
831
+ str,
832
+ Field(
833
+ description="Text description of the music to generate. Length bounds per model ('caption' in the model list)"
834
+ ),
835
+ ],
836
+ model: Annotated[
837
+ str,
838
+ Field(description="Music generation model name (must support txt2music inference type)"),
839
+ ],
840
+ lyrics: Annotated[
841
+ str, Field(description="Song lyrics (max 10000 chars). Use '[Instrumental]' for no vocals")
842
+ ],
843
+ duration: Annotated[
844
+ float,
845
+ Field(
846
+ ge=10,
847
+ le=600,
848
+ description="Audio duration in seconds. Bounds per model ('duration' in the model list)",
849
+ ),
850
+ ],
851
+ inference_steps: Annotated[
852
+ Optional[int],
853
+ Field(
854
+ ge=1,
855
+ le=100,
856
+ description="Number of inference steps. Leave unset when the model fixes it (see 'steps' in the model list)",
857
+ ),
858
+ ] = None,
859
+ guidance_scale: Annotated[
860
+ Optional[float],
861
+ Field(
862
+ ge=0.0,
863
+ le=20.0,
864
+ description="Guidance scale. Leave unset when the model fixes it (see 'guidance' in the model list)",
865
+ ),
866
+ ] = None,
867
+ seed: Annotated[int, Field(description="Random seed (-1 for random)")] = -1,
868
+ audio_format: Annotated[
869
+ Optional[str],
870
+ Field(
871
+ description="Output format, e.g. 'mp3' or 'flac'. Per-model — see info.limits.output_formats; leave unset for the model's own default"
872
+ ),
873
+ ] = None,
874
+ bpm: Annotated[
875
+ Optional[int],
876
+ Field(
877
+ ge=30,
878
+ le=300,
879
+ description="Beats per minute (optional). Bounds per model ('bpm' in the model list)",
880
+ ),
881
+ ] = None,
882
+ keyscale: Annotated[
883
+ Optional[str], Field(description="Musical key/scale, e.g. 'C major', 'F# minor' (optional)")
884
+ ] = None,
885
+ timesignature: Annotated[
886
+ Optional[int], Field(description="Time signature: 2, 3, 4, or 6 (optional)")
887
+ ] = None,
888
+ vocal_language: Annotated[
889
+ Optional[str], Field(description="Vocal language code, e.g. 'en', 'es' (optional)")
890
+ ] = None,
891
+ reference_audio: Annotated[
892
+ Optional[str],
893
+ Field(
894
+ description="Reference audio for style transfer (URL, data URI, or base64). Its length must be within the model's window ('ref_audio' in the model list, e.g. 5-60s)"
895
+ ),
896
+ ] = None,
897
+ webhook_url: Annotated[
898
+ Optional[str],
899
+ Field(
900
+ description="HTTPS URL for deAPI to call when this job finishes. Notifies your own systems; the tool still returns the result here"
901
+ ),
902
+ ] = None,
903
+ webhook_secret: Annotated[
904
+ Optional[str],
905
+ Field(
906
+ description="32-255 char key deAPI signs the callback with (HMAC-SHA256). Needs webhook_url. A secret given in chat stays in the transcript"
907
+ ),
908
+ ] = None,
909
+ ) -> dict[str, Any]:
910
+ """Generate music from text description and lyrics.
911
+
912
+ Creates music tracks from text prompts with customizable parameters including
913
+ tempo, key, time signature, and optional style reference audio.
914
+
915
+ IMPORTANT: Check model specifications using get_available_models() before calling.
916
+ Pay attention to model limits for duration, inference_steps, guidance_scale, and bpm.
917
+
918
+ Returns:
919
+ dict: Contains 'success', 'result_url' with audio URL, 'job_id'
920
+ """
921
+ try:
922
+ client = get_client()
923
+ async with client:
924
+ # The API requires `format` and accepts only what the card lists
925
+ # under info.limits.output_formats; every current music model is
926
+ # mp3-only, so a fixed default would fail on all of them.
927
+ await ensure_model_cache(model=model)
928
+ # Both are required by the API; every current model pins them
929
+ # (steps 8, guidance 1) and publishes only the range, not a default.
930
+ if inference_steps is None:
931
+ inference_steps = _pinned_limit(model, "steps")
932
+ if guidance_scale is None:
933
+ guidance_scale = _pinned_limit(model, "guidance")
934
+ if inference_steps is None or guidance_scale is None:
935
+ return input_error_response(
936
+ "inference_steps and guidance_scale are required for this model: it does not fix them (see its limits in the model list)."
937
+ )
938
+ form_data = {
939
+ "caption": caption,
940
+ "model": model,
941
+ "lyrics": lyrics,
942
+ "duration": str(duration),
943
+ "inference_steps": str(inference_steps),
944
+ "guidance_scale": str(guidance_scale),
945
+ "seed": str(seed),
946
+ "format": audio_format or _music_format_default(model),
947
+ }
948
+
949
+ if bpm is not None:
950
+ form_data["bpm"] = str(bpm)
951
+ if keyscale is not None:
952
+ form_data["keyscale"] = keyscale
953
+ if timesignature is not None:
954
+ form_data["timesignature"] = str(timesignature)
955
+ if vocal_language is not None:
956
+ form_data["vocal_language"] = vocal_language
957
+
958
+ files = {}
959
+ if reference_audio:
960
+ field_name, file_tuple = await prepare_audio_upload_async(
961
+ reference_audio, "reference_audio"
962
+ )
963
+ files[field_name] = file_tuple
964
+
965
+ job_response = await client.submit_job(
966
+ endpoint="audio/music",
967
+ data=form_data,
968
+ files=files if files else None,
969
+ webhook_url=webhook_url,
970
+ webhook_secret=webhook_secret,
971
+ )
972
+ job_id = job_response.data.request_id
973
+
974
+ polling_manager = PollingManager(client, job_type="audio")
975
+ result = await polling_manager.poll_until_complete(job_id)
976
+
977
+ return build_job_response(result, job_id)
978
+
979
+ except ValueError as e:
980
+ return {"success": False, "error": f"Invalid audio format: {str(e)}"}
981
+ except DeapiAPIError as e:
982
+ return {"success": False, "error": f"API error: {str(e)}"}
983
+ except Exception as e:
984
+ return {"success": False, "error": f"Unexpected error: {str(e)}"}
985
+
986
+
987
+ async def text_to_music_price(
988
+ model: Annotated[str, Field(description="Music generation model name")],
989
+ duration: Annotated[
990
+ float,
991
+ Field(ge=10, le=600, description="Audio duration in seconds, as the job will send it"),
992
+ ],
993
+ inference_steps: Annotated[
994
+ Optional[int],
995
+ Field(ge=1, le=100, description="Inference steps. Leave unset when the model fixes it"),
996
+ ] = None,
997
+ ) -> dict[str, Any]:
998
+ """Calculate price for text-to-music generation.
999
+
1000
+ Returns:
1001
+ dict: Contains 'success' and 'price' information
1002
+ """
1003
+ try:
1004
+ client = get_client()
1005
+ async with client:
1006
+ await ensure_model_cache(model=model)
1007
+ if inference_steps is None:
1008
+ inference_steps = _pinned_limit(model, "steps")
1009
+ if inference_steps is None:
1010
+ return input_error_response(
1011
+ "inference_steps is required for this model: it does not fix it (see its limits in the model list)."
1012
+ )
1013
+ form_data = {
1014
+ "model": model,
1015
+ "duration": str(duration),
1016
+ "inference_steps": str(inference_steps),
1017
+ }
1018
+
1019
+ price_response = await client.calculate_price(
1020
+ endpoint="audio/music/price",
1021
+ data=form_data,
1022
+ )
1023
+
1024
+ return build_price_response(price_response)
1025
+
1026
+ except DeapiAPIError as e:
1027
+ return {"success": False, "error": f"API error: {str(e)}"}
1028
+ except Exception as e:
1029
+ return {"success": False, "error": f"Unexpected error: {str(e)}"}
1030
+
1031
+
1032
+ async def audio_url_transcription(
1033
+ audio_url: Annotated[
1034
+ str,
1035
+ Field(
1036
+ description="URL of Twitter Spaces audio to transcribe (e.g., 'https://twitter.com/i/spaces/1nAKEERkeLbKL')"
1037
+ ),
1038
+ ],
1039
+ include_ts: Annotated[bool, Field(description="Include timestamps in transcription")],
1040
+ model: Annotated[str, Field(description=_MODEL_HELP)] = DEFAULT_TRANSCRIPTION_MODEL,
1041
+ ts_level: Annotated[Optional[TimestampLevel], Field(description=_TS_LEVEL_HELP)] = None,
1042
+ diarize: Annotated[Optional[bool], Field(description=_DIARIZE_HELP)] = None,
1043
+ lang: Annotated[
1044
+ Optional[str],
1045
+ Field(
1046
+ max_length=16,
1047
+ description=_LANG_HELP,
1048
+ ),
1049
+ ] = None,
1050
+ include_metadata: Annotated[
1051
+ Optional[bool],
1052
+ Field(
1053
+ description="Include source metadata in the result. Carries a flat surcharge on models that price it"
1054
+ ),
1055
+ ] = None,
1056
+ return_result_in_response: Annotated[
1057
+ bool,
1058
+ Field(
1059
+ description="Return transcription inline. Set to False for large files to get download URL instead"
1060
+ ),
1061
+ ] = True,
1062
+ webhook_url: Annotated[
1063
+ Optional[str],
1064
+ Field(
1065
+ description="HTTPS URL for deAPI to call when this job finishes. Notifies your own systems; the tool still returns the result here"
1066
+ ),
1067
+ ] = None,
1068
+ webhook_secret: Annotated[
1069
+ Optional[str],
1070
+ Field(
1071
+ description="32-255 char key deAPI signs the callback with (HMAC-SHA256). Needs webhook_url. A secret given in chat stays in the transcript"
1072
+ ),
1073
+ ] = None,
1074
+ ) -> dict[str, Any]:
1075
+ """Transcribe audio from Twitter Spaces URL to text using Whisper models.
1076
+
1077
+ Extracts and transcribes audio from Twitter Spaces URLs.
1078
+ NOTE: This endpoint only works with Twitter Spaces URLs. For video content,
1079
+ use video_url_transcription instead.
1080
+
1081
+ Returns:
1082
+ dict: Contains 'success', 'job_id', 'result_url' and, inline, 'result' with
1083
+ the transcript text. Models marked 'output=json' in the model list
1084
+ (WhisperLargeV3Ct2) also return 'segments' (start/end in seconds, text,
1085
+ speaker and words when asked for) and 'language'. Other models write
1086
+ timestamps into the text itself, e.g. '[0:50 - 1:49] ...'
1087
+ """
1088
+ try:
1089
+ client = get_client()
1090
+ async with client:
1091
+ form_data = {
1092
+ "source_url": audio_url,
1093
+ "include_ts": form_bool(include_ts),
1094
+ "model": model,
1095
+ "return_result_in_response": form_bool(return_result_in_response),
1096
+ }
1097
+ _add_transcription_params(form_data, ts_level, diarize, lang, include_metadata)
1098
+
1099
+ job_response = await client.submit_job(
1100
+ endpoint="audio/transcriptions",
1101
+ data=form_data,
1102
+ webhook_url=webhook_url,
1103
+ webhook_secret=webhook_secret,
1104
+ )
1105
+ job_id = job_response.data.request_id
1106
+
1107
+ # Poll for completion using audio job type
1108
+ polling_manager = PollingManager(client, job_type="audio")
1109
+ result = await polling_manager.poll_until_complete(job_id)
1110
+
1111
+ return decode_transcript(build_job_response(result, job_id))
1112
+
1113
+ except DeapiAPIError as e:
1114
+ return {"success": False, "error": f"API error: {str(e)}"}
1115
+ except Exception as e:
1116
+ return {"success": False, "error": f"Unexpected error: {str(e)}"}
1117
+
1118
+
1119
+ async def audio_url_transcription_price(
1120
+ include_ts: Annotated[bool, Field(description="Include timestamps")],
1121
+ model: Annotated[str, Field(description=_MODEL_HELP)] = DEFAULT_TRANSCRIPTION_MODEL,
1122
+ audio_url: Annotated[
1123
+ Optional[str],
1124
+ Field(description="Twitter Spaces URL (required if duration_seconds not provided)"),
1125
+ ] = None,
1126
+ duration_seconds: Annotated[
1127
+ Optional[float],
1128
+ Field(gt=0, description="Audio duration in seconds (required if audio_url not provided)"),
1129
+ ] = None,
1130
+ ts_level: Annotated[Optional[TimestampLevel], Field(description=_TS_LEVEL_HELP)] = None,
1131
+ diarize: Annotated[Optional[bool], Field(description=_DIARIZE_HELP)] = None,
1132
+ lang: Annotated[Optional[str], Field(max_length=16, description=_LANG_HELP)] = None,
1133
+ include_metadata: Annotated[
1134
+ Optional[bool],
1135
+ Field(
1136
+ description="Include source metadata. Carries a flat surcharge on models that price it"
1137
+ ),
1138
+ ] = None,
1139
+ platform: Annotated[
1140
+ Optional[str],
1141
+ Field(
1142
+ description="Pass 'twitter' when quoting a Twitter Spaces recording by duration_seconds, so it is priced as a platform source. Only valid together with duration_seconds"
1143
+ ),
1144
+ ] = None,
1145
+ ) -> dict[str, Any]:
1146
+ """Calculate price for Twitter Spaces audio transcription.
1147
+
1148
+ Provide either audio_url or duration_seconds for price calculation.
1149
+ `platform` is only accepted alongside `duration_seconds`; with a URL the
1150
+ API derives the platform from the source.
1151
+
1152
+ Returns:
1153
+ dict: Contains 'success' and 'price' information
1154
+ """
1155
+ try:
1156
+ client = get_client()
1157
+ async with client:
1158
+ if audio_url and duration_seconds is not None:
1159
+ return input_error_response(
1160
+ "Pass either 'audio_url' or 'duration_seconds', not both — the API rejects requests carrying both."
1161
+ )
1162
+ if not audio_url and duration_seconds is None:
1163
+ return input_error_response(
1164
+ "Provide 'audio_url' or 'duration_seconds' to calculate a price."
1165
+ )
1166
+ if platform and audio_url:
1167
+ return input_error_response(
1168
+ "'platform' is only accepted with 'duration_seconds'; with a URL the API derives the platform from the source."
1169
+ )
1170
+
1171
+ form_data = {
1172
+ "include_ts": form_bool(include_ts),
1173
+ "model": model,
1174
+ }
1175
+ _add_transcription_params(form_data, ts_level, diarize, lang, include_metadata)
1176
+
1177
+ if platform:
1178
+ form_data["platform"] = platform
1179
+
1180
+ if audio_url:
1181
+ form_data["source_url"] = audio_url
1182
+ if duration_seconds is not None:
1183
+ form_data["duration_seconds"] = str(duration_seconds)
1184
+
1185
+ price_response = await client.calculate_price(
1186
+ endpoint="audio/transcriptions/price",
1187
+ data=form_data,
1188
+ )
1189
+
1190
+ return build_price_response(price_response)
1191
+
1192
+ except DeapiAPIError as e:
1193
+ return {"success": False, "error": f"API error: {str(e)}"}
1194
+ except Exception as e:
1195
+ return {"success": False, "error": f"Unexpected error: {str(e)}"}