abir614/i
0
1// ═══════════════════════════════════════2// STATE3// ═══════════════════════════════════════4let flow = 1, queue = [], results = [];5let _previewSrc = { w: 0, h: 0 };6 7// ═══════════════════════════════════════8// INLINE SERVER-PROGRESS OVERLAY9// Replaces the old model-download overlay —10// now shows server processing status11// ═══════════════════════════════════════12let _inlineOverlay = null;13 14function showInlineProgress(title, icon = '⚙️') {15 if (_inlineOverlay) return;16 _inlineOverlay = document.createElement('div');17 _inlineOverlay.id = 'inlineOverlay';18 _inlineOverlay.innerHTML = `19 <div class="mo-card">20 <div class="mo-icon-wrap">21 <svg class="mo-spinner" width="48" height="48" viewBox="0 0 48 48" fill="none">22 <circle cx="24" cy="24" r="20" stroke="rgba(198,241,53,0.12)" stroke-width="3"/>23 <path d="M24 4 A20 20 0 0 1 44 24" stroke="var(--a)" stroke-width="3" stroke-linecap="round"/>24 </svg>25 <span class="mo-icon-inner" id="ipoIcon">${icon}</span>26 </div>27 <div class="mo-title" id="ipoTitle">${title}</div>28 <div class="mo-sub" id="ipoSub">Sending to server…</div>29 <div class="mo-track">30 <div class="mo-bar-wrap">31 <div class="mo-bar" id="ipoBar" style="background:linear-gradient(90deg,var(--a2),var(--a))"></div>32 <div class="mo-bar-glow" id="ipoBarGlow" style="background:radial-gradient(ellipse,rgba(198,241,53,.55),transparent 70%)"></div>33 </div>34 <div class="mo-pct" id="ipoPct" style="color:var(--a)">—</div>35 </div>36 <div class="mo-files" id="ipoDetail"></div>37 <div class="mo-note">Processing on server · no downloads required</div>38 </div>`;39 document.body.appendChild(_inlineOverlay);40 requestAnimationFrame(() => _inlineOverlay.classList.add('visible'));41}42 43function updateInlineProgress(pct, sub, detail) {44 const bar = document.getElementById('ipoBar');45 const glow = document.getElementById('ipoBarGlow');46 const pctEl = document.getElementById('ipoPct');47 const subEl = document.getElementById('ipoSub');48 const detEl = document.getElementById('ipoDetail');49 if (bar) { bar.style.width = pct + '%'; }50 if (glow) { glow.style.left = pct + '%'; }51 if (pctEl) pctEl.textContent = typeof pct === 'number' ? Math.round(pct) + '%' : pct;52 if (subEl && sub != null) subEl.textContent = sub;53 if (detEl && detail != null) detEl.textContent = detail;54}55 56function hideInlineProgress() {57 if (!_inlineOverlay) return;58 _inlineOverlay.classList.add('hiding');59 setTimeout(() => { _inlineOverlay?.remove(); _inlineOverlay = null; }, 500);60}61 62// ═══════════════════════════════════════63// FLOW UI (unchanged from original)64// ═══════════════════════════════════════65function selectFlow(n) {66 flow = n;67 document.querySelectorAll('.ftab').forEach((b, i) => b.classList.toggle('active', i === n - 1));68 69 document.getElementById('bgModelGroup').classList.toggle('sg-hidden', n !== 2);70 document.getElementById('bgSensGroup').classList.toggle('sg-hidden', n !== 2);71 document.getElementById('bgFeatherGroup').classList.toggle('sg-hidden', n !== 2);72 document.getElementById('bgOutputGroup').classList.toggle('sg-hidden', n !== 2);73 document.getElementById('bgInfo').classList.toggle('sg-hidden', n !== 2);74 75 document.querySelectorAll('.resize-setting').forEach(el => el.classList.toggle('sg-hidden', n !== 3));76 document.getElementById('resizeInfo').classList.toggle('sg-hidden', n !== 3);77 document.getElementById('resizePreview').classList.toggle('sg-hidden', n !== 3);78 79 toggleFillColor();80 onResizeModeChange();81 renderTrack();82 if (n === 3) updateResizePreview();83}84 85function onResizeModeChange() {86 if (flow !== 3) return;87 const mode = document.getElementById('resizeMode')?.value;88 const blendGroup = document.getElementById('resizeBlendGroup');89 if (blendGroup) blendGroup.classList.toggle('sg-hidden', mode !== 'smart-crop-extend');90 const focusGroup = document.getElementById('resizeFocusGroup');91 if (focusGroup) focusGroup.classList.toggle('sg-hidden', mode !== 'smart-crop-extend');92 const fillEl = document.getElementById('resizeFill');93 if (!fillEl) return;94 const prevVal = fillEl.value;95 const hasBluryOption = [...fillEl.options].some(o => o.value === 'blur');96 const hasAIOption = [...fillEl.options].some(o => o.value === 'ai-extend');97 if (mode === 'proportional') {98 if (hasAIOption) [...fillEl.options].find(o => o.value === 'ai-extend')?.remove();99 if (!hasBluryOption) {100 const opt = document.createElement('option');101 opt.value = 'blur'; opt.textContent = 'Blurred Source (cinematic)';102 fillEl.insertBefore(opt, fillEl.options[1]);103 }104 if (fillEl.value === 'ai-extend' || !fillEl.value) fillEl.value = 'extend';105 } else {106 if (hasBluryOption) [...fillEl.options].find(o => o.value === 'blur')?.remove();107 if (!hasAIOption) {108 const opt = document.createElement('option');109 opt.value = 'ai-extend'; opt.textContent = '🤖 AI Environment Fill (smart)';110 const extOpt = [...fillEl.options].find(o => o.value === 'extend');111 if (extOpt) fillEl.insertBefore(opt, extOpt.nextSibling);112 else fillEl.appendChild(opt);113 }114 if (prevVal === 'blur' || !prevVal) fillEl.value = 'ai-extend';115 }116 toggleFillColor();117 updateResizePreview();118}119 120function renderTrack() {121 let steps;122 if (flow === 1) steps = [['🔎','Lanczos\nUpscale'],['📐','Shopify\nResize'],['🌐','WebP\nEncode']];123 else if (flow === 2) steps = [['🧠','ISNet AI\nBG Remove'],['✨','Refine\nEdges'],['🔎','Lanczos\nUpscale'],['🌐','WebP\nEncode']];124 else steps = [['🔍','Detect\nSubject'],['🔎','Upscale'],['⚡','Smart\nResize'],['🌐','Encode']];125 126 document.getElementById('pipeTrack').innerHTML = steps.map((s, i) => `127 <div class="pt-step">128 <div class="pt-icon" id="ptd-${i}">${s[0]}</div>129 <div class="pt-label" id="ptl-${i}">${s[1].replace('\n','<br>')}</div>130 </div>131 ${i < steps.length - 1 ? `<div class="pt-line" id="ptln-${i}"></div>` : ''}132 `).join('');133}134 135function pipeStep(i, state) {136 const d = document.getElementById('ptd-' + i);137 const l = document.getElementById('ptln-' + i);138 if (d) { d.classList.remove('running','done'); if (state) d.classList.add(state); }139 if (state === 'done' && l) l.classList.add('done');140}141 142function resetTrack() {143 document.querySelectorAll('.pt-icon').forEach(d => d.classList.remove('running','done'));144 document.querySelectorAll('.pt-line').forEach(l => l.classList.remove('done'));145}146 147function toggleFillColor() {148 const mode = document.getElementById('resizeFill')?.value;149 const cg = document.getElementById('fillColorGroup');150 if (!cg) return;151 cg.classList.toggle('sg-hidden', mode !== 'color' || flow !== 3);152}153 154// ─── Live resize preview (browser-only, purely cosmetic) ────────────────155function updateResizePreview() {156 if (flow !== 3) return;157 const tw = parseInt(document.getElementById('resizeW')?.value) || 0;158 const th = parseInt(document.getElementById('resizeH')?.value) || 0;159 const mode = document.getElementById('resizeMode')?.value || 'smart-crop-extend';160 161 const rpSrc = document.getElementById('rpSrc');162 const rpTarget = document.getElementById('rpTarget');163 const rpW = document.getElementById('rpW');164 const rpH = document.getElementById('rpH');165 166 if (rpTarget) rpTarget.textContent = tw && th ? `${tw} × ${th}` : '—';167 168 if (!_previewSrc.w || !tw || !th) {169 if (rpSrc) rpSrc.textContent = _previewSrc.w ? `${_previewSrc.w} × ${_previewSrc.h}` : '(drop image)';170 if (rpW) { rpW.textContent = 'W: —'; rpW.className = 'rp-axis'; }171 if (rpH) { rpH.textContent = 'H: —'; rpH.className = 'rp-axis'; }172 return;173 }174 if (rpSrc) rpSrc.textContent = `${_previewSrc.w} × ${_previewSrc.h}`;175 176 if (mode === 'proportional') {177 const ratio = Math.min(tw / _previewSrc.w, th / _previewSrc.h);178 const fw = Math.round(_previewSrc.w * ratio), fh = Math.round(_previewSrc.h * ratio);179 const padW = tw - fw, padH = th - fh;180 if (rpW) { rpW.textContent = `W: scale → ${fw}px (${padW>0?'+'+padW+' pad':'no pad'})`; rpW.className='rp-axis fit'; }181 if (rpH) { rpH.textContent = `H: scale → ${fh}px (${padH>0?'+'+padH+' pad':'no pad'})`; rpH.className='rp-axis fit'; }182 } else {183 const sW=_previewSrc.w, sH=_previewSrc.h, sAR=sW/sH, tAR=tw/th;184 let wLabel,hLabel,wCls,hCls;185 if (sW<tw&&sH<th) {186 wLabel=`W: ${sW}px → extend → ${tw}px`; wCls='extend';187 hLabel=`H: ${sH}px → extend → ${th}px`; hCls='extend';188 } else if (sW>=tw&&sH>=th) {189 if (Math.abs(sAR-tAR)<0.005) { wLabel=`W: scale → ${tw}px`; wCls='match'; hLabel=`H: scale → ${th}px`; hCls='match'; }190 else if (sAR>tAR) { wLabel=`W: crop → ${tw}px (subject-centred)`; wCls='crop'; hLabel=`H: fit ✓`; hCls='match'; }191 else { wLabel=`W: fit ✓`; wCls='match'; hLabel=`H: crop → ${th}px (subject-centred)`; hCls='crop'; }192 } else if (sW<tw) { wLabel=`W: extend → ${tw}px`; wCls='extend'; hLabel=`H: crop → ${th}px`; hCls='crop'; }193 else { wLabel=`W: crop → ${tw}px`; wCls='crop'; hLabel=`H: extend → ${th}px`; hCls='extend'; }194 if (rpW) { rpW.textContent=wLabel; rpW.className='rp-axis '+wCls; }195 if (rpH) { rpH.textContent=hLabel; rpH.className='rp-axis '+hCls; }196 }197}198 199// ═══════════════════════════════════════200// FILE INPUT201// ═══════════════════════════════════════202const dz = document.getElementById('dropZone');203const fi = document.getElementById('fileInput');204dz.addEventListener('dragover', e => { e.preventDefault(); dz.classList.add('drag'); });205dz.addEventListener('dragleave', () => dz.classList.remove('drag'));206dz.addEventListener('drop', e => { e.preventDefault(); dz.classList.remove('drag'); addFiles([...e.dataTransfer.files]); });207fi.addEventListener('change', () => { addFiles([...fi.files]); fi.value = ''; });208 209function addFiles(files) {210 files.filter(f => f.type.startsWith('image/')).forEach(f => {211 if (queue.find(q => q.name === f.name && q.size === f.size)) return;212 const item = { id: Date.now() + Math.random(), file: f, name: f.name, size: f.size };213 queue.push(item);214 renderQI(item);215 });216 syncQ();217}218 219function renderQI(item) {220 document.getElementById('emptyMsg')?.remove();221 const div = document.createElement('div');222 div.className = 'qi'; div.id = 'qi-' + item.id;223 div.innerHTML = `224 <img class="qi-thumb" id="qt-${item.id}" src="">225 <div>226 <div class="qi-name">${item.name}</div>227 <div class="qi-meta"><span>${(item.size/1024).toFixed(0)} KB</span><span id="qdm-${item.id}">—</span></div>228 <div class="qpb" id="qpb-${item.id}"><div class="qpbr" id="qpbr-${item.id}"></div></div>229 </div>230 <span class="qs sw" id="qs-${item.id}">WAITING</span>`;231 document.getElementById('queueList').appendChild(div);232 233 const r = new FileReader();234 r.onload = e => { const el = document.getElementById('qt-' + item.id); if (el) el.src = e.target.result; };235 r.readAsDataURL(item.file);236 237 const img = new Image();238 img.onload = () => {239 const d = document.getElementById('qdm-' + item.id);240 if (d) d.textContent = img.width + '×' + img.height;241 _previewSrc = { w: img.width, h: img.height };242 updateResizePreview();243 URL.revokeObjectURL(img.src);244 };245 img.src = URL.createObjectURL(item.file);246}247 248function syncQ() {249 document.getElementById('qCount').textContent = queue.length + (queue.length === 1 ? ' file' : ' files');250 document.getElementById('runBtn').disabled = queue.length === 0;251}252 253function clearQueue() {254 queue = [];255 _previewSrc = { w: 0, h: 0 };256 document.getElementById('queueList').innerHTML = '<div class="empty" id="emptyMsg">No images queued</div>';257 syncQ();258 updateResizePreview();259}260 261function setQS(id, cls, txt) { const e = document.getElementById('qs-'+id); if (e) { e.className='qs '+cls; e.textContent=txt; } }262function setPB(id, show, pct) {263 const pb = document.getElementById('qpb-'+id), pbr = document.getElementById('qpbr-'+id);264 if (pb) pb.classList.toggle('on', show); if (pbr) pbr.style.width = pct+'%';265}266function log(msg, cls='') {267 const w = document.getElementById('logWrap');268 w.classList.add('on');269 const d = document.createElement('div');270 d.className='log-line '+cls; d.textContent='» '+msg;271 w.appendChild(d); w.scrollTop = w.scrollHeight;272}273 274// ═══════════════════════════════════════════════════════════════════275// PIPELINE RUNNER ← Now calls the server API276// ═══════════════════════════════════════════════════════════════════277 278async function runPipeline() {279 if (!queue.length) return;280 results = [];281 document.getElementById('resGrid').innerHTML = '';282 document.getElementById('resultsSection').style.display = 'none';283 document.getElementById('logWrap').innerHTML = '';284 document.getElementById('logWrap').classList.remove('on');285 document.getElementById('runBtn').disabled = true;286 287 // ── Collect settings from the UI ──288 const resizeMode = document.getElementById('resizeMode')?.value || 'smart-crop-extend';289 const cfg = {290 flow: flow,291 upscale_factor: parseFloat(document.getElementById('upscaleFactor').value),292 upscale_method: document.getElementById('upscaleMethod').value,293 shopify_size: parseInt(document.getElementById('shopifySize').value),294 webp_quality: parseInt(document.getElementById('webpQ').value),295 max_kb: parseInt(document.getElementById('maxKB').value),296 rename_pattern: document.getElementById('renamePattern').value.trim(),297 bg_model: document.getElementById('bgModel')?.value || 'isnet',298 alpha_threshold: parseInt(document.getElementById('bgSens')?.value) || 80,299 feather: parseInt(document.getElementById('bgFeather')?.value) || 1,300 output_format: document.getElementById('bgOutputFormat')?.value || 'webp',301 resize_w: parseInt(document.getElementById('resizeW')?.value) || 1200,302 resize_h: parseInt(document.getElementById('resizeH')?.value) || 1200,303 resize_mode: resizeMode,304 resize_focus: document.getElementById('resizeFocus')?.value || 'smart',305 resize_align: document.getElementById('resizeAlign')?.value || 'center',306 resize_blend: parseInt(document.getElementById('resizeBlend')?.value) || 40,307 resize_fill: document.getElementById('resizeFill')?.value || 'extend',308 fill_color: document.getElementById('fillColor')?.value || '#ffffff',309 };310 311 // ── Process each image ──312 for (const item of queue) {313 setQS(item.id, 'sp', 'PROCESSING');314 setPB(item.id, true, 5);315 resetTrack();316 log(`Processing: ${item.name}`);317 318 try {319 const flowIcons = { 1:'🔎', 2:'🧠', 3:'⚡' };320 const flowNames = { 1:`Upscaling ×${cfg.upscale_factor}`, 2:'ISNet BG Removal', 3:'Smart Resize' };321 showInlineProgress(flowNames[flow] || 'Processing…', flowIcons[flow] || '⚙️');322 updateInlineProgress(10, 'Uploading to server…', item.name);323 324 // ── Build FormData ──325 const fd = new FormData();326 fd.append('file', item.file);327 Object.entries(cfg).forEach(([k, v]) => fd.append(k, v));328 329 // Animate a fake progress bar while waiting330 let fakeP = 10;331 const fakeTick = setInterval(() => {332 fakeP = Math.min(fakeP + (85 - fakeP) * 0.06, 84);333 updateInlineProgress(fakeP, 'Server processing…', item.name);334 setPB(item.id, true, Math.round(fakeP));335 }, 400);336 337 // ── Send to API ──338 const response = await fetch('/api/process', { method: 'POST', body: fd });339 340 clearInterval(fakeTick);341 updateInlineProgress(95, 'Receiving result…', '');342 343 if (!response.ok) {344 let errMsg = `Server error ${response.status}`;345 try { const j = await response.json(); errMsg = j.detail || errMsg; } catch {}346 throw new Error(errMsg);347 }348 349 const blob = await response.blob();350 351 // ── Parse response headers ──352 const outName = response.headers.get('X-IMGFLOW-Name') || `output_${item.name}`;353 const dims = response.headers.get('X-IMGFLOW-Dims') || '—';354 const srvLog = response.headers.get('X-IMGFLOW-Log') || '';355 const srvTime = response.headers.get('X-IMGFLOW-Time') || '';356 357 updateInlineProgress(100, `Done ✓ (${srvTime})`, '');358 hideInlineProgress();359 360 // Read as dataURL for preview361 const dataURL = await _blobToDataURL(blob);362 363 const out = {364 id: item.id,365 name: outName,366 blob,367 dataURL,368 orig: item.size,369 size: blob.size,370 dims,371 };372 results.push(out);373 addResult(out);374 setQS(item.id, 'sd', 'DONE');375 setPB(item.id, true, 100);376 377 if (srvLog) srvLog.split(' | ').forEach(l => log(` ✓ ${l}`, 'ok'));378 log(` ✓ ${outName} — ${(blob.size/1024).toFixed(0)} KB ${srvTime}`, 'ok');379 380 // Mark all pipe steps done381 const stepCount = flow === 2 ? 4 : 3;382 for (let i = 0; i < stepCount; i++) pipeStep(i, 'done');383 384 } catch (err) {385 hideInlineProgress();386 setQS(item.id, 'se', 'ERROR');387 log(` ✗ ${err.message}`, 'err');388 console.error(err);389 }390 391 setPB(item.id, false, 0);392 resetTrack();393 }394 395 document.getElementById('statsCount').textContent = results.length;396 document.getElementById('resultsSection').style.display = 'block';397 document.getElementById('resCount').textContent = results.length + ' file' + (results.length !== 1 ? 's' : '');398 document.getElementById('runBtn').disabled = false;399 log(`Done. ${results.length} file(s) ready.`, 'ok');400}401 402// Blob → data URL403function _blobToDataURL(blob) {404 return new Promise((res, rej) => {405 const r = new FileReader();406 r.onload = () => res(r.result);407 r.onerror = () => rej(new Error('FileReader failed'));408 r.readAsDataURL(blob);409 });410}411 412// ═══════════════════════════════════════413// RESULT CARDS414// ═══════════════════════════════════════415function addResult(r) {416 const s = Math.round((1 - r.size / r.orig) * 100);417 const card = document.createElement('div');418 card.className = 'rc';419 card.innerHTML = `420 <img class="rc-img" src="${r.dataURL}" alt="${r.name}">421 <div class="rc-body">422 <div class="rc-name">${r.name}</div>423 <div class="rc-stats">424 <span class="pill py">${(r.size/1024).toFixed(0)} KB</span>425 <span class="pill ${s>0?'pg':'pr'}">${s>0?'↓':'↑'}${Math.abs(s)}%</span>426 <span class="pill pg">${r.dims}</span>427 </div>428 <button class="dl-btn" onclick="dlOne('${r.id}')">⬇ DOWNLOAD</button>429 </div>`;430 document.getElementById('resGrid').appendChild(card);431 document.getElementById('resultsSection').style.display = 'block';432}433 434function dlOne(id) {435 const r = results.find(x => String(x.id) === String(id));436 if (!r) return;437 const a = document.createElement('a');438 a.href = URL.createObjectURL(r.blob);439 a.download = r.name;440 a.click();441}442 443async function downloadAll() {444 if (!results.length) return;445 const zip = new JSZip();446 results.forEach(r => zip.file(r.name, r.blob));447 const blob = await zip.generateAsync({ type: 'blob' });448 const a = document.createElement('a');449 a.href = URL.createObjectURL(blob);450 a.download = 'imgflow_pipeline.zip';451 a.click();452}453 454// ═══════════════════════════════════════455// PRESETS456// ═══════════════════════════════════════457function applyPreset(p) {458 document.querySelectorAll('.preset-btn').forEach(b => b.classList.toggle('active', b.dataset.preset === p));459 if (p === 'quick') {460 document.getElementById('upscaleMethod').value = 'bicubic';461 document.getElementById('upscaleFactor').value = '2';462 document.getElementById('webpQ').value = 75; document.getElementById('qv').textContent = 75;463 document.getElementById('maxKB').value = 300;464 } else if (p === 'balanced') {465 document.getElementById('upscaleMethod').value = 'lanczos';466 document.getElementById('upscaleFactor').value = '2';467 document.getElementById('webpQ').value = 85; document.getElementById('qv').textContent = 85;468 document.getElementById('maxKB').value = 500;469 } else {470 document.getElementById('upscaleMethod').value = 'lanczos';471 document.getElementById('upscaleFactor').value = '3';472 document.getElementById('webpQ').value = 95; document.getElementById('qv').textContent = 95;473 document.getElementById('maxKB').value = 2000;474 }475}476 477// ═══════════════════════════════════════478// INIT479// ═══════════════════════════════════════480renderTrack();481 