-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
364 lines (283 loc) · 12.2 KB
/
Copy pathscript.js
File metadata and controls
364 lines (283 loc) · 12.2 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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
// const generateForm = document.querySelector(".generate-form");
// const generateBtn = generateForm.querySelector(".generate-btn");
// const imageGallery = document.querySelector(".image-gallery");
// // const OPENAI_API_KEY = "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";
// const OPENAI_API_KEY = "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";
// // Your OpenAI API key here
// let isImageGenerating = false;
// const updateImageCard = (imgDataArray) => {
// imgDataArray.forEach((imgObject, index) => {
// const imgCard = imageGallery.querySelectorAll(".img-card")[index];
// const imgElement = imgCard.querySelector("img");
// const downloadBtn = imgCard.querySelector(".download-btn");
// // Set the image source to the AI-generated image data
// const aiGeneratedImage = `data:image/jpeg;base64,${imgObject.b64_json}`;
// imgElement.src = aiGeneratedImage;
// // When the image is loaded, remove the loading class and set download attributes
// imgElement.onload = () => {
// imgCard.classList.remove("loading");
// downloadBtn.setAttribute("href", aiGeneratedImage);
// downloadBtn.setAttribute("download", `${new Date().getTime()}.jpg`);
// }
// });
// }
// const generateAiImages = async (userPrompt, userImgQuantity) => {
// try {
// // Send a request to the OpenAI API to generate images based on user inputs
// const response = await fetch("https://api.openai.com/v1/images/generations", {
// method: "POST",
// headers: {
// "Content-Type": "application/json",
// "Authorization": `Bearer ${OPENAI_API_KEY}`,
// },
// body: JSON.stringify({
// prompt: userPrompt,
// n: userImgQuantity,
// size: "512x512",
// response_format: "b64_json"
// }),
// });
// // Throw an error message if the API response is unsuccessful
// // if(!response.ok) throw new Error("Failed to generate AI images. Make sure your API key is valid.");
// const { data } = await response.json(); // Get data from the response
// updateImageCard([...data]);
// } catch (error) {
// alert(error.message);
// } finally {
// generateBtn.removeAttribute("disabled");
// generateBtn.innerText = "Generate";
// isImageGenerating = false;
// }
// }
// const handleImageGeneration = (e) => {
// e.preventDefault();
// if(isImageGenerating) return;
// // Get user input and image quantity values
// const userPrompt = e.srcElement[0].value;
// const userImgQuantity = parseInt(e.srcElement[1].value);
// // Disable the generate button, update its text, and set the flag
// generateBtn.setAttribute("disabled", true);
// generateBtn.innerText = "Generating";
// isImageGenerating = true;
// // Creating HTML markup for image cards with loading state
// const imgCardMarkup = Array.from({ length: userImgQuantity }, () =>
// `<div class="img-card loading">
// <img src="images/loader.svg" alt="AI generated image">
// <a class="download-btn" href="#">
// <img src="images/download.svg" alt="download icon">
// </a>
// </div>`
// ).join("");
// imageGallery.innerHTML = imgCardMarkup;
// generateAiImages(userPrompt, userImgQuantity);
// }
// generateForm.addEventListener("submit", handleImageGeneration);
// const OPENAI_API_KEY = "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";
// const generateForm = document.querySelector(".generate-form");
// const generateBtn = generateForm.querySelector(".generate-btn");
// const imageGallery = document.querySelector(".image-gallery");
// let isImageGenerating = false;
// const updateImageCard = (imgDataArray) => {
// imgDataArray.forEach((imgObject, index) => {
// const imgCard = imageGallery.querySelectorAll(".img-card")[index];
// const imgElement = imgCard.querySelector("img");
// const downloadBtn = imgCard.querySelector(".download-btn");
// const aiGeneratedImage = `data:image/jpeg;base64,${imgObject.b64_json}`;
// imgElement.src = aiGeneratedImage;
// imgElement.onload = () => {
// imgCard.classList.remove("loading");
// downloadBtn.setAttribute("href", aiGeneratedImage);
// downloadBtn.setAttribute("download", `${new Date().getTime()}.jpg`);
// };
// });
// };
// const generateAiImages = async (userPrompt, userImgQuantity) => {
// try {
// const response = await fetch("https://api.openai.com/v1/images/generations", {
// method: "POST",
// headers: {
// "Content-Type": "application/json",
// "Authorization": `Bearer ${OPENAI_API_KEY}`,
// },
// body: JSON.stringify({
// prompt: userPrompt,
// n: userImgQuantity,
// size: "512x512",
// response_format: "url",
// }),
// });
// if (!response.ok) {
// const errorResponse = await response.json();
// throw new Error(`Failed to generate AI images: ${errorResponse.error.message}`);
// }
// const { data } = await response.json();
// updateImageCard([...data]);
// } catch (error) {
// alert(error.message);
// } finally {
// generateBtn.removeAttribute("disabled");
// generateBtn.innerText = "Generate";
// isImageGenerating = false;
// }
// };
// const handleImageGeneration = async (e) => {
// e.preventDefault();
// if (isImageGenerating) return;
// const userPrompt = e.srcElement[0].value;
// const userImgQuantity = parseInt(e.srcElement[1].value);
// generateBtn.setAttribute("disabled", true);
// generateBtn.innerText = "Generating";
// isImageGenerating = true;
// const imgCardMarkup = Array.from({ length: userImgQuantity }, () =>
// `<div class="img-card loading">
// <img src="images/loader.svg" alt="AI generated image">
// <a class="download-btn" href="#">
// <img src="images/download.svg" alt="download icon">
// </a>
// </div>`
// ).join("");
// imageGallery.innerHTML = imgCardMarkup;
// await generateAiImages(userPrompt, userImgQuantity);
// };
// generateForm.addEventListener("submit", handleImageGeneration);
// const OPENAI_API_KEY = "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";
// const generateForm = document.querySelector(".generate-form");
// const generateBtn = generateForm.querySelector(".generate-btn");
// const imageGallery = document.querySelector(".image-gallery");
// let isImageGenerating = false;
// const updateImageCard = (imgURLArray) => {
// imgURLArray.forEach((imgURL, index) => {
// const imgCard = imageGallery.querySelectorAll(".img-card")[index];
// const imgElement = imgCard.querySelector("img");
// const downloadBtn = imgCard.querySelector(".download-btn");
// // Assuming the response is in URL format
// const aiGeneratedImage = imgURL;
// imgElement.src = aiGeneratedImage;
// imgElement.onload = () => {
// imgCard.classList.remove("loading");
// downloadBtn.setAttribute("href", aiGeneratedImage);
// downloadBtn.setAttribute("download", `${new Date().getTime()}.jpg`);
// };
// });
// };
// const generateAiImages = async (userPrompt, userImgQuantity) => {
// try {
// const response = await fetch("https://api.openai.com/v1/images/generations", {
// method: "POST",
// headers: {
// "Content-Type": "application/json",
// "Authorization": `Bearer ${OPENAI_API_KEY}`,
// },
// body: JSON.stringify({
// prompt: userPrompt,
// max_tokens: 50, // Adjust as needed
// n: userImgQuantity,
// }),
// });
// if (!response.ok) {
// const errorResponse = await response.json();
// throw new Error(`Failed to generate AI images: ${errorResponse.error.message}`);
// }
// const { choices } = await response.json();
// const imageURLs = choices.map(choice => choice.text.trim());
// updateImageCard(imageURLs);
// } catch (error) {
// alert(error.message);
// } finally {
// generateBtn.removeAttribute("disabled");
// generateBtn.innerText = "Generate";
// isImageGenerating = false;
// }
// };
// const handleImageGeneration = async (e) => {
// e.preventDefault();
// if (isImageGenerating) return;
// const userPrompt = e.srcElement[0].value;
// const userImgQuantity = parseInt(e.srcElement[1].value);
// generateBtn.setAttribute("disabled", true);
// generateBtn.innerText = "Generating";
// isImageGenerating = true;
// const imgCardMarkup = Array.from({ length: userImgQuantity }, () =>
// `<div class="img-card loading">
// <img src="images/loader.svg" alt="AI generated image">
// <a class="download-btn" href="#">
// <img src="images/download.svg" alt="download icon">
// </a>
// </div>`
// ).join("");
// imageGallery.innerHTML = imgCardMarkup;
// await generateAiImages(userPrompt, userImgQuantity);
// };
// generateForm.addEventListener("submit", handleImageGeneration);
const generateForm = document.querySelector(".generate-form");
const generateBtn = generateForm.querySelector(".generate-btn");
const imageGallery = document.querySelector(".image-gallery");
const OPENAI_API_KEY = "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";
let isImageGenerating = false;
const updateImageCard = (imgDataArray) => {
imgDataArray.forEach((imgObject, index) => {
const imgCard = imageGallery.querySelectorAll(".img-card")[index];
const imgElement = imgCard.querySelector("img");
const downloadBtn = imgCard.querySelector(".download-btn");
// Set the image source to the AI-generated image data
const aiGeneratedImage = `data:image/jpeg;base64,${imgObject.b64_json}`;
imgElement.src = aiGeneratedImage;
// When the image is loaded, remove the loading class and set download attributes
imgElement.onload = () => {
imgCard.classList.remove("loading");
downloadBtn.setAttribute("href", aiGeneratedImage);
downloadBtn.setAttribute("download", `${new Date().getTime()}.jpg`);
}
});
}
const generateAiImages = async (userPrompt, userImgQuantity) => {
try {
// Send a request to the OpenAI API to generate images based on user inputs
const response = await fetch("https://api.openai.com/v1/images/generations", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${OPENAI_API_KEY}`,
},
body: JSON.stringify({
prompt: userPrompt,
n: userImgQuantity,
size: "512x512",
response_format: "b64_json"
}),
});
// Throw an error message if the API response is unsuccessful
if(!response.ok) throw new Error("Failed to generate AI images. Make sure your API key is valid.");
const { data } = await response.json(); // Get data from the response
updateImageCard([...data]);
} catch (error) {
alert(error.message);
} finally {
generateBtn.removeAttribute("disabled");
generateBtn.innerText = "Generate";
isImageGenerating = false;
}
}
const handleImageGeneration = (e) => {
e.preventDefault();
if(isImageGenerating) return;
// Get user input and image quantity values
const userPrompt = e.srcElement[0].value;
const userImgQuantity = parseInt(e.srcElement[1].value);
// Disable the generate button, update its text, and set the flag
generateBtn.setAttribute("disabled", true);
generateBtn.innerText = "Generating";
isImageGenerating = true;
// Creating HTML markup for image cards with loading state
const imgCardMarkup = Array.from({ length: userImgQuantity }, () =>
`<div class="img-card loading">
<img src="images/loader.svg" alt="AI generated image">
<a class="download-btn" href="#">
<img src="images/download.svg" alt="download icon">
</a>
</div>`
).join("");
imageGallery.innerHTML = imgCardMarkup;
generateAiImages(userPrompt, userImgQuantity);
}
generateForm.addEventListener("submit", handleImageGeneration);