-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
69 lines (53 loc) · 1.92 KB
/
script.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
const token = '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';
const inputTxt = document.getElementById("input");
const image = document.getElementById("image");
const button = document.getElementById("btn");
async function query() {
image.src = 'loading.gif';
const response = await fetch(
"https://api-inference.huggingface.co/models/ZB-Tech/Text-to-Image",
{
headers: {
Authorization: `Bearer ${token}`,
},
method: "POST",
body: JSON.stringify({
inputs: inputTxt.value
}),
}
);
if (!response.ok) {
throw new Error("Failed to fetch the image. Please try again.");
}
const result = await response.blob();
return result;
}
button.addEventListener('click', async function () {
if (!inputTxt.value.trim()) {
alert("Please enter a text prompt.");
return;
}
try {
const response = await query();
const objectURL = URL.createObjectURL(response);
image.src = objectURL;
let downloadBtn = document.getElementById("downloadBtn");
if (!downloadBtn) {
downloadBtn = document.createElement("button");
downloadBtn.id = "downloadBtn";
downloadBtn.innerText = "Download Image";
document.body.appendChild(downloadBtn);
}
downloadBtn.addEventListener("click", () => {
const a = document.createElement("a");
a.href = image.src;
a.download = "generated_image.png";
document.body.appendChild(a);
a.click(); // Download the Image locally
document.body.removeChild(a);
});
} catch (error) {
console.error("Error:", error);
alert("Error generating image: " + error.message);
}
});