-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
303 lines (271 loc) · 10.8 KB
/
app.js
File metadata and controls
303 lines (271 loc) · 10.8 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
/* ===== SPA + OpenAI client (Stages 1 & 2) ===== */
const STAGE_HOST = document.getElementById("stageHost");
const openaiKeyInput = document.getElementById("openaiKeyInput");
const rodinKeyInput = document.getElementById("rodinKeyInput");
const saveKeyBtn = document.getElementById("saveKeyBtn");
const state = {
openaiKey: "",
rodinKey: "",
vehicleImageFile: null,
vehicleName: "",
suggestedColors: [],
// Stage 2 results:
generatedImages: [] // [{ color, dataUrl, blob }]
};
// nav
document.querySelectorAll(".linkish").forEach(b=>{
b.addEventListener("click", ()=> loadStage(b.dataset.route));
});
// save keys
saveKeyBtn.addEventListener("click", () => {
state.openaiKey = openaiKeyInput.value.trim();
state.rodinKey = rodinKeyInput.value.trim();
sessionStorage.setItem("openai_key", state.openaiKey);
sessionStorage.setItem("rodin_key", state.rodinKey);
toast("Keys saved");
});
/* ---------- SPA loader ---------- */
async function loadStage(url){
const html = await fetch(url).then(r=>r.text());
STAGE_HOST.innerHTML = html;
if (url.endsWith("stage1.html")) initStage1();
if (url.endsWith("stage2.html")) initStage2();
if (url.endsWith("stage3.html")) initStage3Bridge(); // defined in stage3.js
}
window.addEventListener("DOMContentLoaded", () => {
state.openaiKey = sessionStorage.getItem("openai_key") || "";
state.rodinKey = sessionStorage.getItem("rodin_key") || "";
openaiKeyInput.value = state.openaiKey;
rodinKeyInput.value = state.rodinKey;
loadStage("stage1.html");
});
function toast(msg){
const el = document.createElement("div");
el.textContent = msg;
el.style.cssText = "position:fixed;bottom:20px;left:50%;transform:translateX(-50%);background:#111;color:#fff;padding:10px 14px;border-radius:10px;z-index:99";
document.body.appendChild(el);
setTimeout(()=> el.remove(), 1500);
}
/* ---------- Stage 1 ---------- */
function initStage1(){
const imageInput = document.getElementById("vehicleImage");
const nameInput = document.getElementById("vehicleName");
const suggestBtn = document.getElementById("suggestBtn");
const s1Status = document.getElementById("s1Status");
const colorsRaw = document.getElementById("colorsRaw");
const contBtn = document.getElementById("continueToStage2");
const resultWrap = document.getElementById("s1Result");
imageInput.addEventListener("change", (e)=> {
state.vehicleImageFile = e.target.files?.[0] || null;
});
nameInput.addEventListener("input", (e)=> state.vehicleName = e.target.value.trim());
suggestBtn.addEventListener("click", async () => {
if (!state.openaiKey) return s1Status.textContent = "Add your OpenAI API key.";
if (!state.vehicleImageFile) return s1Status.textContent = "Choose a vehicle image.";
if (!state.vehicleName) return s1Status.textContent = "Enter the vehicle name.";
s1Status.textContent = "Analysing image & suggesting colors…";
suggestBtn.disabled = true;
try {
const imgDataUrl = await fileToDataURL(state.vehicleImageFile);
const colorsText = await suggestColorsViaChat(imgDataUrl, state.vehicleName, state.openaiKey);
const colors = colorsText
.split(/\r?\n/)
.map(line => line.replace(/^\s*\d+\s*[).:-]?\s*/,"").trim())
.filter(Boolean)
.slice(0,6);
state.suggestedColors = colors;
resultWrap.style.display = "block";
colorsRaw.textContent = colors.map((c,i)=>`${i+1}. ${c}`).join("\n");
s1Status.textContent = "Done.";
contBtn.disabled = colors.length === 0;
contBtn.onclick = () => loadStage("stage2.html");
} catch (e) {
s1Status.textContent = `Error: ${e.message}`;
} finally {
suggestBtn.disabled = false;
}
});
}
/* ---------- Stage 2 ---------- */
function initStage2(){
const colorsEditor = document.getElementById("colorsEditor");
const generateBtn = document.getElementById("generateBtn");
const s2Status = document.getElementById("s2Status");
const gallery = document.getElementById("gallery");
const toStage3Btn = document.getElementById("continueToStage3");
let colors = state.suggestedColors.length ? [...state.suggestedColors] :
["Cherry Red","Pearl White","Midnight Black","Ocean Blue","Forest Green","Sunset Orange"];
renderTagsEditor(colorsEditor, colors, (newColors)=> colors = newColors);
generateBtn.addEventListener("click", async () => {
if (!state.openaiKey) return s2Status.textContent = "Add your OpenAI API key.";
if (!state.vehicleImageFile) return s2Status.textContent = "Vehicle image missing (go back to Stage 1).";
if (colors.length === 0) return s2Status.textContent = "Add at least one color.";
s2Status.textContent = "Generating images…";
generateBtn.disabled = true;
gallery.innerHTML = "";
state.generatedImages = [];
try {
for (const color of colors) {
s2Status.textContent = `Generating: ${color}…`;
const b64 = await generateRecolorImageEdit(state.vehicleImageFile, color, state.vehicleName, state.openaiKey);
const dataUrl = `data:image/png;base64,${b64}`;
const blob = dataURLToBlob(dataUrl);
state.generatedImages.push({ color, dataUrl, blob });
const card = document.createElement("div");
card.className = "gallery-item";
card.innerHTML = `
<img src="${dataUrl}" alt="${escapeHtml(color)} variant" />
<div class="caption">
<span>${escapeHtml(color)}</span>
<button class="icon-btn" title="Download" aria-label="Download">
<svg class="icon" viewBox="0 0 24 24">
<path d="M5 20h14v-2H5v2zm7-18l-5 5h3v6h4V7h3l-5-5z"/>
</svg>
</button>
</div>
`;
// download handler
card.querySelector(".icon-btn").addEventListener("click", ()=>{
const a = document.createElement("a");
a.href = dataUrl;
a.download = `vehicle_${color.replace(/\s+/g,'_').toLowerCase()}.png`;
a.click();
});
gallery.appendChild(card);
}
s2Status.textContent = "All images ready.";
toStage3Btn.disabled = state.generatedImages.length === 0;
toStage3Btn.onclick = () => loadStage("stage3.html");
} catch (e) {
s2Status.textContent = `Error: ${e.message}`;
} finally {
generateBtn.disabled = false;
}
});
}
/* ---------- Stage 3 bridge init (called after stage3.html loads) ---------- */
function initStage3Bridge(){
if (typeof initStage3 === "function") {
// Pass both keys to stage3.js via state
initStage3(state);
} else {
const s3 = document.getElementById("s3Status");
if (s3) s3.textContent = "Stage 3 script not loaded.";
}
}
/* ---------- UI helpers ---------- */
function renderTagsEditor(root, colors, onChange){
root.innerHTML = "";
const frag = document.createDocumentFragment();
colors.forEach((c, idx) => frag.appendChild(makeTag(c, idx)));
const add = document.createElement("button");
add.className = "tag add-tag";
add.textContent = "+ add color";
add.type = "button";
add.onclick = () => {
colors.push("New Color");
onChange(colors);
renderTagsEditor(root, colors, onChange);
};
frag.appendChild(add);
root.appendChild(frag);
function makeTag(text, index){
const tag = document.createElement("span");
tag.className = "tag";
const input = document.createElement("input");
input.value = text;
input.addEventListener("blur", save);
input.addEventListener("keydown", (e)=>{
if (e.key === "Enter") { input.blur(); }
if (e.key === "Escape") { input.value = text; input.blur(); }
});
const close = document.createElement("span");
close.className = "x";
close.textContent = "✕";
close.title = "Remove";
close.onclick = () => {
colors.splice(index,1);
onChange(colors);
renderTagsEditor(root, colors, onChange);
};
tag.appendChild(input);
tag.appendChild(close);
function save(){
colors[index] = input.value.trim() || text;
onChange(colors);
}
tag.addEventListener("click", ()=> input.focus());
return tag;
}
}
function fileToDataURL(file){
return new Promise((resolve, reject)=>{
const r = new FileReader();
r.onload = () => resolve(r.result);
r.onerror = () => reject(r.error);
r.readAsDataURL(file);
});
}
function dataURLToBlob(dataUrl){
const [hdr, b64] = dataUrl.split(",");
const mime = (hdr.match(/data:(.+);base64/) || [])[1] || "image/png";
const bin = atob(b64);
const len = bin.length;
const buf = new Uint8Array(len);
for (let i=0;i<len;i++) buf[i] = bin.charCodeAt(i);
return new Blob([buf], {type:mime});
}
function escapeHtml(s){
return s.replace(/[&<>"']/g, c => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));
}
/* ---------- OpenAI calls ---------- */
async function suggestColorsViaChat(imageDataUrl, vehicleName, apiKey){
const body = {
model: "gpt-4o-mini",
messages: [
{ role: "system", content: "You are a strict formatter. Output ONLY a numbered list of 6 specific color names. No extra words."},
{
role: "user",
content: [
{ type: "text", text: `Based on this vehicle photo and the name "${vehicleName}", list the six most commonly used specific colors worldwide for this vehicle. Format:\n1. Color Name\n2. ...\n3. ...\n4. ...\n5. ...\n6. ...` },
{ type: "image_url", image_url: { url: imageDataUrl } }
]
}
],
temperature: 0.4
};
const res = await fetch("https://api.openai.com/v1/chat/completions", {
method: "POST",
headers: { "Authorization": `Bearer ${apiKey}`, "Content-Type": "application/json" },
body: JSON.stringify(body)
});
if (!res.ok) {
const t = await res.text().catch(()=> "");
throw new Error(`Suggest API ${res.status}: ${t || res.statusText}`);
}
const data = await res.json();
const text = data.choices?.[0]?.message?.content?.trim();
if (!text) throw new Error("No colors returned");
return text;
}
async function generateRecolorImageEdit(originalFile, color, vehicleName, apiKey){
const prompt = `Recolor the vehicle in this image to "${color}". Keep all features, model, shape, trims, and details identical. Do not change pose or background. Use a clean white background. Vehicle: ${vehicleName}.`;
const fd = new FormData();
fd.append("model", "gpt-image-1");
fd.append("image[]", originalFile, originalFile.name);
fd.append("prompt", prompt);
fd.append("size", "1024x1024");
const res = await fetch("https://api.openai.com/v1/images/edits", {
method: "POST",
headers: { "Authorization": `Bearer ${apiKey}` },
body: fd
});
if (!res.ok) {
const t = await res.text().catch(()=> "");
throw new Error(`Image API ${res.status}: ${t || res.statusText}`);
}
const data = await res.json();
const b64 = data.data?.[0]?.b64_json;
if (!b64) throw new Error("No image data returned");
return b64;
}