-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathstability.js
167 lines (133 loc) · 4.67 KB
/
stability.js
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
import "https://deno.land/x/dotenv/load.ts";
const apiKey = Deno.env.get("STABILITY_API_KEY");
const FAST_CHEAP_MODEL = {
id: "stable-diffusion-512-v2-1",
width: 512,
height: 512,
widthWide: 768,
heightWide: 640,
}
const QUALITY_EXPENSIVE_MODEL = {
id: "stable-diffusion-xl-1024-v1-0",
width: 1024,
height: 1024,
widthWide: 1152,
heightWide: 896,
}
if (!apiKey) {
throw new Error("missing STABILITY_API_KEY environment variable");
}
const STEP_COUNT = 45;
const apiHost = "https://api.stability.ai";
export async function tryGenerate(
prompt,
negativeprompt,
format,
qualityEnabled = false,
maxAttempts = 3,
) {
let generated;
for (let i = 0; i < maxAttempts; i++) {
generated = await generate(prompt, negativeprompt, format, qualityEnabled);
if (generated.isValid) {
return generated.data;
}
if (generated.isInvalidPrompt) {
console.log(
{ isInvalidPrompt: generated.isInvalidPrompt },
"Prompt invalid, trying with words removed",
);
let cleanedPromptToTest;
const words = prompt.split(" ");
const wordsSet = new Set(words);
const uniqueWords = Array.from(wordsSet);
for (const word of uniqueWords) {
console.log({ word: word }, "removing word ");
const pattern = new RegExp("\\b" + word + "\\b", "g");
cleanedPromptToTest = prompt.replace(pattern, "");
generated = await generate(prompt, negativeprompt, format, engine);
if (generated.isValid) {
return generated.data;
}
}
console.log(
{
isValid: generated.isValid,
},
"No valid prompt found removing one word, generation failed",
);
console.log("No valid prompt found removing one word, generation failed");
return; // no image
}
console.log(
{
attempt: i,
attemptsLeft: maxAttempts - i,
isBlurred: generated.isBlurred,
isValid: generated.isValid,
},
"Image generation failed, requesting new image",
);
}
if (generated.isBlurred) {
return generated.data;
} // blurred image
else {
console.error("No image");
return;
} // no image
}
export async function generate(prompt, negativeprompt, format, qualityEnabled = false) {
const engine = qualityEnabled ? QUALITY_EXPENSIVE_MODEL : FAST_CHEAP_MODEL;
console.log("Calling Stability with model: ", engine);
const width = format == "wide" ? engine.widthWide : engine.width;
const height = format == "wide" ? engine.heightWide : engine.height;;
const url = `${apiHost}/v1alpha/generation/${engine.id}/text-to-image`;
try {
const response = await fetch(
url,
{
method: 'POST',
body: JSON.stringify({
cfg_scale: 7,
clip_guidance_preset: "FAST_BLUE",
height: height,
width: width,
// sampler: "K_DPMPP_2M",
samples: 1,
seed: 0,
steps: STEP_COUNT,
text_prompts: [
{
text: prompt,
weight: 1.0,
},
// {
// text: negativeprompt,
// weight: -1.0,
// },
],
}),
headers: {
"Content-Type": "application/json",
Accept: "image/png",
Authorization: apiKey,
}
},
);
for (let [key, value] of response.headers) {
console.log(`${key}: ${value}`);
}
const responseBuffer = await response.arrayBuffer();
console.log(response.headers.get("Finish-Reason"))
const isValid = response.headers.get("Finish-Reason") == "SUCCESS";
const isBlurred = response.headers.get("Finish-Reason") == "CONTENT_FILTERED";
return { data: responseBuffer, isValid, isBlurred };
} catch (error) {
console.error(error);
const errorData = await error.response.json();
const isInvalidPrompt = errorData.name == "invalid_prompts";
console.error(errorData, "error response data");
return { isInvalidPrompt };
}
}