-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathimplementation.js
More file actions
67 lines (61 loc) · 1.57 KB
/
Copy pathimplementation.js
File metadata and controls
67 lines (61 loc) · 1.57 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
async function image_generation_via_stable_diffusion(params, userSettings) {
const { prompt } = params;
const { stabilityAPIKey, width, height } = userSettings;
validateAPIKey(stabilityAPIKey);
try {
const imageData = await generateImageFromStabilityAPI(
stabilityAPIKey,
prompt,
Number(width) || 512,
Number(height) || 512
);
return imageData;
} catch (error) {
console.error('Error generating image:', error);
throw new Error(`Error: ${error.message}`);
}
}
function validateAPIKey(apiKey) {
if (!apiKey) {
throw new Error(
'Please set a Stable Diffusion API Key in the plugin settings.'
);
}
}
async function generateImageFromStabilityAPI(apiKey, prompt, width, height) {
const apiUrl =
'https://api.stability.ai/v1/generation/stable-diffusion-v1-6/text-to-image';
const response = await fetch(apiUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${apiKey}`,
},
body: JSON.stringify({
text_prompts: [{ text: prompt }],
cfg_scale: 7,
samples: 1,
steps: 30,
width: width,
height: height,
}),
});
if (!response.ok) {
const errorText = await response.text();
throw new Error(
`Stability API error: ${response.status}, Message: ${errorText}`
);
}
const data = await response.json();
return {
cards: [
{
type: 'image',
image: {
url: `data:image/png;base64,${data.artifacts[0].base64}`,
alt: prompt,
},
},
],
};
}