Create translation

Translates audio into English.

Script openai Verified

by adam186 · 4/25/2023

The script

Submitted by hugo697 Typescript (fetch-only)
Verified 367 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
  • Submitted by adam186 Deno
    Created 1000 days ago
    1
    import { removeObjectEmptyFields } from "https://deno.land/x/[email protected]/mod.ts";
    2
    import {
    3
      Configuration,
    4
      CreateCompletionRequest,
    5
      OpenAIApi,
    6
    } from "npm:[email protected]";
    7
    
    
    8
    /**
    9
     * You can read about the parameters at
    10
     * https://platform.openai.com/docs/api-reference/completions/create
    11
     *
    12
     * @returns An object with the **lowercase** values of the `translate_to` array as keys.
    13
     *
    14
     * *For example:*
    15
     * ```
    16
     *  { french: "J'aime les pommes", german: "Ich liebe Äpfel" }
    17
     * ```
    18
     */
    19
    type Openai = {
    20
      api_key: string;
    21
      organization_id: string;
    22
    };
    23
    export async function main(
    24
      auth: Openai,
    25
      text: string,
    26
      translate_to: string[] = ["french", "german"],
    27
      model: string = "text-davinci-003",
    28
      max_tokens: number = 100,
    29
    ) {
    30
      const configuration = new Configuration({
    31
        apiKey: auth.api_key,
    32
        organization: auth.organization_id,
    33
      });
    34
      const openai = new OpenAIApi(configuration);
    35
    
    
    36
      const prompt = `Translate the text below into the languages found in this array:
    37
    [${translate_to.map((l) => l.trim().toLowerCase()).join(", ")}]
    38
    Apply the following rules:
    39
      - return ONLY a valid JSON object
    40
      - the object keys are strictly the languages in the array above
    41
      - the values are the corresponding translations
    42
      - do NOT try to complete the original text
    43
    
    
    44
    ${text}`;
    45
      console.log(prompt);
    46
      const request = removeObjectEmptyFields({
    47
        model,
    48
        prompt,
    49
        max_tokens,
    50
        temperature: 0.3,
    51
        top_p: 1.0,
    52
        frequency_penalty: 0.0,
    53
        presence_penalty: 0.0,
    54
      }) as CreateCompletionRequest;
    55
      const { data } = await openai.createCompletion(request);
    56
      console.log(data?.choices[0]?.text);
    57
    
    
    58
      return JSON.parse(data?.choices[0]?.text.replaceAll('"', '"') ?? "");
    59
    }
    60