-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
171 lines (152 loc) · 6.38 KB
/
script.js
File metadata and controls
171 lines (152 loc) · 6.38 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
// ====== DOM ======
const promptForm = document.querySelector(".prompt-form");
const themeToggle = document.querySelector(".theme-toggle");
const promptBtn = document.querySelector(".prompt-btn");
const promptInput = document.querySelector(".prompt-input");
const generateBtn = document.querySelector(".generate-btn");
const galleryGrid = document.querySelector(".gallery-grid");
const modelSelect = document.getElementById("model-select");
const countSelect = document.getElementById("count-select");
const ratioSelect = document.getElementById("ratio-select");
// Put your real HF key here (you had one). Keeping placeholder for safety.
const API_KEY = "PASTE YOUR HUGGING FACE API KEY";
// Example prompts (kept)
const examplePrompts = [
"A magic forest with glowing plants and fairy homes among giant mushrooms",
"An old steampunk airship floating through golden clouds at sunset",
"A future Mars colony with glass domes and gardens against red mountains",
"A dragon sleeping on gold coins in a crystal cave",
"An underwater kingdom with merpeople and glowing coral buildings",
"A floating island with waterfalls pouring into clouds below",
"A witch's cottage in fall with magic herbs in the garden",
"A robot painting in a sunny studio with art supplies around it",
"A magical library with floating glowing books and spiral staircases",
"A Japanese shrine during cherry blossom season with lanterns and misty mountains",
"A cosmic beach with glowing sand and an aurora in the night sky",
"A medieval marketplace with colorful tents and street performers",
"A cyberpunk city with neon signs and flying cars at night",
"A peaceful bamboo forest with a hidden ancient temple",
"A giant turtle carrying a village on its back in the ocean",
];
// ====== THEME (kept behavior, icon swap) ======
(() => {
const saved = localStorage.getItem("theme");
const systemDark = window.matchMedia("(prefers-color-scheme: dark)").matches;
const isDark = saved === "dark" || (!saved && systemDark);
document.body.classList.toggle("dark-theme", isDark);
themeToggle.querySelector("i").className = isDark ? "fa-solid fa-sun" : "fa-solid fa-moon";
})();
themeToggle.addEventListener("click", () => {
const isDark = document.body.classList.toggle("dark-theme");
localStorage.setItem("theme", isDark ? "dark" : "light");
themeToggle.querySelector("i").className = isDark ? "fa-solid fa-sun" : "fa-solid fa-moon";
});
// ====== UTIL ======
const getImageDimensions = (aspectRatio, baseSize = 768) => {
const [w, h] = aspectRatio.split("/").map(Number);
const scale = baseSize / Math.sqrt(w*h);
let width = Math.floor((w * scale) / 16) * 16;
let height= Math.floor((h * scale) / 16) * 16;
return { width, height };
};
const updateImageCard = (index, imageUrl) => {
const card = document.getElementById(`img-card-${index}`);
if (!card) return;
card.classList.remove("loading", "error");
card.innerHTML = `
<img class="result-img" src="${imageUrl}" alt="AI Image ${index+1}" />
<div class="img-overlay">
<a href="${imageUrl}" class="img-download-btn" title="Download Image" download>
<i class="fa-solid fa-download"></i>
</a>
</div>
`;
};
const generateImages = async (selectedModel, imageCount, aspectRatio, promptText) => {
const MODEL_URL = `https://api-inference.huggingface.co/models/${selectedModel}`;
const { width, height } = getImageDimensions(aspectRatio);
generateBtn.setAttribute("disabled", "true");
const tasks = Array.from({ length: imageCount }, async (_, i) => {
try {
const response = await fetch(MODEL_URL, {
method: "POST",
headers: {
Authorization: `Bearer ${API_KEY}`,
"Content-Type": "application/json",
"x-use-cache": "false",
},
body: JSON.stringify({
inputs: promptText,
parameters: { width, height },
}),
});
if (!response.ok) {
let err;
try { err = (await response.json())?.error; } catch {}
throw new Error(err || `HTTP ${response.status}`);
}
const blob = await response.blob();
updateImageCard(i, URL.createObjectURL(blob));
} catch (err) {
console.error(err);
const card = document.getElementById(`img-card-${i}`);
if (card) {
card.classList.add("error");
const status = card.querySelector(".status-text");
if (status) status.textContent = "Generation failed. See console for details.";
}
}
});
await Promise.allSettled(tasks);
generateBtn.removeAttribute("disabled");
};
const createImageCards = (selectedModel, imageCount, aspectRatio, promptText) => {
galleryGrid.innerHTML = "";
for (let i=0; i<imageCount; i++){
const card = document.createElement("div");
card.className = "img-card loading";
card.id = `img-card-${i}`;
card.style.aspectRatio = aspectRatio;
card.innerHTML = `
<div class="status-container">
<div class="spinner"></div>
<i class="fa-solid fa-triangle-exclamation" style="display:none;"></i>
<p class="status-text">Generating...</p>
</div>
`;
galleryGrid.appendChild(card);
}
// Staggered animate-in
requestAnimationFrame(() => {
[...document.querySelectorAll(".img-card")].forEach((c, i) => {
setTimeout(() => c.classList.add("animate-in"), i * 80);
});
});
generateImages(selectedModel, imageCount, aspectRatio, promptText);
};
// ====== FORM ======
promptForm.addEventListener("submit", (e) => {
e.preventDefault();
const selectedModel = modelSelect.value;
const imageCount = parseInt(countSelect.value) || 1;
const aspectRatio = ratioSelect.value || "1/1";
const promptText = promptInput.value.trim();
if (!selectedModel || !promptText) return;
createImageCards(selectedModel, imageCount, aspectRatio, promptText);
});
// Random prompt typing effect (kept)
promptBtn.addEventListener("click", () => {
const prompt = examplePrompts[Math.floor(Math.random()*examplePrompts.length)];
let i = 0;
promptInput.focus();
promptInput.value = "";
promptBtn.disabled = true;
const iv = setInterval(() => {
if (i < prompt.length) {
promptInput.value += prompt.charAt(i++);
} else {
clearInterval(iv);
promptBtn.disabled = false;
}
}, 10);
});