-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.ts
202 lines (173 loc) · 4.65 KB
/
main.ts
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
import * as fs from 'node:fs';
import * as path from 'node:path';
import { config } from './config';
interface RequestBody {
prompt: string;
negative_prompt?: string;
aspect_ratio?: string;
seed?: number;
output_format?: string;
image?: string; // base64
}
interface Completion {
Content: string | ErrorResponse | null;
Error?: string;
TokenUsage?: number;
}
interface ConnectorResponse {
Completions: Completion[];
ModelType: string;
}
const mapToResponse = (
outputs: (string | ErrorResponse)[],
model: string,
): ConnectorResponse => {
return {
Completions: outputs.map((output) => {
if (typeof output === 'string') {
return {
Content: output,
TokenUsage: undefined,
};
}
return {
Content: null,
TokenUsage: undefined,
Error: output.error,
};
}),
ModelType: model,
};
};
interface SuccessResponse {
image: string;
finish_reason: string;
seed?: number;
}
interface ErrorConnectorResponse {
id: string;
name: string;
errors: string;
}
interface ErrorResponse {
error: string;
model: string;
usage: undefined;
}
const mapErrorToCompletion = (
error: ErrorConnectorResponse | Error,
model: string,
): ErrorResponse => {
if ('message' in error) {
return {
error: error.message,
model,
usage: undefined,
};
}
return {
error: `[${error.name}]: ${error.errors[0]}`,
model,
usage: undefined,
};
};
function encodeImage(imagePath: string): {
data: string;
format: string;
imageName: string;
} {
const imageExtName = path.extname(imagePath);
const imageName = path.basename(imagePath);
const imageBuffer = fs.readFileSync(imagePath);
return {
data: Buffer.from(imageBuffer).toString('base64'),
format: `image/${imageExtName.slice(1)}`,
imageName,
};
}
function base64ToBlob(base64: string, contentType: string): Blob {
const byteCharacters = atob(base64);
const byteNumbers = new Array(byteCharacters.length);
for (let i = 0; i < byteCharacters.length; i++) {
byteNumbers[i] = byteCharacters.charCodeAt(i);
}
const byteArray = new Uint8Array(byteNumbers);
return new Blob([byteArray], { type: contentType });
}
async function main(
model: string,
prompts: string[],
properties: Record<string, unknown>,
settings: Record<string, unknown>,
) {
const url = `https://api.stability.ai/v2beta/stable-image/generate/${model}`;
const total = prompts.length;
const outputs: Array<string | ErrorResponse> = [];
try {
for (let index = 0; index < total; index++) {
try {
const userPrompt = prompts[index];
const imageUrls = extractImageUrls(userPrompt);
const payload: RequestBody = {
prompt: userPrompt,
...properties,
};
const formData = new FormData();
Object.entries(payload).forEach(([key, value]) =>
formData.append(key, value),
);
for (const imageUrl of imageUrls) {
const { data, format, imageName } = encodeImage(imageUrl);
formData.append('image', base64ToBlob(data, format), imageName);
formData.append('mode', properties?.mode as string);
formData.append('strength', properties?.strength as string);
}
const response = await fetch(url, {
method: 'POST',
body: formData,
headers: {
Authorization: `Bearer ${settings?.['API_KEY']}`,
Accept: 'application/json',
},
});
if (response.status === 200) {
const data: SuccessResponse = await response.json();
console.log('Success data: ', data.finish_reason);
outputs.push(
`![${userPrompt}](data:image/${properties?.output_format ?? 'png'};base64,${data.image})`,
);
} else {
const data: ErrorConnectorResponse = await response.json();
console.log('Error data: ', data);
const completionWithError = mapErrorToCompletion(data, model);
outputs.push(completionWithError);
}
} catch (error) {
console.log(error);
const completionWithError = mapErrorToCompletion(error, model);
outputs.push(completionWithError);
}
}
return mapToResponse(outputs, model);
} catch (error) {
console.error('Error in main function:', error);
return { Error: error, ModelType: model };
}
}
function extractImageUrls(prompt: string): string[] {
const imageExtensions = ['.png', '.jpeg', '.webp'];
// Updated regex to match both http and local file paths
const urlRegex =
/(https?:\/\/[^\s]+|[a-zA-Z]:\\[^:<>"|?\n]*|\/[^:<>"|?\n]*)/g;
const urls = prompt.match(urlRegex) || [];
return urls.filter((url) => {
const extensionIndex = url.lastIndexOf('.');
if (extensionIndex === -1) {
// If no extension found, return false.
return false;
}
const extension = url.slice(extensionIndex);
return imageExtensions.includes(extension.toLowerCase());
});
}
export { main, config };