-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
94 lines (76 loc) · 2.74 KB
/
main.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
const apiKey = "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";
const maxImage = 4;
const selectedImageNumber = undefined;
function getRandomNumber(min, max) {
return Math.floor(Math.random() * (min - max + 1)) + min;
}
function disableGenerateButton() {
document.getElementById("generate").disabled = true;
}
function enableGenerateButton() {
document.getElementById("generate").disabled = false;
}
function clearImageGrid() {
const imageGrid = document.getElementById("image-grid");
imageGrid.innerHTML = "";
}
async function generateImages(input) {
disableGenerateButton();
clearImageGrid();
const loading = document.getElementById("loading");
loading.style.display = "block";
const imageUrls = [];
for (let i = 0; i < maxImage; i++) {
const randomNumber = getRandomNumber(1, 10000);
const prompt = `${input} ${randomNumber}`;
const response = await fetch(
"https://api-inference.huggingface.co/models/SG161222/Realistic_Vision_V1.4", {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${apiKey}`,
},
body: JSON.stringify({ inputs: prompt }),
}
);
if (!response.ok) {
const error = document.createElement("h2");
error.style.color = "red";
error.style.fontSize = "1.2rem";
const result = document.getElementById("result");
error.innerHTML = response.text();
result.appendChild(error);
}
const blob = await response.blob();
const imgUrl = URL.createObjectURL(blob);
imageUrls.push(imgUrl);
const img = document.createElement("img");
img.src = imgUrl;
img.alt = `art-${i + 1}`;
img.onclick = () => downloadImage(imgUrl, i);
document.getElementById("image-grid").appendChild(img);
}
loading.style.display = "none";
enableGenerateButton();
selectedImageNumber = null;
}
document.getElementById("generate").addEventListener("click", () => {
const input = document.getElementById("user-prompt").value;
console.log(input);
generateImages(input);
});
document.getElementById("form").addEventListener("submit", (e) => {
e.preventDefault();
const input = document.getElementById("user-prompt").value;
console.log(input);
generateImages(input);
});
function downloadImage(imgUrl, imageNumber) {
const link = document.createElement("a");
link.href = imgUrl;
link.download = `image-${imageNumber + 1}.jpg`;
link.click();
}
document.addEventListener("DOMContentLoaded", () => {
document.getElementById("splash").classList.add("loaded");
});