Repository navigation
Expand file tree
/
Copy pathapp.js
More file actions
237 lines (216 loc) · 6.3 KB
/
Copy pathapp.js
File metadata and controls
237 lines (216 loc) · 6.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
(function (root) {
function joinUrl(baseUrl, endpoint) {
const cleanBase = String(baseUrl || "").trim().replace(/\/+$/, "");
const cleanEndpoint = String(endpoint || "").trim().replace(/^\/+/, "");
return cleanEndpoint ? `${cleanBase}/${cleanEndpoint}` : cleanBase;
}
function buildImageGenerationRequest({
baseUrl,
endpoint,
apiKey,
model,
prompt,
size,
responseFormat,
}) {
const body = {
model: String(model || "").trim(),
prompt: String(prompt || "").trim(),
size: String(size || "").trim() || "1024x1024",
n: 1,
response_format: String(responseFormat || "url").trim(),
};
return {
url: joinUrl(baseUrl, endpoint || "/images/generations"),
options: {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${String(apiKey || "").trim()}`,
},
body: JSON.stringify(body),
},
};
}
async function buildImageExperimentRequest({
baseUrl,
endpoint,
referenceEndpoint,
apiKey,
model,
prompt,
size,
responseFormat,
experimentMode,
imageFiles,
}) {
const files = Array.from(imageFiles || []);
const resolvedEndpoint =
files.length > 0
? referenceEndpoint || "/chat/completions"
: endpoint || "/images/generations";
const url = joinUrl(baseUrl, resolvedEndpoint);
const mode = files.length > 0 ? "chat_messages" : "images_generations";
if (mode === "chat_messages") {
const imageParts = await Promise.all(
files.map(async (file) => ({
type: "image_url",
image_url: {
url: `data:${file.type};base64,${await fileToBase64(file)}`,
},
})),
);
const body = {
model: String(model || "").trim(),
group: "vip_2_image",
messages: [
{
role: "user",
content:
imageParts.length > 0
? [
{ type: "text", text: String(prompt || "").trim() },
...imageParts,
]
: String(prompt || "").trim(),
},
],
stream: true,
temperature: 0.7,
top_p: 1,
frequency_penalty: 0,
presence_penalty: 0,
};
return {
url,
options: {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${String(apiKey || "").trim()}`,
},
body: JSON.stringify(body),
},
displayBody: maskLongImageUrls(body),
};
}
const body = {
model: String(model || "").trim(),
prompt: String(prompt || "").trim(),
size: String(size || "1024x1024").trim(),
n: 1,
response_format: String(responseFormat || "url").trim(),
};
return {
url,
options: {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${String(apiKey || "").trim()}`,
},
body: JSON.stringify(body),
},
displayBody: body,
};
}
function fileToBase64(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => {
const result = String(reader.result || "");
resolve(result.includes(",") ? result.split(",")[1] : result);
};
reader.onerror = () => reject(reader.error);
reader.readAsDataURL(file);
});
}
function maskLongImageUrls(value) {
return JSON.parse(
JSON.stringify(value, (key, currentValue) => {
if (
key === "url" &&
typeof currentValue === "string" &&
currentValue.startsWith("data:image/")
) {
return `${currentValue.slice(0, 80)}... (length=${currentValue.length})`;
}
return currentValue;
}),
);
}
function extractImageResults(responseJson) {
const data = Array.isArray(responseJson?.data) ? responseJson.data : [];
return data.flatMap((item) => {
if (item?.url) {
return [{ type: "url", value: item.url }];
}
if (item?.b64_json) {
return [{ type: "base64", value: item.b64_json }];
}
return [];
});
}
function maskApiKey(apiKey) {
const value = String(apiKey || "").trim();
if (value.length <= 8) return value ? "****" : "";
return `${value.slice(0, 4)}...${value.slice(-4)}`;
}
function buildCurlCommand(request, apiKey) {
const masked = maskApiKey(apiKey);
return [
`curl -X POST "${request.url}"`,
` -H "Content-Type: application/json"`,
` -H "Authorization: Bearer ${masked}"`,
` -d '${request.options.body}'`,
].join(" \\\n");
}
function toDisplayRequest(request, apiKey) {
return {
url: request.url,
options: {
...request.options,
headers: {
...request.options.headers,
Authorization: `Bearer ${maskApiKey(apiKey)}`,
},
body: request.displayBody || JSON.parse(request.options.body),
},
};
}
async function sendImageGenerationRequest(formData) {
const request = formData.experimentMode
? await buildImageExperimentRequest(formData)
: buildImageGenerationRequest(formData);
const response = await fetch(request.url, request.options);
const contentType = response.headers.get("content-type") || "";
const rawText = await response.text();
const responseBody = contentType.includes("application/json")
? JSON.parse(rawText)
: rawText;
return {
ok: response.ok,
status: response.status,
statusText: response.statusText,
responseBody,
imageResults:
typeof responseBody === "object" ? extractImageResults(responseBody) : [],
displayRequest: toDisplayRequest(request, formData.apiKey),
curlCommand: buildCurlCommand(request, formData.apiKey),
};
}
const api = {
joinUrl,
buildImageGenerationRequest,
buildImageExperimentRequest,
extractImageResults,
maskApiKey,
buildCurlCommand,
toDisplayRequest,
sendImageGenerationRequest,
};
if (typeof module !== "undefined" && module.exports) {
module.exports = api;
}
root.ImageApiTester = api;
})(typeof window !== "undefined" ? window : globalThis);