0
Create image edit
One script reply has been approved by the moderators Verified

Creates an edited or extended image given an original image and a prompt.

Created by hugo697 156 days ago Viewed 5543 times
0
Submitted by hugo697 Typescript (fetch-only)
Verified 156 days ago
1
type Openai = {
2
  api_key: string;
3
  organization_id: string;
4
};
5
type Base64 = string;
6
/**
7
 * Create image edit
8
 * Creates an edited or extended image given an original image and a prompt.
9
 */
10
export async function main(
11
  auth: Openai,
12
  body: {
13
    image: {
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
    prompt: string;
29
    mask?: {
30
      base64: Base64;
31
      type:
32
        | "image/png"
33
        | "image/jpeg"
34
        | "image/gif"
35
        | "application/pdf"
36
        | "appication/json"
37
        | "text/csv"
38
        | "text/plain"
39
        | "audio/mpeg"
40
        | "audio/wav"
41
        | "video/mp4";
42
      name: string;
43
    };
44
    model?: string | "dall-e-2";
45
    n?: number;
46
    size?: "256x256" | "512x512" | "1024x1024";
47
    response_format?: "url" | "b64_json";
48
    user?: string;
49
    [k: string]: unknown;
50
  }
51
) {
52
  const url = new URL(`https://api.openai.com/v1/images/edits`);
53

54
  const formData = new FormData();
55
  for (const [k, v] of Object.entries(body)) {
56
    if (v !== undefined && v !== "") {
57
      if (["image", "mask"].includes(k)) {
58
        const { base64, type, name } = v as {
59
          base64: Base64;
60
          type: string;
61
          name: string;
62
        };
63
        formData.append(
64
          k,
65
          new Blob([Uint8Array.from(atob(base64), (m) => m.codePointAt(0)!)], {
66
            type,
67
          }),
68
          name
69
        );
70
      } else {
71
        formData.append(k, String(v));
72
      }
73
    }
74
  }
75
  const response = await fetch(url, {
76
    method: "POST",
77
    headers: {
78
      "OpenAI-Organization": auth.organization_id,
79
      Authorization: "Bearer " + auth.api_key,
80
    },
81
    body: formData,
82
  });
83
  if (!response.ok) {
84
    const text = await response.text();
85
    throw new Error(`${response.status} ${text}`);
86
  }
87
  return await response.json();
88
}
89