1
Create translation
One script reply has been approved by the moderators Verified

Translates audio into English.

Created by adam186 361 days ago Viewed 4328 times
0
Submitted by hugo697 Typescript (fetch-only)
Verified 141 days ago
1
type Openai = {
2
  api_key: string;
3
  organization_id: string;
4
};
5
type Base64 = string;
6
/**
7
 * Create translation
8
 * Translates audio into English.
9
 */
10
export async function main(
11
  auth: Openai,
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
    model: string | "whisper-1";
29
    prompt?: string;
30
    response_format?: string;
31
    temperature?: number;
32
  }
33
) {
34
  const url = new URL(`https://api.openai.com/v1/audio/translations`);
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
      "OpenAI-Organization": auth.organization_id,
61
      Authorization: "Bearer " + auth.api_key,
62
    },
63
    body: formData,
64
  });
65
  if (!response.ok) {
66
    const text = await response.text();
67
    throw new Error(`${response.status} ${text}`);
68
  }
69
  return await response.json();
70
}
71

Other submissions