1 | |
2 | type Telnyx = { |
3 | apiKey: string |
4 | } |
5 | type Base64 = string |
6 | |
7 | * Transcribe speech to text |
8 | * Transcribe speech to text. This endpoint is consistent with the [OpenAI Transcription API](https://platform.openai.com/docs/api-reference/audio/createTranscription) and may be used with the OpenAI JS or Python SDK. |
9 | */ |
10 | export async function main( |
11 | auth: Telnyx, |
12 | body: { |
13 | file?: { |
14 | base64: Base64 |
15 | type: |
16 | | 'image/png' |
17 | | 'image/jpeg' |
18 | | 'image/gif' |
19 | | 'application/pdf' |
20 | | 'appication/json' |
21 | | 'text/csv' |
22 | | 'text/plain' |
23 | | 'audio/mpeg' |
24 | | 'audio/wav' |
25 | | 'video/mp4' |
26 | name: string |
27 | } |
28 | file_url?: string |
29 | model: 'distil-whisper/distil-large-v2' | 'openai/whisper-large-v3-turbo' |
30 | response_format?: 'json' | 'verbose_json' |
31 | 'timestamp_granularities[]'?: 'segment' |
32 | } |
33 | ) { |
34 | const url = new URL(`https://api.telnyx.com/v2/ai/audio/transcriptions`) |
35 |
|
36 | const formData = new FormData() |
37 | for (const [k, v] of Object.entries(body)) { |
38 | if (v !== undefined && v !== '') { |
39 | if (['file'].includes(k)) { |
40 | const { base64, type, name } = v as { |
41 | base64: Base64 |
42 | type: string |
43 | name: string |
44 | } |
45 | formData.append( |
46 | k, |
47 | new Blob([Uint8Array.from(atob(base64), (m) => m.codePointAt(0)!)], { |
48 | type |
49 | }), |
50 | name |
51 | ) |
52 | } else { |
53 | formData.append(k, String(v)) |
54 | } |
55 | } |
56 | } |
57 | const response = await fetch(url, { |
58 | method: 'POST', |
59 | headers: { |
60 | Authorization: 'Bearer ' + auth.apiKey |
61 | }, |
62 | body: formData |
63 | }) |
64 | if (!response.ok) { |
65 | const text = await response.text() |
66 | throw new Error(`${response.status} ${text}`) |
67 | } |
68 | return await response.json() |
69 | } |
70 |
|