Spaces:
Paused
Paused
F1: debugging fixes (tap pick, a11y, Esc/focus, pause, ctx-loss, timers) + F2 real studios via public Gradio Spaces
Browse files- app.js +33 -15
- index.html +3 -3
- real.js +181 -0
- style.css +14 -1
- vendor/gradio-client.js +3 -0
- widgets.js +9 -6
app.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
| 1 |
import * as THREE from './vendor/three.module.min.js';
|
| 2 |
-
import { STUDIOS, stopLoops } from './widgets.js?v=
|
|
|
|
| 3 |
import { icon } from './icons.js?v=30';
|
| 4 |
import { RoomEnvironment } from './vendor/addons/environments/RoomEnvironment.js';
|
| 5 |
import { EffectComposer } from './vendor/addons/postprocessing/EffectComposer.js';
|
|
@@ -28,6 +29,7 @@ $('#snd').onclick = toggleSound; $('#snd').innerHTML = icon('mute');
|
|
| 28 |
/* ---------- three setup ---------- */
|
| 29 |
let renderer = null, gl3d = true, composer = null, bloom = null;
|
| 30 |
try {
|
|
|
|
| 31 |
renderer = new THREE.WebGLRenderer({ canvas: $('#gl'), antialias: !isMobile, powerPreference: 'high-performance' });
|
| 32 |
} catch (e) { gl3d = false; console.warn('WebGL unavailable, 2D fallback'); }
|
| 33 |
if (renderer) { renderer.toneMapping = THREE.ACESFilmicToneMapping; renderer.toneMappingExposure = 1.05; }
|
|
@@ -115,7 +117,8 @@ const cats = $('#cats');
|
|
| 115 |
CATS.forEach(c => { const b = document.createElement('button'); b.textContent = c.toUpperCase(); b.dataset.c = c; b.onclick = () => setCat(c); cats.append(b); });
|
| 116 |
function setCat(c) { cat = c; [...cats.children].forEach(b => b.classList.toggle('on', b.dataset.c === c)); beep(520); const v = visible(); if (!v.includes(sel)) select(v[0]); }
|
| 117 |
function visible() { return nodes.map((n, i) => i).filter(i => cat === 'Alle' || nodes[i].userData.s.cat === cat || nodes[i].userData.s.id === 'merge'); }
|
| 118 |
-
const labels = STUDIOS.map((s, i) => { const d = document.createElement('div'); d.className = 'lbl'; d.innerHTML = `${icon(s.id)}<span>${s.name}</span>`; d.dataset.cat = s.cat; d.title = s.cat + ' · ' + s.like;
|
|
|
|
| 119 |
d.onmouseenter = () => select(i); d.onclick = (e) => { e.stopPropagation(); select(i); open(i); }; $('#labels').append(d); return d; });
|
| 120 |
function select(i) { if (i == null) return; if (sel !== i) beep(660, .03); sel = i; labels.forEach((l, k) => l.classList.toggle('sel', k === i)); }
|
| 121 |
const pop = $('#pop');
|
|
@@ -123,9 +126,11 @@ function open(i) {
|
|
| 123 |
stopLoops(); openId = i; const s = STUDIOS[i]; beep(990, .08, 'triangle');
|
| 124 |
pop.innerHTML = `<div class="ph"><span class="pi">${icon(s.id)}</span><span class="pt"><b>${s.name}</b><small>${s.cat === '+' ? 'Modul' : s.cat} · ${s.like}</small></span><button aria-label="schließen">${icon('close')}</button></div><div class="pb"></div><div class="pf"><span>STUDIO ${String(i + 1).padStart(2, '0')}/${STUDIOS.length}</span><span>● SIMULATION</span></div>`;
|
| 125 |
pop.classList.remove('in'); void pop.offsetWidth; pop.classList.add('in'); focusNode(i);
|
| 126 |
-
pop.hidden = false; pop.querySelector('.ph button').onclick = close; s.build(pop.querySelector('.pb'));
|
|
|
|
| 127 |
}
|
| 128 |
-
|
|
|
|
| 129 |
function placePop() {
|
| 130 |
if (openId == null || innerWidth < 700) return;
|
| 131 |
const W = pop.offsetWidth, H = pop.offsetHeight; const x = innerWidth - W - Math.max(40, innerWidth * .06);
|
|
@@ -144,39 +149,44 @@ const keys = {};
|
|
| 144 |
let started = false, lookK = 0;
|
| 145 |
addEventListener('keydown', e => {
|
| 146 |
if (!started) { start(); return; }
|
| 147 |
-
if (e.
|
|
|
|
|
|
|
|
|
|
| 148 |
const v = visible(), k = v.indexOf(sel);
|
| 149 |
if (['ArrowRight', 'd', 'D', 'ArrowDown', 's', 'S'].includes(e.key)) select(v[(k + 1) % v.length]);
|
| 150 |
else if (['ArrowLeft', 'a', 'A', 'ArrowUp', 'w', 'W'].includes(e.key)) select(v[(k - 1 + v.length) % v.length]);
|
| 151 |
else if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); open(sel); }
|
| 152 |
-
else if (e.key === '
|
| 153 |
else if (e.key === 'q' || e.key === 'Q') cycleQ();
|
| 154 |
else if (e.key === 'm' || e.key === 'M') toggleSound();
|
| 155 |
-
else if (e.key === '
|
| 156 |
});
|
| 157 |
const mouse = new THREE.Vector2(9, 9), ray = new THREE.Raycaster(); let drag = null;
|
| 158 |
const cv = $('#gl');
|
| 159 |
const ptrs = new Map(); let pinch0 = 0, lastMv = 0, idleT = 0; const ZMIN = 12, ZMAX = 34;
|
| 160 |
addEventListener('pointermove', e => { mouse.set(e.clientX / innerWidth * 2 - 1, -(e.clientY / innerHeight) * 2 + 1); });
|
| 161 |
cv.addEventListener('pointerdown', e => { if (!started) return; cv.setPointerCapture(e.pointerId); ptrs.set(e.pointerId, { x: e.clientX, y: e.clientY }); idleT = 0;
|
| 162 |
-
if (ptrs.size === 1) drag = { x: e.clientX, y: e.clientY, moved: 0, t: performance.now(), v: 0, vp: 0 };
|
| 163 |
if (ptrs.size === 2) { const [a, b] = [...ptrs.values()]; pinch0 = Math.hypot(a.x - b.x, a.y - b.y); drag = null; } });
|
| 164 |
cv.addEventListener('pointermove', e => { const p = ptrs.get(e.pointerId); if (!p) return; p.x = e.clientX; p.y = e.clientY; idleT = 0;
|
| 165 |
if (ptrs.size === 2) { const [a, b] = [...ptrs.values()]; const d = Math.hypot(a.x - b.x, a.y - b.y); if (pinch0) cam.tr = Math.max(ZMIN, Math.min(ZMAX, cam.tr * pinch0 / d)); pinch0 = d; return; }
|
| 166 |
if (!drag) return; const now = performance.now(), dts = Math.max(.008, (now - (lastMv || now)) / 1000); lastMv = now;
|
| 167 |
const dx = e.clientX - drag.x, dy = e.clientY - drag.y; drag.moved += Math.abs(dx) + Math.abs(dy); drag.x = e.clientX; drag.y = e.clientY;
|
| 168 |
-
if (drag.moved > 6) { const w = -dx * .005; cam.tth += w; cam.th += w; drag.v = drag.v * .6 + (w / dts) * .4; cam.tph = Math.max(.45, Math.min(1.5, cam.tph - dy * .004)); cv.style.cursor = 'grabbing'; } });
|
|
|
|
|
|
|
| 169 |
function endPtr(e) { if (!ptrs.has(e.pointerId)) return; ptrs.delete(e.pointerId); if (ptrs.size < 2) pinch0 = 0; lastMv = 0;
|
| 170 |
-
if (drag && ptrs.size === 0) { if (drag.moved <=
|
| 171 |
-
if (hi < 0) { let bd = e.pointerType === 'mouse' ? 18 : 34; nodes.forEach((n, k) => { const p = screenPos(n); const d = Math.hypot(p.x - e.clientX, p.y - e.clientY); if (p.z < 1 && d < bd) { bd = d; hi = k; } }); }
|
| 172 |
if (hi >= 0) { select(hi); open(hi); navigator.vibrate?.(8); } }
|
| 173 |
else spin = Math.max(-3, Math.min(3, drag.v)); drag = null; cv.style.cursor = ''; } }
|
| 174 |
-
cv.addEventListener('pointerup', endPtr); cv.addEventListener('pointercancel',
|
| 175 |
cv.addEventListener('wheel', e => { if (!started) return; e.preventDefault(); idleT = 0; cam.tr = Math.max(ZMIN, Math.min(ZMAX, cam.tr * Math.exp(e.deltaY * .0012))); }, { passive: false });
|
| 176 |
let spin = 0;
|
| 177 |
function cycleQ() { qMode = qMode === 'AUTO' ? 'HIGH' : qMode === 'HIGH' ? 'LOW' : 'AUTO'; if (qMode !== 'AUTO') quality = qMode.toLowerCase(); applyQuality(); }
|
| 178 |
$('#q').onclick = cycleQ;
|
| 179 |
-
|
|
|
|
| 180 |
// gamepad
|
| 181 |
let gpCool = 0;
|
| 182 |
function pollPad() { const p = navigator.getGamepads ? [...navigator.getGamepads()].find(Boolean) : null; if (!p) return; if (Math.abs(p.axes[2] || 0) > .15) cam.tth += p.axes[2] * .04; if (Math.abs(p.axes[3] || 0) > .15) cam.tph = Math.max(.45, Math.min(1.5, cam.tph + p.axes[3] * .02)); if (gpCool-- > 0) return;
|
|
@@ -212,8 +222,16 @@ const spring = (s, target, dt, w) => { const n = Math.max(1, Math.ceil(dt / .008
|
|
| 212 |
const sp = { th: { x: 0, v: 0 }, ph: { x: 1.15, v: 0 }, r: { x: 60, v: 0 }, lk: { x: 0, v: 0 }, mx: { x: 0, v: 0 }, my: { x: 0, v: 0 } };
|
| 213 |
const AR = { pr: 1, ema: 16.7, t: 0, slow: 0 }; let lastT = performance.now();
|
| 214 |
function setPR(p) { if (!renderer) return; AR.pr = p; renderer.setPixelRatio(p); renderer.setSize(innerWidth, innerHeight, false); if (composer) { composer.setPixelRatio(p); composer.setSize(innerWidth, innerHeight); } }
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 215 |
function frame(now) {
|
| 216 |
requestAnimationFrame(frame);
|
|
|
|
| 217 |
now = now ?? performance.now(); const rawMs = now - lastT; lastT = now; const dt = Math.min(rawMs / 1000, .1) || .016; clock.elapsedTime += dt; const t = clock.elapsedTime;
|
| 218 |
frames++; fpsT += dt; if (fpsT > 1) { const fps = Math.round(frames / fpsT); $('#fps').textContent = fps + ' fps'; window.__fps = fps; frames = 0; fpsT = 0; }
|
| 219 |
if (renderer && started && qMode === 'AUTO') { AR.ema = AR.ema * .9 + rawMs * .1; AR.t += dt;
|
|
@@ -279,11 +297,11 @@ function frame(now) {
|
|
| 279 |
}
|
| 280 |
}
|
| 281 |
setPR(1); applyQuality();
|
| 282 |
-
window.__studius = { core: () => screenPos(core), get sel() { return sel; }, get openId() { return openId; }, get zoom() { return cam.r; }, get th() { return cam.th; }, nodeScreen: (i) => screenPos(nodes[i]), open: (i) => { select(i); open(i); } };
|
| 283 |
if (gl3d) requestAnimationFrame(frame); else { setTimeout(() => start(), 7800);
|
| 284 |
document.body.insertAdjacentHTML('beforeend', '<div style="position:fixed;left:14px;top:60px;z-index:16;color:#faa968;font-size:11px">⚠ WebGL nicht verfügbar – 2D-Modus</div>');
|
| 285 |
// minimal 2D loop to keep labels in a ring
|
| 286 |
-
const tick = () => { requestAnimationFrame(tick); const t = performance.now() / 1000; nodes.forEach((n, i) => { const u = n.userData; const a = u.a + t * .04; n.position.set(Math.cos(a) * u.R, u.y, Math.sin(a) * u.R); });
|
| 287 |
camera.position.set(0, 18, 18); camera.lookAt(0, 0, 0); camera.updateMatrixWorld(); if (started) nodes.forEach((n, i) => { n.updateMatrixWorld(); const p = screenPos(n); labels[i].style.transform = `translate(${p.x}px,${p.y}px) translate(-50%,-50%)`; }); };
|
| 288 |
tick();
|
| 289 |
}
|
|
|
|
| 1 |
import * as THREE from './vendor/three.module.min.js';
|
| 2 |
+
import { STUDIOS, stopLoops } from './widgets.js?v=40';
|
| 3 |
+
import './real.js?v=40';
|
| 4 |
import { icon } from './icons.js?v=30';
|
| 5 |
import { RoomEnvironment } from './vendor/addons/environments/RoomEnvironment.js';
|
| 6 |
import { EffectComposer } from './vendor/addons/postprocessing/EffectComposer.js';
|
|
|
|
| 29 |
/* ---------- three setup ---------- */
|
| 30 |
let renderer = null, gl3d = true, composer = null, bloom = null;
|
| 31 |
try {
|
| 32 |
+
const tc = document.createElement('canvas'); if (!(tc.getContext('webgl2') || tc.getContext('webgl'))) throw new Error('no webgl');
|
| 33 |
renderer = new THREE.WebGLRenderer({ canvas: $('#gl'), antialias: !isMobile, powerPreference: 'high-performance' });
|
| 34 |
} catch (e) { gl3d = false; console.warn('WebGL unavailable, 2D fallback'); }
|
| 35 |
if (renderer) { renderer.toneMapping = THREE.ACESFilmicToneMapping; renderer.toneMappingExposure = 1.05; }
|
|
|
|
| 117 |
CATS.forEach(c => { const b = document.createElement('button'); b.textContent = c.toUpperCase(); b.dataset.c = c; b.onclick = () => setCat(c); cats.append(b); });
|
| 118 |
function setCat(c) { cat = c; [...cats.children].forEach(b => b.classList.toggle('on', b.dataset.c === c)); beep(520); const v = visible(); if (!v.includes(sel)) select(v[0]); }
|
| 119 |
function visible() { return nodes.map((n, i) => i).filter(i => cat === 'Alle' || nodes[i].userData.s.cat === cat || nodes[i].userData.s.id === 'merge'); }
|
| 120 |
+
const labels = STUDIOS.map((s, i) => { const d = document.createElement('div'); d.className = 'lbl'; d.innerHTML = `${icon(s.id)}<span>${s.name}</span>`; d.dataset.cat = s.cat; d.title = s.cat + ' · ' + s.like; d.tabIndex = 0; d.setAttribute('role', 'button'); d.setAttribute('aria-label', s.name + ' öffnen – ' + s.like);
|
| 121 |
+
d.onkeydown = (e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); e.stopPropagation(); select(i); open(i); } }; d.onfocus = () => select(i);
|
| 122 |
d.onmouseenter = () => select(i); d.onclick = (e) => { e.stopPropagation(); select(i); open(i); }; $('#labels').append(d); return d; });
|
| 123 |
function select(i) { if (i == null) return; if (sel !== i) beep(660, .03); sel = i; labels.forEach((l, k) => l.classList.toggle('sel', k === i)); }
|
| 124 |
const pop = $('#pop');
|
|
|
|
| 126 |
stopLoops(); openId = i; const s = STUDIOS[i]; beep(990, .08, 'triangle');
|
| 127 |
pop.innerHTML = `<div class="ph"><span class="pi">${icon(s.id)}</span><span class="pt"><b>${s.name}</b><small>${s.cat === '+' ? 'Modul' : s.cat} · ${s.like}</small></span><button aria-label="schließen">${icon('close')}</button></div><div class="pb"></div><div class="pf"><span>STUDIO ${String(i + 1).padStart(2, '0')}/${STUDIOS.length}</span><span>● SIMULATION</span></div>`;
|
| 128 |
pop.classList.remove('in'); void pop.offsetWidth; pop.classList.add('in'); focusNode(i);
|
| 129 |
+
pop.hidden = false; pop.setAttribute('role', 'dialog'); pop.setAttribute('aria-label', s.name + ' Studio'); pop.querySelector('.ph button').onclick = close; retFocus = document.activeElement; s.build(pop.querySelector('.pb')); const bd = pop.querySelector('.pf span:last-child'); if (s.real) { bd.textContent = '● REAL · ' + s.real; bd.classList.add('real'); }
|
| 130 |
+
setTimeout(() => { if (openId === i && !pop.contains(document.activeElement)) pop.querySelector('.ph button').focus({ preventScroll: true }); }, 30); placePop(); $('#wire').classList.add('on'); setTimeout(placePop, 60);
|
| 131 |
}
|
| 132 |
+
let retFocus = null;
|
| 133 |
+
function close() { if (openId == null && pop.hidden) return; stopLoops(); if (openId != null) cam.tr = cam.base; const was = openId; openId = null; pop.hidden = true; pop.innerHTML = ''; if (was != null) (retFocus && retFocus.isConnected && retFocus !== document.body ? retFocus : labels[was]).focus?.({ preventScroll: true }); $('#wire').classList.remove('on'); beep(300); }
|
| 134 |
function placePop() {
|
| 135 |
if (openId == null || innerWidth < 700) return;
|
| 136 |
const W = pop.offsetWidth, H = pop.offsetHeight; const x = innerWidth - W - Math.max(40, innerWidth * .06);
|
|
|
|
| 149 |
let started = false, lookK = 0;
|
| 150 |
addEventListener('keydown', e => {
|
| 151 |
if (!started) { start(); return; }
|
| 152 |
+
if (e.key === 'Escape') { close(); return; }
|
| 153 |
+
if (e.target.matches('input,textarea,select,[contenteditable]')) return;
|
| 154 |
+
if (pop.contains(e.target)) return; // don't hijack keys inside the studio
|
| 155 |
+
if (e.target.classList?.contains('lbl') && (e.key === 'Enter' || e.key === ' ')) return;
|
| 156 |
const v = visible(), k = v.indexOf(sel);
|
| 157 |
if (['ArrowRight', 'd', 'D', 'ArrowDown', 's', 'S'].includes(e.key)) select(v[(k + 1) % v.length]);
|
| 158 |
else if (['ArrowLeft', 'a', 'A', 'ArrowUp', 'w', 'W'].includes(e.key)) select(v[(k - 1 + v.length) % v.length]);
|
| 159 |
else if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); open(sel); }
|
| 160 |
+
else if (e.key === 'Backspace') close();
|
| 161 |
else if (e.key === 'q' || e.key === 'Q') cycleQ();
|
| 162 |
else if (e.key === 'm' || e.key === 'M') toggleSound();
|
| 163 |
+
else if (e.key === 'c' || e.key === 'C') { setCat(CATS[(CATS.indexOf(cat) + 1) % CATS.length]); }
|
| 164 |
});
|
| 165 |
const mouse = new THREE.Vector2(9, 9), ray = new THREE.Raycaster(); let drag = null;
|
| 166 |
const cv = $('#gl');
|
| 167 |
const ptrs = new Map(); let pinch0 = 0, lastMv = 0, idleT = 0; const ZMIN = 12, ZMAX = 34;
|
| 168 |
addEventListener('pointermove', e => { mouse.set(e.clientX / innerWidth * 2 - 1, -(e.clientY / innerHeight) * 2 + 1); });
|
| 169 |
cv.addEventListener('pointerdown', e => { if (!started) return; cv.setPointerCapture(e.pointerId); ptrs.set(e.pointerId, { x: e.clientX, y: e.clientY }); idleT = 0;
|
| 170 |
+
if (ptrs.size === 1) drag = { x: e.clientX, y: e.clientY, moved: 0, t: performance.now(), v: 0, vp: 0, pick: pickAt(e.clientX, e.clientY, e.pointerType) };
|
| 171 |
if (ptrs.size === 2) { const [a, b] = [...ptrs.values()]; pinch0 = Math.hypot(a.x - b.x, a.y - b.y); drag = null; } });
|
| 172 |
cv.addEventListener('pointermove', e => { const p = ptrs.get(e.pointerId); if (!p) return; p.x = e.clientX; p.y = e.clientY; idleT = 0;
|
| 173 |
if (ptrs.size === 2) { const [a, b] = [...ptrs.values()]; const d = Math.hypot(a.x - b.x, a.y - b.y); if (pinch0) cam.tr = Math.max(ZMIN, Math.min(ZMAX, cam.tr * pinch0 / d)); pinch0 = d; return; }
|
| 174 |
if (!drag) return; const now = performance.now(), dts = Math.max(.008, (now - (lastMv || now)) / 1000); lastMv = now;
|
| 175 |
const dx = e.clientX - drag.x, dy = e.clientY - drag.y; drag.moved += Math.abs(dx) + Math.abs(dy); drag.x = e.clientX; drag.y = e.clientY;
|
| 176 |
+
if (drag.moved > (e.pointerType === 'mouse' ? 6 : 14)) { const w = -dx * .005; cam.tth += w; cam.th += w; drag.v = drag.v * .6 + (w / dts) * .4; cam.tph = Math.max(.45, Math.min(1.5, cam.tph - dy * .004)); cv.style.cursor = 'grabbing'; } });
|
| 177 |
+
function pickAt(x, y, type) { mouse.set(x / innerWidth * 2 - 1, -(y / innerHeight) * 2 + 1); ray.setFromCamera(mouse, camera); const h = ray.intersectObjects(nodes, false)[0]; let hi = h ? h.object.userData.i : -1;
|
| 178 |
+
if (hi < 0) { let bd = type === 'mouse' ? 18 : 40; nodes.forEach((n, k) => { const p = screenPos(n); const d = Math.hypot(p.x - x, p.y - y); if (p.z < 1 && d < bd) { bd = d; hi = k; } }); } return hi; }
|
| 179 |
function endPtr(e) { if (!ptrs.has(e.pointerId)) return; ptrs.delete(e.pointerId); if (ptrs.size < 2) pinch0 = 0; lastMv = 0;
|
| 180 |
+
if (drag && ptrs.size === 0) { if (drag.moved <= (e.pointerType === 'mouse' ? 6 : 14)) { let hi = drag.pick; if (hi < 0) hi = pickAt(e.clientX, e.clientY, e.pointerType);
|
|
|
|
| 181 |
if (hi >= 0) { select(hi); open(hi); navigator.vibrate?.(8); } }
|
| 182 |
else spin = Math.max(-3, Math.min(3, drag.v)); drag = null; cv.style.cursor = ''; } }
|
| 183 |
+
cv.addEventListener('pointerup', endPtr); cv.addEventListener('pointercancel', e => { ptrs.delete(e.pointerId); if (!ptrs.size) { drag = null; pinch0 = 0; cv.style.cursor = ''; } });
|
| 184 |
cv.addEventListener('wheel', e => { if (!started) return; e.preventDefault(); idleT = 0; cam.tr = Math.max(ZMIN, Math.min(ZMAX, cam.tr * Math.exp(e.deltaY * .0012))); }, { passive: false });
|
| 185 |
let spin = 0;
|
| 186 |
function cycleQ() { qMode = qMode === 'AUTO' ? 'HIGH' : qMode === 'HIGH' ? 'LOW' : 'AUTO'; if (qMode !== 'AUTO') quality = qMode.toLowerCase(); applyQuality(); }
|
| 187 |
$('#q').onclick = cycleQ;
|
| 188 |
+
let rsT = 0; const onResize = () => { camera.aspect = innerWidth / innerHeight; camera.updateProjectionMatrix(); applyQuality(); if (innerWidth < 700) { pop.style.left = ''; pop.style.top = ''; } placePop(); };
|
| 189 |
+
addEventListener('resize', () => { cancelAnimationFrame(rsT); rsT = requestAnimationFrame(onResize); }); addEventListener('orientationchange', () => setTimeout(onResize, 250)); screen.orientation?.addEventListener?.('change', () => setTimeout(onResize, 250));
|
| 190 |
// gamepad
|
| 191 |
let gpCool = 0;
|
| 192 |
function pollPad() { const p = navigator.getGamepads ? [...navigator.getGamepads()].find(Boolean) : null; if (!p) return; if (Math.abs(p.axes[2] || 0) > .15) cam.tth += p.axes[2] * .04; if (Math.abs(p.axes[3] || 0) > .15) cam.tph = Math.max(.45, Math.min(1.5, cam.tph + p.axes[3] * .02)); if (gpCool-- > 0) return;
|
|
|
|
| 222 |
const sp = { th: { x: 0, v: 0 }, ph: { x: 1.15, v: 0 }, r: { x: 60, v: 0 }, lk: { x: 0, v: 0 }, mx: { x: 0, v: 0 }, my: { x: 0, v: 0 } };
|
| 223 |
const AR = { pr: 1, ema: 16.7, t: 0, slow: 0 }; let lastT = performance.now();
|
| 224 |
function setPR(p) { if (!renderer) return; AR.pr = p; renderer.setPixelRatio(p); renderer.setSize(innerWidth, innerHeight, false); if (composer) { composer.setPixelRatio(p); composer.setSize(innerWidth, innerHeight); } }
|
| 225 |
+
let paused = document.hidden, ctxLost = false;
|
| 226 |
+
document.addEventListener('visibilitychange', () => { paused = document.hidden; lastT = performance.now(); if (paused) { spin = 0; ac?.suspend?.(); } else if (soundOn) ac?.resume?.(); });
|
| 227 |
+
if (renderer) { const c = renderer.domElement;
|
| 228 |
+
c.addEventListener('webglcontextlost', e => { e.preventDefault(); ctxLost = true; if (!$('#ctxmsg')) document.body.insertAdjacentHTML('beforeend', '<div id="ctxmsg" role="status" style="position:fixed;left:50%;top:70px;transform:translateX(-50%);z-index:40;padding:6px 12px;border:1px solid #faa968;background:#000c;color:#faa968;font-size:12px;border-radius:6px">GPU-Kontext verloren – stelle wieder her…</div>'); });
|
| 229 |
+
c.addEventListener('webglcontextrestored', () => { ctxLost = false; $('#ctxmsg')?.remove(); applyQuality(); setPR(AR.pr); lastT = performance.now(); }); }
|
| 230 |
+
window.__studiusLoseCtx = () => renderer?.forceContextLoss?.();
|
| 231 |
+
window.__studiusRestoreCtx = () => renderer?.forceContextRestore?.();
|
| 232 |
function frame(now) {
|
| 233 |
requestAnimationFrame(frame);
|
| 234 |
+
if (paused || ctxLost) { lastT = now ?? performance.now(); window.__paused = (window.__paused || 0) + (paused ? 1 : 0); return; }
|
| 235 |
now = now ?? performance.now(); const rawMs = now - lastT; lastT = now; const dt = Math.min(rawMs / 1000, .1) || .016; clock.elapsedTime += dt; const t = clock.elapsedTime;
|
| 236 |
frames++; fpsT += dt; if (fpsT > 1) { const fps = Math.round(frames / fpsT); $('#fps').textContent = fps + ' fps'; window.__fps = fps; frames = 0; fpsT = 0; }
|
| 237 |
if (renderer && started && qMode === 'AUTO') { AR.ema = AR.ema * .9 + rawMs * .1; AR.t += dt;
|
|
|
|
| 297 |
}
|
| 298 |
}
|
| 299 |
setPR(1); applyQuality();
|
| 300 |
+
window.__studius = { core: () => screenPos(core), get sel() { return sel; }, get openId() { return openId; }, get zoom() { return cam.r; }, get th() { return cam.th; }, nodeScreen: (i) => screenPos(nodes[i]), open: (i) => { select(i); open(i); }, close: () => close(), get paused() { return paused; }, get ctxLost() { return ctxLost; } };
|
| 301 |
if (gl3d) requestAnimationFrame(frame); else { setTimeout(() => start(), 7800);
|
| 302 |
document.body.insertAdjacentHTML('beforeend', '<div style="position:fixed;left:14px;top:60px;z-index:16;color:#faa968;font-size:11px">⚠ WebGL nicht verfügbar – 2D-Modus</div>');
|
| 303 |
// minimal 2D loop to keep labels in a ring
|
| 304 |
+
const tick = () => { requestAnimationFrame(tick); if (document.hidden) return; const t = performance.now() / 1000; nodes.forEach((n, i) => { const u = n.userData; const a = u.a + t * .04; n.position.set(Math.cos(a) * u.R, u.y, Math.sin(a) * u.R); });
|
| 305 |
camera.position.set(0, 18, 18); camera.lookAt(0, 0, 0); camera.updateMatrixWorld(); if (started) nodes.forEach((n, i) => { n.updateMatrixWorld(); const p = screenPos(n); labels[i].style.transform = `translate(${p.x}px,${p.y}px) translate(-50%,-50%)`; }); };
|
| 306 |
tick();
|
| 307 |
}
|
index.html
CHANGED
|
@@ -8,7 +8,7 @@
|
|
| 8 |
<title>STUDIUS · DAS Studio — Einswarm</title>
|
| 9 |
<link rel="icon" href="assets/einswarm-mascot.webp">
|
| 10 |
<link rel="preload" href="fonts/outfit-latin-wght.woff2" as="font" type="font/woff2" crossorigin>
|
| 11 |
-
<link rel="stylesheet" href="style.css?v=
|
| 12 |
</head>
|
| 13 |
<body>
|
| 14 |
<canvas id="gl"></canvas>
|
|
@@ -45,10 +45,10 @@
|
|
| 45 |
<div id="labels"></div>
|
| 46 |
<svg id="wire"><line id="wl" x1="0" y1="0" x2="0" y2="0"/></svg>
|
| 47 |
<div id="pop" hidden></div>
|
| 48 |
-
<footer id="hint" hidden><kbd>←→</kbd><kbd>WASD</kbd> wählen <kbd>ENTER</kbd> öffnen <kbd>ESC</kbd> zurück <kbd>
|
| 49 |
|
| 50 |
<a id="bmc" href="https://www.buymeacoffee.com/2btainment" target="_blank" rel="noopener noreferrer">Buy me a coffee</a>
|
| 51 |
<noscript><p style="color:#f2c94c;padding:2em">STUDIUS braucht JavaScript.</p></noscript>
|
| 52 |
-
<script type="module" src="app.js?v=
|
| 53 |
</body>
|
| 54 |
</html>
|
|
|
|
| 8 |
<title>STUDIUS · DAS Studio — Einswarm</title>
|
| 9 |
<link rel="icon" href="assets/einswarm-mascot.webp">
|
| 10 |
<link rel="preload" href="fonts/outfit-latin-wght.woff2" as="font" type="font/woff2" crossorigin>
|
| 11 |
+
<link rel="stylesheet" href="style.css?v=40">
|
| 12 |
</head>
|
| 13 |
<body>
|
| 14 |
<canvas id="gl"></canvas>
|
|
|
|
| 45 |
<div id="labels"></div>
|
| 46 |
<svg id="wire"><line id="wl" x1="0" y1="0" x2="0" y2="0"/></svg>
|
| 47 |
<div id="pop" hidden></div>
|
| 48 |
+
<footer id="hint" hidden><kbd>←→</kbd><kbd>WASD</kbd> wählen <kbd>ENTER</kbd> öffnen <kbd>ESC</kbd> zurück <kbd>C</kbd> Kategorie <kbd>TAB</kbd> Fokus <kbd>Q</kbd> Qualität · Ziehen = Orbit</footer>
|
| 49 |
|
| 50 |
<a id="bmc" href="https://www.buymeacoffee.com/2btainment" target="_blank" rel="noopener noreferrer">Buy me a coffee</a>
|
| 51 |
<noscript><p style="color:#f2c94c;padding:2em">STUDIUS braucht JavaScript.</p></noscript>
|
| 52 |
+
<script type="module" src="app.js?v=40"></script>
|
| 53 |
</body>
|
| 54 |
</html>
|
real.js
ADDED
|
@@ -0,0 +1,181 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// STUDIUS real functions — public Gradio Spaces via self-hosted @gradio/client (no token, no secrets) + client-side tools.
|
| 2 |
+
import { Client, handle_file } from './vendor/gradio-client.js?v=271';
|
| 3 |
+
import { STUDIOS, every, onStop, loop, cv } from './widgets.js?v=40';
|
| 4 |
+
|
| 5 |
+
const esc = (t) => String(t).replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c]));
|
| 6 |
+
const hf = (s) => `<a href="https://huggingface.co/spaces/${s}" target="_blank" rel="noopener">${s}</a>`;
|
| 7 |
+
const conns = new Map();
|
| 8 |
+
function connect(space) {
|
| 9 |
+
if (!conns.has(space)) conns.set(space, Promise.race([Client.connect(space, { events: ['status', 'data'] }), new Promise((_, r) => setTimeout(() => r(new Error('Verbindung: Zeitüberschreitung')), 30000))]).catch(e => { conns.delete(space); throw e; }));
|
| 10 |
+
return conns.get(space);
|
| 11 |
+
}
|
| 12 |
+
window.__studiusLog = [];
|
| 13 |
+
/** run a Space endpoint robustly: status → onStatus, partial data → onData, hard timeout, cancel on close */
|
| 14 |
+
export async function run(space, ep, data, { onStatus = () => {}, onData = () => {}, timeout = 150000, el } = {}) {
|
| 15 |
+
const t0 = performance.now(); const c = await connect(space); const job = c.submit(ep, data);
|
| 16 |
+
let last = null, done = false, err = null; const cancel = () => { if (!done) { done = true; try { job.cancel?.(); } catch (e) {} } };
|
| 17 |
+
onStop(cancel); const to = setTimeout(() => { err = new Error('Zeitüberschreitung nach ' + Math.round(timeout / 1000) + ' s'); cancel(); }, timeout);
|
| 18 |
+
try {
|
| 19 |
+
for await (const m of job) {
|
| 20 |
+
if (done || (el && !el.isConnected)) break;
|
| 21 |
+
if (m.type === 'status') { onStatus(m); if (m.stage === 'error') { err = new Error(String(m.message || m.title || 'Backend-Fehler').replace(/<[^>]*>/g, '').trim()); break; } if (m.stage === 'complete' && last) break; }
|
| 22 |
+
else if (m.type === 'data') { last = m.data; onData(m.data); }
|
| 23 |
+
}
|
| 24 |
+
} finally { clearTimeout(to); done = true; }
|
| 25 |
+
if (err) throw err; if (el && !el.isConnected) throw new Error('abgebrochen'); if (!last) throw new Error('keine Daten');
|
| 26 |
+
window.__studiusLog.push({ space, ep, ms: Math.round(performance.now() - t0) }); return last;
|
| 27 |
+
}
|
| 28 |
+
const stTxt = (m) => m.stage === 'pending' ? (m.position != null ? `Warteschlange: Platz ${m.position + 1}${m.queue_size ? '/' + m.queue_size : ''}${m.eta ? ' · ETA ' + Math.round(m.eta) + ' s' : ''}` : 'Warte auf GPU…')
|
| 29 |
+
: m.stage === 'generating' ? (m.progress_data?.[0]?.index != null && m.progress_data[0].length ? `Generiere… ${m.progress_data[0].index}/${m.progress_data[0].length}` : 'Generiere…') : m.stage === 'complete' ? 'fertig' : m.stage || '';
|
| 30 |
+
const url = (f) => typeof f === 'string' ? f : f?.url || f?.path;
|
| 31 |
+
function badge(el, mode, space) {
|
| 32 |
+
const b = el.querySelector('.badge'); if (b) { b.className = 'badge ' + (mode === 'SIM' ? 'sim' : 'real'); b.textContent = mode; }
|
| 33 |
+
const f = el.closest('#pop')?.querySelector('.pf span:last-child'); if (f) { f.textContent = mode === 'SIM' ? '● SIMULATION (Fallback)' : '● ' + mode + ' · API'; f.classList.toggle('real', mode !== 'SIM'); }
|
| 34 |
+
}
|
| 35 |
+
async function dl(a, src, name) { // cross-origin download → blob URL
|
| 36 |
+
try { const r = await fetch(src); const b = await r.blob(); const u = URL.createObjectURL(b); onStop(() => URL.revokeObjectURL(u)); a.href = u; a.download = name; } catch (e) { a.href = src; a.target = '_blank'; }
|
| 37 |
+
}
|
| 38 |
+
function timer(el, sel) { const t0 = performance.now(); const s = el.querySelector(sel); return every(() => { if (s && s.dataset.base) s.textContent = s.dataset.base + ' · ' + ((performance.now() - t0) / 1000).toFixed(0) + ' s'; }, 1000); }
|
| 39 |
+
const setS = (el, txt, err) => { const s = el.querySelector('.stat'); if (!s) return; s.dataset.base = txt; s.textContent = txt; s.classList.toggle('err', !!err); };
|
| 40 |
+
const S = (id) => STUDIOS.find(s => s.id === id);
|
| 41 |
+
const keep = (el) => el.querySelectorAll('input,textarea').forEach(i => i.addEventListener('keydown', e => e.stopPropagation()));
|
| 42 |
+
|
| 43 |
+
/* 1 CHAT */
|
| 44 |
+
const CHAT = 'huggingface-projects/llama-3.2-3B-Instruct';
|
| 45 |
+
{ const s = S('chat'); s.real = 'API'; s.build = (el) => {
|
| 46 |
+
el.innerHTML = `<div class="row" style="margin:0 0 6px"><span class="badge real">REAL</span><span class="stat"></span></div><div class="chat" aria-live="polite"><p class="a">◆ STUDIUS-Chat (Llama 3.2 3B). Frag mich etwas.</p></div><div class="row"><input aria-label="Nachricht" placeholder="Nachricht… (Enter)"><button class="btn" aria-label="Senden">➤</button></div><div class="credit">powered by ${hf(CHAT)}</div>`;
|
| 47 |
+
const log = el.querySelector('.chat'), inp = el.querySelector('input'), btn = el.querySelector('.btn'); keep(el); let busy = false; const hist = [];
|
| 48 |
+
const R = ['Der Schwarm ist gerade offline – hier eine simulierte Antwort. 🐝', 'Simulation: Klar, machbar, mit Gold-Rand.'];
|
| 49 |
+
const send = async () => { const q = inp.value.trim(); if (!q || busy) return; busy = true; btn.disabled = true; inp.value = '';
|
| 50 |
+
log.insertAdjacentHTML('beforeend', `<p class="u">› ${esc(q)}</p>`); const p = document.createElement('p'); p.className = 'a'; p.textContent = '◆ ��'; log.append(p); log.scrollTop = 1e5;
|
| 51 |
+
const ctx = hist.slice(-4).map(([u, a]) => `User: ${u}\nAssistant: ${a}`).join('\n'); const msg = ctx ? ctx + '\nUser: ' + q : q;
|
| 52 |
+
setS(el, 'Verbinde…'); const tm = timer(el, '.stat'); let out = '';
|
| 53 |
+
try { await run(CHAT, '/generate', { message: msg, max_new_tokens: 400, temperature: .6, top_p: .9, top_k: 50, repetition_penalty: 1.2 }, { el, timeout: 90000,
|
| 54 |
+
onStatus: m => setS(el, stTxt(m)), onData: d => { const t = String(d[0] ?? ''); out = t.startsWith(out) ? t : out + t; p.textContent = '◆ ' + out; log.scrollTop = 1e5; } });
|
| 55 |
+
hist.push([q, out]); setS(el, '✔ gestreamt'); badge(el, 'REAL', CHAT);
|
| 56 |
+
} catch (e) { if (!el.isConnected) return; setS(el, '⚠ ' + e.message + ' – Simulation', true); badge(el, 'SIM'); const txt = R[Math.random() * R.length | 0]; p.textContent = '◆ ' + txt; }
|
| 57 |
+
finally { clearInterval(tm); busy = false; btn.disabled = false; window.__chatOut = out; } };
|
| 58 |
+
btn.onclick = send; inp.onkeydown = e => { e.stopPropagation(); if (e.key === 'Enter') send(); }; }; }
|
| 59 |
+
|
| 60 |
+
/* 2 IMAGE: Generate (FLUX) + Edit (local) */
|
| 61 |
+
const FLUX = 'black-forest-labs/FLUX.1-schnell';
|
| 62 |
+
{ const s = S('image'); const editBuild = s.build; s.real = 'API'; s.build = (el) => {
|
| 63 |
+
el.innerHTML = `<div class="tabs" role="tablist"><button class="btn" role="tab" data-tab="gen">Generate</button><button class="btn alt" role="tab" data-tab="edit">Edit</button></div><div class="tp"></div>`;
|
| 64 |
+
const tp = el.querySelector('.tp');
|
| 65 |
+
const gen = () => { tp.innerHTML = `<div class="row" style="margin:0 0 6px"><span class="badge real">REAL</span><span class="stat"></span></div><input aria-label="Bild-Prompt" value="Goldene Biene auf Hexagon-Kristall, cinematic, dunkler Hintergrund"><div class="row"><button class="btn go">Generieren</button><a class="btn alt dl" hidden>⬇ Download</a></div><div class="gen"></div><div class="credit">powered by ${hf(FLUX)} · 512×512 · 4 Steps</div>`;
|
| 66 |
+
keep(tp); const go = tp.querySelector('.go'), a = tp.querySelector('.dl');
|
| 67 |
+
go.onclick = async () => { go.disabled = true; a.hidden = true; setS(tp, 'Verbinde…'); const tm = timer(tp, '.stat');
|
| 68 |
+
try { const d = await run(FLUX, '/infer', { prompt: tp.querySelector('input').value, seed: 0, randomize_seed: true, width: 512, height: 512, num_inference_steps: 4 }, { el: tp, onStatus: m => setS(tp, stTxt(m)) });
|
| 69 |
+
const u = url(d[0]); tp.querySelector('.gen').innerHTML = `<img alt="Generiertes Bild" src="${esc(u)}">`; window.__imgUrl = u; await dl(a, u, 'studius-flux.webp'); a.hidden = false; setS(tp, '✔ Seed ' + d[1]); badge(el, 'REAL');
|
| 70 |
+
} catch (e) { if (!tp.isConnected) return; setS(tp, '⚠ ' + e.message + ' – Simulation', true); badge(el, 'SIM'); const c = document.createElement('canvas'); c.width = c.height = 256; const x = c.getContext('2d'); const g = x.createRadialGradient(128, 128, 10, 128, 128, 128); g.addColorStop(0, '#f2c94c'); g.addColorStop(1, '#05182e'); x.fillStyle = g; x.fillRect(0, 0, 256, 256); tp.querySelector('.gen').replaceChildren(c); }
|
| 71 |
+
finally { clearInterval(tm); go.disabled = false; } }; };
|
| 72 |
+
const tabs = el.querySelectorAll('[data-tab]');
|
| 73 |
+
tabs.forEach(b => b.onclick = () => { tabs.forEach(o => { o.classList.toggle('alt', o !== b); o.setAttribute('aria-selected', o === b); }); if (b.dataset.tab === 'gen') gen(); else { tp.innerHTML = '<div class="row" style="margin:0 0 6px"><span class="badge sim">LOKAL</span></div><div class="ed"></div>'; editBuild(tp.querySelector('.ed')); } });
|
| 74 |
+
tabs[0].click(); }; }
|
| 75 |
+
|
| 76 |
+
/* 3 MUSIC */
|
| 77 |
+
const ACE = 'ACE-Step/ACE-Step', TF = 'declare-lab/TangoFlux';
|
| 78 |
+
{ const s = S('music'); const sim = s.build; s.real = 'API'; s.build = (el) => {
|
| 79 |
+
el.innerHTML = `<div class="row" style="margin:0 0 6px"><span class="badge real">REAL</span><span class="stat"></span></div><input aria-label="Musik-Prompt" value="synthwave, retro, 100 BPM, warm pads, punchy drums"><div class="row"><button class="btn go">♪ Song erzeugen (15 s)</button><a class="btn alt dl" hidden>⬇ Download</a></div><div class="out"></div><div class="credit">powered by ${hf(ACE)} · Fallback ${hf(TF)}</div>`;
|
| 80 |
+
keep(el); const go = el.querySelector('.go'), a = el.querySelector('.dl');
|
| 81 |
+
go.onclick = async () => { go.disabled = true; a.hidden = true; const pr = el.querySelector('input').value; const tm = timer(el, '.stat'); let u, used, aceErr = '';
|
| 82 |
+
try { try { setS(el, 'Verbinde ACE-Step…'); const d = await run(ACE, '/__call__', { audio_duration: 15, prompt: pr, lyrics: '[instrumental]', infer_step: 27, guidance_scale: 15, scheduler_type: 'euler', cfg_type: 'apg', omega_scale: 10 }, { el, timeout: 180000, onStatus: m => setS(el, 'ACE-Step: ' + stTxt(m)) }); u = url(d[0]); used = ACE; }
|
| 83 |
+
catch (e) { if (!el.isConnected) return; console.warn('ACE-Step failed', e); setS(el, 'ACE-Step: ' + e.message + ' → TangoFlux…'); const d = await run(TF, '/predict', { prompt: pr, steps: 25, guidance: 4.5, duration: 10 }, { el, onStatus: m => setS(el, 'TangoFlux: ' + stTxt(m)) }); u = url(d[0] ?? d); used = TF; aceErr = e.message; }
|
| 84 |
+
el.querySelector('.out').innerHTML = `<audio controls src="${esc(u)}"></audio>`; window.__musicUrl = u; await dl(a, u, 'studius-music' + (u.match(/\.(mp3|wav|ogg|flac)/)?.[0] || '.mp3')); a.hidden = false; setS(el, '✔ ' + used.split('/')[1] + (aceErr ? ' (ACE-Step: ' + aceErr.slice(0, 60) + ')' : '')); badge(el, 'REAL');
|
| 85 |
+
} catch (e) { if (!el.isConnected) return; setS(el, '⚠ ' + e.message + ' – Simulation', true); badge(el, 'SIM'); sim(el.querySelector('.out')); }
|
| 86 |
+
finally { clearInterval(tm); go.disabled = false; } }; }; }
|
| 87 |
+
|
| 88 |
+
/* 4 STEMS */
|
| 89 |
+
const SEP = 'abidlabs/music-separation';
|
| 90 |
+
function demoWav() { const sr = 22050, n = sr * 6, b = new ArrayBuffer(44 + n * 2), v = new DataView(b); const w = (o, s) => [...s].forEach((c, i) => v.setUint8(o + i, c.charCodeAt(0)));
|
| 91 |
+
w(0, 'RIFF'); v.setUint32(4, 36 + n * 2, true); w(8, 'WAVEfmt '); v.setUint32(16, 16, true); v.setUint16(20, 1, true); v.setUint16(22, 1, true); v.setUint32(24, sr, true); v.setUint32(28, sr * 2, true); v.setUint16(32, 2, true); v.setUint16(34, 16, true); w(36, 'data'); v.setUint32(40, n * 2, true);
|
| 92 |
+
for (let i = 0; i < n; i++) { const t = i / sr, f = [262, 330, 392, 330][(t * 2 | 0) % 4]; const s = .35 * Math.sin(2 * Math.PI * f * t) * (1 + Math.sin(2 * Math.PI * 5 * t) * .2) + .25 * Math.sin(2 * Math.PI * 55 * t) + (t % .5 < .04 ? (Math.random() - .5) * .6 : 0); v.setInt16(44 + i * 2, Math.max(-1, Math.min(1, s)) * 32000, true); }
|
| 93 |
+
return new Blob([b], { type: 'audio/wav' }); }
|
| 94 |
+
{ const s = S('stems'); s.real = 'API'; s.build = (el) => {
|
| 95 |
+
el.innerHTML = `<div class="row" style="margin:0 0 6px"><span class="badge real">REAL</span><span class="stat">Audio wählen (≤ 30 s empfohlen)</span></div><div class="row"><input type="file" accept="audio/*" aria-label="Audiodatei"><button class="btn alt demo">Demo-Audio</button></div><div class="row"><button class="btn go" disabled>Trennen</button></div><div class="out"></div><div class="credit">powered by ${hf(SEP)} (Demucs)</div>`;
|
| 96 |
+
let file = null; const go = el.querySelector('.go'), fi = el.querySelector('input[type=file]');
|
| 97 |
+
fi.onchange = () => { file = fi.files[0] || null; go.disabled = !file; setS(el, file ? file.name + ' · ' + (file.size / 1e6).toFixed(1) + ' MB' : ''); };
|
| 98 |
+
el.querySelector('.demo').onclick = () => { file = new File([demoWav()], 'studius-demo.wav', { type: 'audio/wav' }); go.disabled = false; setS(el, 'Demo-Audio (6 s) bereit'); };
|
| 99 |
+
go.onclick = async () => { if (!file) return; if (file.size > 25e6) return setS(el, '⚠ Datei > 25 MB', true); go.disabled = true; const tm = timer(el, '.stat'); setS(el, 'Lade hoch…');
|
| 100 |
+
try { const d = await run(SEP, '/inference', { audio: handle_file(file) }, { el, timeout: 240000, onStatus: m => setS(el, stTxt(m)) });
|
| 101 |
+
const names = ['Vocals', 'Instrumental']; const o = el.querySelector('.out'); o.innerHTML = d.map((f, i) => `<div class="row"><b style="width:86px">${names[i] || 'Stem ' + i}</b><a class="btn alt" data-i="${i}">⬇</a></div><audio controls src="${esc(url(f))}"></audio>`).join('');
|
| 102 |
+
o.querySelectorAll('a[data-i]').forEach(a => dl(a, url(d[a.dataset.i]), 'studius-' + names[a.dataset.i].toLowerCase() + '.wav')); window.__stems = d.map(url); setS(el, '✔ ' + d.length + ' Stems'); badge(el, 'REAL');
|
| 103 |
+
} catch (e) { if (!el.isConnected) return; setS(el, '⚠ ' + e.message + ' – Simulation', true); badge(el, 'SIM'); el.querySelector('.out').innerHTML = ['Vocals', 'Drums', 'Bass', 'Other'].map(n => `<div class="row"><span style="width:52px">${n}</span><input type="range" value="80" aria-label="${n} Pegel"></div>`).join(''); }
|
| 104 |
+
finally { clearInterval(tm); go.disabled = false; } }; }; }
|
| 105 |
+
|
| 106 |
+
/* 5 CODE: sandboxed iframe runner + HTML/CSS live preview */
|
| 107 |
+
{ const s = S('code'); s.real = 'LOKAL'; s.build = (el) => {
|
| 108 |
+
el.innerHTML = `<div class="tabs"><button class="btn" data-m="js">JS</button><button class="btn alt" data-m="html">HTML/CSS</button><span class="badge real" style="align-self:center">LOKAL</span></div><textarea rows="6" spellcheck="false" aria-label="Code"></textarea><div class="row"><button class="btn run">▶ Run</button><span class="stat"></span></div><div class="code out" aria-live="polite">// Ausgabe</div><div class="pv"></div><div class="credit">Sandbox: iframe sandbox="allow-scripts" (keine Cookies, kein DOM-Zugriff) · Timeout 3 s</div>`;
|
| 109 |
+
const ta = el.querySelector('textarea'), out = el.querySelector('.out'), pv = el.querySelector('.pv'); keep(el); let mode = 'js', fr = null, deb = 0;
|
| 110 |
+
const SRC = { js: "function swarm(n){\n return Array.from({length:n},(_,i)=>'🐝'+i)\n}\nconsole.log('Hallo Schwarm')\nswarm(5)", html: '<style>\n h1{color:#f2c94c;font-family:sans-serif}\n body{background:#05182e}\n</style>\n<h1>Hallo STUDIUS</h1>\n<button onclick="this.textContent=\'🐝 summt\'">Klick</button>' };
|
| 111 |
+
const kill = () => { fr?.remove(); fr = null; }; onStop(kill); onStop(() => removeEventListener('message', onMsg));
|
| 112 |
+
let tok = '', to = 0; function onMsg(e) { if (!fr || e.source !== fr.contentWindow || e.data?.tok !== tok) return; clearTimeout(to); out.textContent = e.data.out; el.querySelector('.stat').textContent = e.data.ok ? '✔ ' + e.data.ms + ' ms' : '✖ Fehler'; kill(); }
|
| 113 |
+
addEventListener('message', onMsg);
|
| 114 |
+
const runJS = () => { kill(); tok = Math.random().toString(36).slice(2); out.textContent = '…'; fr = document.createElement('iframe'); fr.setAttribute('sandbox', 'allow-scripts'); fr.style.display = 'none'; fr.title = 'JS-Sandbox';
|
| 115 |
+
const code = JSON.stringify(ta.value.replace(/\n([^\n]*)\s*$/, (m, l) => /^\s*(return|const|let|var|function|class|if|for|while|}|\/\/)/.test(l) || !l.trim() ? m : '\nreturn (' + l.replace(/;\s*$/, '') + ')'));
|
| 116 |
+
const wsrc = `const L=[],t=performance.now();console.log=(...a)=>L.push(a.map(x=>typeof x==='string'?x:JSON.stringify(x)).join(' '));let ok=1,r;try{r=(new Function(${code}))();if(r!==undefined)L.push('> '+JSON.stringify(r))}catch(e){ok=0;L.push('✖ '+e.message)}postMessage({ok,out:L.join('\\n')||'(keine Ausgabe)',ms:Math.round(performance.now()-t)})`;
|
| 117 |
+
// user code runs in a Worker inside an opaque-origin sandboxed iframe: own thread (infinite loops can't freeze the 3D view), no DOM, no cookies/storage of this site
|
| 118 |
+
fr.srcdoc = `<script>const w=new Worker(URL.createObjectURL(new Blob([${JSON.stringify(wsrc).replace(/</g, '\\u003c')}],{type:'text/javascript'})));w.onmessage=e=>parent.postMessage(Object.assign({tok:'${tok}'},e.data),'*');w.onerror=e=>{e.preventDefault();parent.postMessage({tok:'${tok}',ok:0,out:'✖ '+e.message,ms:0},'*')}<\/script>`;
|
| 119 |
+
to = setTimeout(() => { if (fr) { kill(); out.textContent = '✖ Timeout (3 s) – Endlosschleife? Sandbox beendet.'; el.querySelector('.stat').textContent = '⏱ abgebrochen'; } }, 3000); onStop(() => clearTimeout(to)); pv.append(fr); };
|
| 120 |
+
const preview = () => { pv.innerHTML = ''; const f = document.createElement('iframe'); f.setAttribute('sandbox', 'allow-scripts'); f.title = 'HTML-Vorschau'; f.srcdoc = ta.value; pv.append(f); out.textContent = '// Live-Vorschau'; };
|
| 121 |
+
const setM = (m) => { mode = m; ta.value = SRC[m]; el.querySelectorAll('[data-m]').forEach(b => b.classList.toggle('alt', b.dataset.m !== m)); pv.innerHTML = ''; el.querySelector('.run').textContent = m === 'js' ? '▶ Run' : '↻ Vorschau'; if (m === 'html') preview(); else out.textContent = '// Ausgabe'; };
|
| 122 |
+
el.querySelectorAll('[data-m]').forEach(b => b.onclick = () => setM(b.dataset.m));
|
| 123 |
+
ta.addEventListener('input', () => { SRC[mode] = ta.value; if (mode === 'html') { clearTimeout(deb); deb = setTimeout(preview, 350); } });
|
| 124 |
+
el.querySelector('.run').onclick = () => mode === 'js' ? runJS() : preview(); setM('js'); }; }
|
| 125 |
+
|
| 126 |
+
/* 6a CANVAS persistence + PNG export */
|
| 127 |
+
const LS = (k, v) => { try { if (v === undefined) return localStorage.getItem(k); localStorage.setItem(k, v); } catch (e) { return null; } };
|
| 128 |
+
function pngBtn(el, c, name) { const a = document.createElement('a'); a.className = 'btn alt'; a.textContent = '⬇ PNG'; a.href = '#'; a.onclick = (e) => { a.href = c.toDataURL('image/png'); a.download = name; }; el.querySelector('.row:last-of-type').append(a); }
|
| 129 |
+
{ const s = S('canvas'); const base = s.build; s.real = 'LOKAL'; s.build = (el) => { base(el); const c = el.querySelector('canvas'), x = c.getContext('2d'); const sv = LS('studius-canvas');
|
| 130 |
+
if (sv) { const im = new Image(); im.onload = () => { x.save(); x.setTransform(1, 0, 0, 1, 0, 0); x.drawImage(im, 0, 0, c.width, c.height); x.restore(); }; im.src = sv; }
|
| 131 |
+
const save = () => LS('studius-canvas', c.toDataURL('image/png')); c.addEventListener('pointerup', save); el.querySelector('.cl').addEventListener('click', save); pngBtn(el, c, 'studius-canvas.png');
|
| 132 |
+
el.insertAdjacentHTML('afterbegin', '<div class="row" style="margin:0 0 6px"><span class="badge real">LOKAL</span><span class="stat">automatisch gespeichert (localStorage)</span></div>'); }; }
|
| 133 |
+
/* 6b DESIGN board persistence + PNG */
|
| 134 |
+
{ const s = S('design'); s.real = 'LOKAL'; s.build = (el) => {
|
| 135 |
+
el.innerHTML = `<div class="row" style="margin:0 0 6px"><span class="badge real">LOKAL</span><span class="stat">Klick = Form · Ziehen = verschieben · gespeichert</span></div><canvas></canvas><div class="row"><button class="btn" data-t="rect" aria-label="Rechteck">▭</button><button class="btn alt" data-t="hex" aria-label="Hexagon">⬡</button><button class="btn alt" data-t="text" aria-label="Text">T</button><button class="btn alt undo">↶</button><button class="btn alt clr">Leeren</button></div>`;
|
| 136 |
+
const [c, x, w, h] = cv(el, 140); let tool = 'rect', drag = null; let shapes; try { shapes = JSON.parse(LS('studius-design')) || null; } catch (e) {} shapes ||= [{ t: 'hex', x: 60, y: 60 }, { t: 'rect', x: 150, y: 50 }, { t: 'text', x: 200, y: 95 }];
|
| 137 |
+
const save = () => LS('studius-design', JSON.stringify(shapes.slice(-300)));
|
| 138 |
+
el.querySelectorAll('[data-t]').forEach(b => b.onclick = () => { tool = b.dataset.t; el.querySelectorAll('[data-t]').forEach(o => o.classList.toggle('alt', o !== b)); });
|
| 139 |
+
el.querySelector('.undo').onclick = () => { shapes.pop(); save(); }; el.querySelector('.clr').onclick = () => { shapes = []; save(); };
|
| 140 |
+
const pos = e => { const r = c.getBoundingClientRect(); return [e.clientX - r.left, e.clientY - r.top]; };
|
| 141 |
+
c.onpointerdown = e => { const [mx, my] = pos(e); drag = [...shapes].reverse().find(s => Math.abs(s.x - mx) < 22 && Math.abs(s.y - my) < 16); if (drag) { c.setPointerCapture(e.pointerId); drag.m = 0; } else { shapes.push({ t: tool, x: mx, y: my }); save(); } };
|
| 142 |
+
c.onpointermove = e => { if (!drag) return; const [mx, my] = pos(e); drag.x = Math.max(0, Math.min(w, mx)); drag.y = Math.max(0, Math.min(h, my)); };
|
| 143 |
+
c.onpointerup = () => { if (drag) { delete drag.m; drag = null; save(); } };
|
| 144 |
+
loop(() => { x.fillStyle = '#0b0b0b'; x.fillRect(0, 0, w, h); x.fillStyle = '#1d1d1d'; for (let i = 0; i < w; i += 12) for (let j = 0; j < h; j += 12) x.fillRect(i, j, 1, 1);
|
| 145 |
+
shapes.forEach(s => { x.strokeStyle = s.t === 'hex' ? '#f2c94c' : '#faa968'; x.lineWidth = 1.5; if (s.t === 'rect') x.strokeRect(s.x - 22, s.y - 14, 44, 28); else if (s.t === 'hex') { x.beginPath(); for (let k = 0; k < 7; k++) { const a = k * Math.PI / 3; x.lineTo(s.x + 20 * Math.cos(a), s.y + 20 * Math.sin(a)); } x.stroke(); } else { x.fillStyle = '#8cbfb8'; x.font = '12px Outfit,sans-serif'; x.fillText('Idee', s.x, s.y); } }); });
|
| 146 |
+
pngBtn(el, c, 'studius-design.png'); }; }
|
| 147 |
+
|
| 148 |
+
/* 7a VIDEO EDIT: local file, real playback, trim in/out preview */
|
| 149 |
+
{ const s = S('videoedit'); const sim = s.build; s.real = 'LOKAL'; s.build = (el) => {
|
| 150 |
+
el.innerHTML = `<div class="row" style="margin:0 0 6px"><span class="badge real">LOKAL</span><span class="stat">Video laden (bleibt lokal im Browser)</span></div><input type="file" accept="video/*" aria-label="Videodatei"><div class="vw"></div><div class="sim"></div>`;
|
| 151 |
+
sim(el.querySelector('.sim')); const fi = el.querySelector('input');
|
| 152 |
+
fi.onchange = () => { const f = fi.files[0]; if (!f) return; const u = URL.createObjectURL(f); onStop(() => URL.revokeObjectURL(u)); el.querySelector('.sim').remove();
|
| 153 |
+
const vw = el.querySelector('.vw'); vw.innerHTML = `<video playsinline muted src="${u}"></video><div class="row">In<input type="range" class="ti" min="0" max="1000" value="0" aria-label="Trim In">Out<input type="range" class="to" min="0" max="1000" value="1000" aria-label="Trim Out"></div><div class="row"><button class="btn pp">▶ Trim-Vorschau</button><span class="tc code" style="padding:2px 6px">00:00.0</span></div>`;
|
| 154 |
+
const v = vw.querySelector('video'), ti = vw.querySelector('.ti'), to = vw.querySelector('.to'); const T = () => [ti.value / 1000 * (v.duration || 0), to.value / 1000 * (v.duration || 0)]; const fmt = s => String(Math.floor(s / 60)).padStart(2, '0') + ':' + (s % 60).toFixed(1).padStart(4, '0');
|
| 155 |
+
const sync = () => { if (+ti.value > +to.value - 10) ti.value = +to.value - 10; const [a, b] = T(); v.currentTime = a; setS(el, `${f.name} · Schnitt ${fmt(a)} – ${fmt(b)} (${(b - a).toFixed(1)} s)`); }; ti.oninput = sync; to.oninput = sync;
|
| 156 |
+
v.onloadedmetadata = () => { sync(); window.__video = { dur: v.duration, w: v.videoWidth, h: v.videoHeight }; };
|
| 157 |
+
v.ontimeupdate = () => { const [a, b] = T(); vw.querySelector('.tc').textContent = fmt(v.currentTime); if (v.currentTime >= b) { v.pause(); v.currentTime = a; vw.querySelector('.pp').textContent = '▶ Trim-Vorschau'; } };
|
| 158 |
+
vw.querySelector('.pp').onclick = (e) => { if (v.paused) { const [a, b] = T(); if (v.currentTime < a || v.currentTime >= b) v.currentTime = a; v.play(); e.target.textContent = '❚❚ Pause'; } else { v.pause(); e.target.textContent = '▶ Trim-Vorschau'; } };
|
| 159 |
+
onStop(() => { v.pause(); v.removeAttribute('src'); v.load(); }); }; }; }
|
| 160 |
+
|
| 161 |
+
/* 7b AUDIO EDIT: local file → real waveform, selection, gain, playback, trimmed WAV export */
|
| 162 |
+
function wav(buf, a, b, g) { const ch = buf.numberOfChannels, sr = buf.sampleRate, s0 = Math.floor(a * sr), n = Math.max(1, Math.floor(b * sr) - s0), out = new DataView(new ArrayBuffer(44 + n * ch * 2)); const w = (o, s) => [...s].forEach((c, i) => out.setUint8(o + i, c.charCodeAt(0)));
|
| 163 |
+
w(0, 'RIFF'); out.setUint32(4, 36 + n * ch * 2, true); w(8, 'WAVEfmt '); out.setUint32(16, 16, true); out.setUint16(20, 1, true); out.setUint16(22, ch, true); out.setUint32(24, sr, true); out.setUint32(28, sr * ch * 2, true); out.setUint16(32, ch * 2, true); out.setUint16(34, 16, true); w(36, 'data'); out.setUint32(40, n * ch * 2, true);
|
| 164 |
+
const d = [...Array(ch)].map((_, c) => buf.getChannelData(c)); for (let i = 0; i < n; i++) for (let c = 0; c < ch; c++) out.setInt16(44 + (i * ch + c) * 2, Math.max(-1, Math.min(1, d[c][s0 + i] * g)) * 32767, true); return new Blob([out], { type: 'audio/wav' }); }
|
| 165 |
+
{ const s = S('audio'); const sim = s.build; s.real = 'LOKAL'; s.build = (el) => {
|
| 166 |
+
el.innerHTML = `<div class="row" style="margin:0 0 6px"><span class="badge real">LOKAL</span><span class="stat">Audio laden · Bereich ziehen = Auswahl</span></div><input type="file" accept="audio/*" aria-label="Audiodatei"><div class="sim"></div>`;
|
| 167 |
+
sim(el.querySelector('.sim')); const fi = el.querySelector('input');
|
| 168 |
+
fi.onchange = async () => { const f = fi.files[0]; if (!f) return; let ac; try { ac = new (window.AudioContext || window.webkitAudioContext)(); onStop(() => ac.close()); const buf = await ac.decodeAudioData(await f.arrayBuffer()); if (!el.isConnected) return;
|
| 169 |
+
const box = el.querySelector('.sim'); box.innerHTML = `<canvas></canvas><div class="row">Gain<input type="range" class="g" min="0" max="200" value="100" aria-label="Gain"><button class="btn alt nm">Normalize</button></div><div class="row"><button class="btn pp">▶ Auswahl abspielen</button><a class="btn alt ex">⬇ WAV-Schnitt</a></div>`;
|
| 170 |
+
const [c, x, w, h] = cv(box, 90); const D = buf.getChannelData(0), N = Math.floor(w), step = Math.max(1, Math.floor(D.length / N)); const pk = [...Array(N)].map((_, i) => { let m = 0; for (let j = i * step; j < (i + 1) * step && j < D.length; j += 4) m = Math.max(m, Math.abs(D[j])); return m; });
|
| 171 |
+
let gain = 1, sel = [0, w], src = null, t0 = 0, off = 0; const gn = ac.createGain(); gn.connect(ac.destination); const T = () => [Math.min(...sel) / w * buf.duration, Math.max(...sel) / w * buf.duration];
|
| 172 |
+
const upd = () => { const [a, b] = T(); setS(el, `${f.name} · ${a.toFixed(2)}–${b.toFixed(2)} s · Gain ${gain.toFixed(2)}`); window.__audioSel = [a, b, gain, buf.duration]; }; upd();
|
| 173 |
+
box.querySelector('.g').oninput = e => { gain = e.target.value / 100; gn.gain.value = gain; upd(); }; box.querySelector('.nm').onclick = () => { gain = 1 / Math.max(.01, ...pk); gn.gain.value = gain; box.querySelector('.g').value = Math.min(200, gain * 100); upd(); };
|
| 174 |
+
c.onpointerdown = e => { const r = c.getBoundingClientRect(); c.setPointerCapture(e.pointerId); sel = [e.clientX - r.left, e.clientX - r.left]; c.onpointermove = m => { sel[1] = Math.max(0, Math.min(w, m.clientX - r.left)); }; c.onpointerup = () => { c.onpointermove = null; if (Math.abs(sel[1] - sel[0]) < 3) sel = [0, w]; upd(); }; };
|
| 175 |
+
const stop = () => { try { src?.stop(); } catch (e) {} src = null; box.querySelector('.pp').textContent = '▶ Auswahl abspielen'; }; onStop(stop);
|
| 176 |
+
box.querySelector('.pp').onclick = async () => { if (src) return stop(); await ac.resume(); const [a, b] = T(); src = ac.createBufferSource(); src.buffer = buf; src.connect(gn); src.start(0, a, b - a); t0 = ac.currentTime; off = a; src.onended = stop; box.querySelector('.pp').textContent = '■ Stop'; };
|
| 177 |
+
const ex = box.querySelector('.ex'); ex.onclick = () => { const [a, b] = T(); if (ex.href) URL.revokeObjectURL(ex.href); ex.href = URL.createObjectURL(wav(buf, a, b, gain)); ex.download = 'studius-trim.wav'; };
|
| 178 |
+
loop(() => { x.fillStyle = '#000'; x.fillRect(0, 0, w, h); x.fillStyle = 'rgba(2,131,145,.35)'; x.fillRect(Math.min(...sel), 0, Math.abs(sel[1] - sel[0]), h); x.strokeStyle = '#f2c94c'; x.beginPath(); for (let i = 0; i < N; i++) { const v = Math.min(1, pk[i] * gain); x.moveTo(i + .5, h / 2 - v * h / 2.1); x.lineTo(i + .5, h / 2 + v * h / 2.1); } x.stroke();
|
| 179 |
+
if (src) { const px = (off + ac.currentTime - t0) / buf.duration * w; x.fillStyle = '#f85525'; x.fillRect(px, 0, 1.5, h); } });
|
| 180 |
+
} catch (e) { setS(el, '⚠ Audio nicht lesbar: ' + e.message, true); } }; }; }
|
| 181 |
+
export const REAL = STUDIOS.filter(s => s.real).map(s => [s.id, s.real]);
|
style.css
CHANGED
|
@@ -126,7 +126,7 @@ body::before{content:"";position:fixed;inset:0;pointer-events:none;z-index:1;bac
|
|
| 126 |
#pop .btn.alt{background:transparent;color:var(--gold);border:1px solid var(--line2)}
|
| 127 |
#pop .btn.alt:hover{background:rgba(242,201,76,.1)}
|
| 128 |
#pop canvas{width:100%;display:block;background:#000;border:1px solid rgba(242,201,76,.2);touch-action:none}
|
| 129 |
-
.chat{height:120px;overflow:auto;background:rgba(0,0,0,.55);border:1px solid rgba(242,201,76,.2);padding:8px;margin-bottom:6px}
|
| 130 |
.chat p{margin:0 0 6px;line-height:1.45}.chat .u{color:var(--r-acc)}.chat .a{color:var(--txt)}
|
| 131 |
.prog{height:4px;background:rgba(255,255,255,.06)}.prog i{display:block;height:100%;width:0;background:linear-gradient(90deg,var(--gold2),var(--gold));box-shadow:0 0 8px var(--gold);transition:width .2s}
|
| 132 |
.track{position:relative;height:18px;background:#000;border:1px solid #222;margin-top:3px}
|
|
@@ -168,3 +168,16 @@ kbd{font:inherit;font-size:9px;color:var(--gold);border:1px solid var(--line);pa
|
|
| 168 |
#nodeTip{position:fixed;left:0;top:0;z-index:13;pointer-events:none;padding:6px 10px;border-radius:8px;background:rgba(20,16,6,.85);backdrop-filter:blur(8px);
|
| 169 |
box-shadow:inset 0 0 0 1px rgba(242,201,76,.45);font-size:11px;color:var(--txt);opacity:0;transform:translateX(-8px);transition:opacity .25s,transform .4s var(--ease);white-space:nowrap}
|
| 170 |
#nodeTip.on{opacity:1}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 126 |
#pop .btn.alt{background:transparent;color:var(--gold);border:1px solid var(--line2)}
|
| 127 |
#pop .btn.alt:hover{background:rgba(242,201,76,.1)}
|
| 128 |
#pop canvas{width:100%;display:block;background:#000;border:1px solid rgba(242,201,76,.2);touch-action:none}
|
| 129 |
+
.chat{height:auto;min-height:120px;overflow:auto;background:rgba(0,0,0,.55);border:1px solid rgba(242,201,76,.2);padding:8px;margin-bottom:6px}
|
| 130 |
.chat p{margin:0 0 6px;line-height:1.45}.chat .u{color:var(--r-acc)}.chat .a{color:var(--txt)}
|
| 131 |
.prog{height:4px;background:rgba(255,255,255,.06)}.prog i{display:block;height:100%;width:0;background:linear-gradient(90deg,var(--gold2),var(--gold));box-shadow:0 0 8px var(--gold);transition:width .2s}
|
| 132 |
.track{position:relative;height:18px;background:#000;border:1px solid #222;margin-top:3px}
|
|
|
|
| 168 |
#nodeTip{position:fixed;left:0;top:0;z-index:13;pointer-events:none;padding:6px 10px;border-radius:8px;background:rgba(20,16,6,.85);backdrop-filter:blur(8px);
|
| 169 |
box-shadow:inset 0 0 0 1px rgba(242,201,76,.45);font-size:11px;color:var(--txt);opacity:0;transform:translateX(-8px);transition:opacity .25s,transform .4s var(--ease);white-space:nowrap}
|
| 170 |
#nodeTip.on{opacity:1}
|
| 171 |
+
/* f1: a11y + real badges */
|
| 172 |
+
.lbl:focus-visible,#pop button:focus-visible,#pop .btn:focus-visible,#hud button:focus-visible,#bmc:focus-visible{outline:2px solid #fff;outline-offset:2px;box-shadow:0 0 0 4px rgba(242,201,76,.55)}
|
| 173 |
+
#pop .pf span.real{color:#7bd84f}
|
| 174 |
+
#pop .badge{display:inline-block;font:700 9px/1 Outfit,sans-serif;letter-spacing:.12em;padding:3px 6px;border-radius:4px;margin-left:6px;vertical-align:middle}
|
| 175 |
+
#pop .badge.real{background:#7bd84f;color:#000}#pop .badge.sim{background:rgba(255,255,255,.14);color:#f6dcac}
|
| 176 |
+
#pop .credit{font-size:9.5px;color:var(--mut);margin-top:6px}#pop .credit a{color:var(--r-cy)}
|
| 177 |
+
#pop .stat{font-size:10.5px;color:var(--r-cy);min-height:14px}#pop .stat.err{color:#f85525}
|
| 178 |
+
#pop .tabs{display:flex;gap:4px;margin-bottom:8px}#pop .tabs button{flex:1}
|
| 179 |
+
#pop audio,#pop video{width:100%;margin-top:6px;display:block}
|
| 180 |
+
#pop .gen img{width:100%;display:block;border:1px solid rgba(242,201,76,.2);margin-top:6px}
|
| 181 |
+
#pop iframe{width:100%;height:150px;border:1px solid rgba(242,201,76,.2);background:#fff;margin-top:6px}
|
| 182 |
+
#pop .chat{max-height:200px;overflow:auto}
|
| 183 |
+
#pop a.btn{text-decoration:none;display:inline-block}
|
vendor/gradio-client.js
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
var ze=Object.defineProperty;var Re=e=>{throw TypeError(e)};var Rt=(e,t,n)=>t in e?ze(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var Be=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(r){throw n=[r],r}};var Bt=(e,t)=>{for(var n in t)ze(e,n,{get:t[n],enumerable:!0})};var l=(e,t,n)=>Rt(e,typeof t!="symbol"?t+"":t,n),Fe=(e,t,n)=>t.has(e)||Re("Cannot "+n);var F=(e,t,n)=>(Fe(e,t,"read from private field"),n?n.call(e):t.get(e)),Je=(e,t,n)=>t.has(e)?Re("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),Me=(e,t,n,r)=>(Fe(e,t,"write to private field"),r?r.call(e,n):t.set(e,n),n);var pe={};Bt(pe,{default:()=>Jt});var Ft,Jt,de=Be(()=>{he();Ft=Ge(((e,t)=>{t.exports={}})),Jt=Ft()});async function mn(e,t,n){try{return(await(await fetch(`https://huggingface.co/api/spaces/${e}/jwt`,{headers:{Authorization:`Bearer ${t}`,...n?{Cookie:n}:{}}})).json()).token||!1}catch{return!1}}function mt(e){e.hf_token&&!e.token&&(e.token=e.hf_token,console.warn("The `hf_token` option has been renamed to `token`. Support for `hf_token` will be removed in a future version of @gradio/client."))}function Ke(e){let t={};return e.forEach(({api_name:n,id:r})=>{n&&(t[n]=r)}),t}function wn(e,t,n=!1){let r=new URL(t),i=new URL(e,r),s=i.hostname.endsWith(".colab-user-runtimes.internal")||i.hostname.endsWith(".codatalab-user-runtimes.internal");return n||s?new URL(new URL(e,r).pathname,r).toString().replace(/\/$/,""):i.hostname===r.hostname?(i.protocol=r.protocol,i.host=r.host,i.toString().replace(/\/$/,"")):e}async function yn(e,t=!0){let n=this.options.token?{Authorization:`Bearer ${this.options.token}`}:{};if(typeof window<"u"&&window.gradio_config&&location.origin!=="http://localhost:9876"){if(t&&window.gradio_config.current_page&&(e=e.substring(0,e.lastIndexOf("/"))),window.gradio_config.dev_mode||typeof window<"u"&&window?.BUILD_MODE==="dev"){let i=new URL(_e(e,Ze));this.deep_link&&i.searchParams.set("deep_link",this.deep_link),this.page!==null&&i.searchParams.set("page",this.page);let s=await Ve(await this.fetch(i,{headers:n,credentials:this.options.credentials??"same-origin"}),!!this.options.auth);s.root=e||s.root,window.gradio_config={...s,current_page:window.gradio_config.current_page}}let r={...window.gradio_config};return r.root=wn(r.root,location.href,r.is_colab),r}else if(e){let r=new URL(_e(e,Ze));this.deep_link&&r.searchParams.set("deep_link",this.deep_link),this.page!==null&&r.searchParams.set("page",this.page);let i=await Ve(await this.fetch(r,{headers:n,credentials:this.options.credentials??"same-origin"}),!!this.options.auth);return i.root||(i.root=e),i}throw Error(T)}async function Ve(e,t){if(e?.status===401&&!t){let n=null;try{n=await e.json()}catch{throw Error(pn)}let r=n?.detail?.auth_message;throw Error(r||"Login credentials are required to access this space.")}else if(e?.status===401&&t)throw Error(gt);if(e?.status===200){let n=await e.json();return n.dependencies?.forEach((r,i)=>{r.id===void 0&&(r.id=i)}),n}else if(e?.status===401)throw Error(ln);throw Error(`${T}(received status ${e?.status} when fetching the app config)`)}async function bn(){let{http_protocol:e,host:t}=await be(this.app_reference,this.options.token);try{if(this.options.auth){let n=await wt(e,t,this.options.auth,this.fetch,this.options.token,this.options.credentials);n&&this.set_cookies(n)}}catch(n){throw Error(n.message)}}async function wt(e,t,n,r,i,s){let a=new FormData;a.append("username",n?.[0]),a.append("password",n?.[1]);let o={};i&&(o.Authorization=`Bearer ${i}`);let u=await r(`${e}//${t}/${Qt}`,{headers:o,method:"POST",body:a,credentials:s??"same-origin"});if(u.status===200)return u.headers.get("set-cookie");throw u.status===401?Error(gt):Error(Y)}function fe(e){if(e.startsWith("http")){let{protocol:t,host:n,pathname:r}=new URL(e);return{ws_protocol:t==="https:"?"wss":"ws",http_protocol:t,host:n+(r==="/"?"":r)}}return{ws_protocol:"wss",http_protocol:"https:",host:new URL(e).host}}async function be(e,t){let n={};t&&(n.Authorization=`Bearer ${t}`);let r=e.trim().replace(/\/$/,"");if(ye.test(r)){let i;try{i=await fetch(`https://huggingface.co/api/spaces/${r}/${Kt}`,{headers:n})}catch{throw Error(Y)}if(i.status===401||i.status===404)throw Error(dn(r,i.status));let s;try{s=(await i.json()).host}catch{throw Error(Y)}if(!s)throw Error(Y);return{space_id:r,...fe(s)}}if(vn.test(r)){let{ws_protocol:i,http_protocol:s,host:a}=fe(r);return{space_id:a.split("/")[0].replace(".hf.space",""),ws_protocol:i,http_protocol:s,host:a}}return{space_id:!1,...fe(r)}}function $n(e,t,n){let r={named_endpoints:{},unnamed_endpoints:{}};return Object.keys(e).forEach(i=>{(i==="named_endpoints"||i==="unnamed_endpoints")&&(r[i]={},Object.entries(e[i]).forEach(([s,a])=>{let o=a?.parameters??[],u=a?.returns??[],c=t.dependencies.find(g=>g.api_name===s||g.api_name===s.replace("/",""))?.id||n[s.replace("/","")]||-1,p=c===-1?void 0:t.dependencies.find(g=>g.id==c),h=c===-1?{generator:!1,cancel:!1}:p?.types;if(p&&Array.isArray(p.inputs)&&p.inputs.length!==o.length){let g=p.inputs.map(k=>t.components.find(m=>m.id===k)?.type);try{g.forEach((k,m)=>{k==="state"&&o.splice(m,0,{component:"state",example:null,parameter_default:null,parameter_has_default:!0,parameter_name:null,hidden:!0})})}catch(k){console.error(k)}}let w=(g,k,m,z)=>({...g,description:Sn(g?.type,m),type:kn(g?.type,k,m,z)||""});r[i][s]={parameters:o.map(g=>w(g,g?.component,g?.serializer,"parameter")),returns:u.map(g=>w(g,g?.component,g?.serializer,"return")),type:h,...a?.oauth_token?{oauth_token:a.oauth_token}:{}}}))}),r}function kn(e,t,n,r){if(t==="Api")return e.type;switch(e?.type){case"string":return"string";case"boolean":return"boolean";case"number":return"number"}if(n==="JSONSerializable"||n==="StringSerializable")return"any";if(n==="ListStringSerializable")return"string[]";if(t==="Image")return r==="parameter"?"Blob | File | Buffer":"string";if(n==="FileSerializable")return e?.type==="array"?r==="parameter"?"(Blob | File | Buffer)[]":"{ name: string; data: string; size?: number; is_file?: boolean; orig_name?: string}[]":r==="parameter"?"Blob | File | Buffer":"{ name: string; data: string; size?: number; is_file?: boolean; orig_name?: string}";if(n==="GallerySerializable")return r==="parameter"?"[(Blob | File | Buffer), (string | null)][]":"[{ name: string; data: string; size?: number; is_file?: boolean; orig_name?: string}, (string | null))][]"}function Sn(e,t){return t==="GallerySerializable"?"array of [file, label] tuples":t==="ListStringSerializable"?"array of strings":t==="FileSerializable"?"array of files or single file":e?.description}function Qe(e,t){switch(e.msg){case"send_data":return{type:"data"};case"send_hash":return{type:"hash"};case"queue_full":return{type:"update",status:{queue:!0,message:ft,stage:"error",code:e.code,success:e.success}};case"heartbeat":return{type:"heartbeat"};case"unexpected_error":return{type:"unexpected_error",status:{queue:!0,message:e.message,session_not_found:e.session_not_found,stage:"error",success:!1}};case"broken_connection":return{type:"broken_connection",status:{queue:!0,message:e.message,stage:"error",success:!1}};case"estimation":return{type:"update",status:{queue:!0,stage:t||"pending",code:e.code,size:e.queue_size,position:e.rank,eta:e.rank_eta,success:e.success}};case"progress":return{type:"update",status:{queue:!0,stage:"pending",code:e.code,progress_data:e.progress_data,success:e.success}};case"log":return{type:"log",data:e};case"process_generating":return{type:"generating",status:{queue:!0,message:e.success?null:e.output.error,stage:e.success?"generating":"error",code:e.code,progress_data:e.progress_data,eta:e.average_duration,changed_state_ids:e.success?e.output.changed_state_ids:void 0},data:e.success?e.output:null};case"process_streaming":return{type:"streaming",status:{queue:!0,message:e.output.error,stage:"streaming",time_limit:e.time_limit,code:e.code,progress_data:e.progress_data,changed_state_ids:e.output.changed_state_ids,eta:e.eta},data:e.output};case"process_completed":return"error"in e.output?{type:"update",status:{queue:!0,title:e.output.title??"Error",message:e.output.error??"An error occurred",visible:e.output.visible,duration:e.output.duration,stage:"error",code:e.code,success:e.success}}:{type:"complete",status:{queue:!0,message:e.success?void 0:e.output.error,stage:e.success?"complete":"error",code:e.code,progress_data:e.progress_data,changed_state_ids:e.success?e.output.changed_state_ids:void 0,used_cache:e.used_cache,cache_duration:e.cache_duration,avg_time:e.avg_time},data:e.success?e.output:null};case"process_starts":return{type:"update",status:{queue:!0,stage:"pending",code:e.code,size:e.rank,position:0,success:e.success,eta:e.eta},original_msg:"process_starts"}}return{type:"none",status:{stage:"error",queue:!0}}}async function xn(){if(this.api_info)return this.api_info;let{token:e}=this.options,{config:t}=this,n={};if(e&&(n.Authorization=`Bearer ${e}`),t)try{let r,i;if(typeof window<"u"&&window.gradio_api_info)i=window.gradio_api_info;else{let s=new URL(_e(t.root,this.api_prefix,Xt));if(this.page!==null&&s.searchParams.set("page",this.page),r=await this.fetch(s,{headers:n,credentials:this.options.credentials??"same-origin"}),!r.ok)throw Error(q);i=await r.json()}return"api"in i&&(i=i.api),i.named_endpoints["/predict"]&&!i.unnamed_endpoints[0]&&(i.unnamed_endpoints[0]=i.named_endpoints["/predict"]),$n(i,t,this.api_map)}catch(r){throw Error("Could not get API info. "+r.message)}}async function On(e,t,n){let r={};this?.options?.token&&(r.Authorization=`Bearer ${this.options.token}`);let i=1e3,s=[],a;for(let o=0;o<t.length;o+=i){let u=t.slice(o,o+i),c=new FormData;u.forEach(h=>{c.append("files",h)});try{let h=n?`${e}${this.api_prefix}/${He}?upload_id=${n}`:`${e}${this.api_prefix}/${He}`;a=await this.fetch(h,{method:"POST",body:c,headers:r,credentials:this.options.credentials??"same-origin"})}catch(h){throw Error(q+h.message)}if(!a.ok){let h=await a.text();return{error:`HTTP ${a.status}: ${h}`}}let p=await a.json();p&&s.push(...p)}return{files:s}}function jn(e,t=1,n="jedec"){e=Math.abs(e);let{radix:r,unit:i}=Xe[n]||Xe.jedec,s=0;for(;e>=r;)e/=r,++s;return`${e.toFixed(t)} ${i[s]}`}async function An(e,t,n,r){let i=(Array.isArray(e)?e:[e]).map(a=>a.blob),s=i.filter(a=>a.size>(r??1/0));if(s.length)throw Error(`File(s) exceed the maximum allowed size of ${jn(r||1/0)}: ${s.map(a=>`"${a.name}"`).join(", ")}`);return await Promise.all(await this.upload_files(t,i,n).then(async a=>{if(a.error)throw Error(a.error);return a.files?a.files.map((o,u)=>{let c=o.split("/").map(p=>encodeURIComponent(p)).join("/");return new ve({...e[u],path:o,url:`${t}${this.api_prefix}/file=${c}`})}):[]}))}function et(e,t,n){for(;n.length>1;){let i=n.shift();if(typeof i=="string"||typeof i=="number")e=e[i];else throw Error("Invalid key type")}let r=n.shift();if(typeof r=="string"||typeof r=="number")e[r]=t;else throw Error("Invalid key type")}async function me(e,t=void 0,n=[],r=!1,i=void 0){if(Array.isArray(e)){let s=[];return await Promise.all(e.map(async(a,o)=>{let u=n.slice();u.push(String(o));let c=await me(e[o],r?i?.parameters[o]?.component||void 0:t,u,!1,i);s=s.concat(c)})),s}else{if(globalThis.Buffer&&e instanceof globalThis.Buffer||e instanceof Blob)return[{path:n,blob:e instanceof Blob?e:new Blob([e]),type:t}];if(typeof e=="object"&&e){let s=[];for(let a of Object.keys(e)){let o=[...n,a],u=e[a];s=s.concat(await me(u,void 0,o,!1,i))}return s}}return[]}function tt(e,t){let n=t?.dependencies?.find(r=>r.id==e)?.queue;return n==null?!t.enable_queue:!n}function Pn(e,t){return new Promise((n,r)=>{let i=new MessageChannel;i.port1.onmessage=(({data:s})=>{i.port1.close(),n(s)}),window.parent.postMessage(e,t,[i.port2])})}function In(e){if(typeof e=="string"){if(e.startsWith("http://")||e.startsWith("https://"))return{path:e,url:e,orig_name:e.split("/").pop()??"unknown",meta:{_type:"gradio.FileData"}};if(Dn)return new bt("upload_file",{path:e,name:e,orig_path:e})}else{if(typeof File<"u"&&e instanceof File)return e;if(globalThis.Buffer&&e instanceof globalThis.Buffer)return new Blob([e]);if(e instanceof Blob)return e}throw Error("Invalid input: must be a URL, File, Blob, or Buffer object.")}function H(e,t,n,r,i=!1){if(r==="input"&&!i)throw Error("Invalid code path. Cannot skip state inputs for input.");if(r==="output"&&i)return e;let s=[],a=0,o=r==="input"?t.inputs:t.outputs;for(let u=0;u<o.length;u++){let c=o[u];if(n.find(p=>p.id===c)?.type==="state"){if(i)if(e.length===o.length){let p=e[a];s.push(p),a++}else s.push(null);else{a++;continue}continue}else{let p=e[a];s.push(p),a++}}return s}function $e(e,t,n,r){if(!r||typeof e!="object"||!e)return;let i=r,s=new URL(t),a=s.pathname.replace(/\/+$/,""),o=n?`/${n.replace(/^\/+|\/+$/g,"")}`:"",u=new Set([`${a}${o}`,o]);o||(u.add(`${a}/gradio_api`),u.add("/gradio_api"));function c(p){if(typeof p!="object"||!p)return;let h=p;if(h.meta?._type==="gradio.FileData"&&typeof h.url=="string"){let w=new URL(h.url,`${s.toString().replace(/\/$/,"")}/`),g=[...u].some(k=>Tn.some(m=>w.pathname.startsWith(`${k}${m}`)));(w.protocol==="http:"||w.protocol==="https:")&&w.origin===s.origin&&g&&(w.searchParams.set("__sign",i),h.url=w.toString())}for(let w of Object.values(h))c(w)}c(e)}function nt(e,t){for(let n of e.components||[])$e(n.props?.value,e.root,e.api_prefix||"",t)}async function Cn(e,t,n){let r=this;await Nn(r,t);let i=await me(t,void 0,[],!0,n);return(await Promise.all(i.map(async({path:s,blob:a,type:o})=>{if(!a)return{path:s,type:o};let u=await r.upload_files(e,[a]);return{path:s,file_url:u.files&&u.files[0],type:o,name:typeof File<"u"&&a instanceof File?a?.name:void 0}}))).forEach(({path:s,file_url:a,type:o,name:u})=>{o==="Gallery"?et(t,a,s):a&&et(t,new ve({path:a,orig_name:u}),s)}),t}async function Nn(e,t){if(!(e.config?.root||e.config?.root_url))throw Error(_t);await vt(e,t)}async function vt(e,t,n=[]){for(let r in t)t[r]instanceof bt?await Un(e,t,r):typeof t[r]=="object"&&t[r]!==null&&await vt(e,t[r],[...n,r])}async function Un(e,t,n){let r=t[n],i=e.config?.root||e.config?.root_url;if(!i)throw Error(_t);try{let s,a;if(typeof process<"u"&&process.versions&&process.versions.node){let p=await Promise.resolve().then(()=>(de(),pe)).then(h=>We(h.default,1));a=(await Promise.resolve().then(()=>(de(),pe)).then(h=>We(h.default,1))).resolve(process.cwd(),r.meta.path),s=await p.readFile(a)}else throw Error(gn);let o=new Blob([s],{type:"application/octet-stream"}),u=await e.upload_files(i,[o]),c=u.files&&u.files[0];c&&(t[n]=new ve({path:c,orig_name:r.meta.name||""}))}catch(s){console.error(_n,s)}}async function Ln(e,t,n){let r={"Content-Type":"application/json"};this.options.token&&(r.Authorization=`Bearer ${this.options.token}`);try{var i=await this.fetch(e,{method:"POST",body:JSON.stringify(t),headers:{...r,...n},credentials:this.options.credentials??"same-origin"})}catch{return[{error:q},500]}let s,a;try{s=await i.json(),a=i.status}catch(o){s={error:`Could not parse server response: ${o}`},a=500}return[s,a]}async function qn(e,t={}){let n=!1,r=!1;if(!this.config)throw Error("Could not resolve app config");if(typeof e=="number")this.config.dependencies.find(a=>a.id==e);else{let a=e.replace(/^\//,"");this.config.dependencies.find(o=>o.id==this.api_map[a])}let i=this.submit(e,t,null,null,!0),s;for await(let a of i){if(a.type==="data"&&(n=!0,s=a,r))return s;if(a.type==="status"){if(a.stage==="error"){let{message:o,...u}=a,c=Error((typeof o=="string"?o:o&&JSON.stringify(o))||"An unknown error occurred while making a prediction.");throw Object.assign(c,u),c}if(a.stage==="complete"&&(r=!0,n))return s}}return s}async function K(e,t,n){let r=t==="subdomain"?`https://huggingface.co/api/spaces/by-subdomain/${e}`:`https://huggingface.co/api/spaces/${e}`,i,s;try{if(i=await fetch(r),s=i.status,s!==200)throw Error();i=await i.json()}catch{n({status:"error",load_status:"error",message:cn,detail:"NOT_FOUND"});return}if(!i||s!==200)return;let{runtime:{stage:a},id:o}=i;switch(a){case"STOPPED":case"SLEEPING":n({status:"sleeping",load_status:"pending",message:"Space is asleep. Waking it up...",detail:a}),setTimeout(()=>{K(e,t,n)},1e3);break;case"PAUSED":n({status:"paused",load_status:"error",message:"This space has been paused by the author. If you would like to try this demo, consider duplicating the space.",detail:a,discussions_enabled:await rt(o)});break;case"RUNNING":case"RUNNING_BUILDING":n({status:"running",load_status:"complete",message:"Space is running.",detail:a});break;case"BUILDING":n({status:"building",load_status:"pending",message:"Space is building...",detail:a}),setTimeout(()=>{K(e,t,n)},1e3);break;case"APP_STARTING":n({status:"starting",load_status:"pending",message:"Space is starting...",detail:a}),setTimeout(()=>{K(e,t,n)},1e3);break;default:n({status:"space_error",load_status:"error",message:"This space is experiencing an issue.",detail:a,discussions_enabled:await rt(o)});break}}async function rt(e){try{let t=await fetch(`https://huggingface.co/api/spaces/${e}/discussions`,{method:"HEAD"}),n=t.headers.get("x-error-message");return!(!t.ok||n&&zn.test(n))}catch{return!1}}async function Rn(e,t){let n={};t&&(n.Authorization=`Bearer ${t}`);try{let r=await fetch(`https://huggingface.co/api/spaces/${e}/${en}`,{headers:n});if(r.status!==200)throw Error("Space hardware could not be obtained.");let{hardware:i}=await r.json();return i.current}catch(r){throw Error(r.message)}}async function Bn(e,t,n){let r={};n&&(r.Authorization=`Bearer ${n}`);let i={seconds:t};try{let s=await fetch(`https://huggingface.co/api/spaces/${e}/${tn}`,{method:"POST",headers:{"Content-Type":"application/json",...r},body:JSON.stringify(i)});if(s.status!==200)throw Error("Could not set sleep timeout on duplicated Space. Please visit *ADD HF LINK TO SETTINGS* to set a timeout manually to reduce billing charges.");return await s.json()}catch(s){throw Error(s.message)}}async function Fn(e,t){mt(t);let{token:n,private:r,hardware:i,timeout:s,auth:a}=t;if(i&&!it.includes(i))throw Error(`Invalid hardware type provided. Valid types are: ${it.map(m=>`"${m}"`).join(",")}.`);let{http_protocol:o,host:u}=await be(e,n),c=null;if(a){let m=await wt(o,u,a,fetch,void 0,t.credentials);m&&(c=yt(m))}let p={Authorization:`Bearer ${n}`,"Content-Type":"application/json",...c?{Cookie:c.join("; ")}:{}},h=(await(await fetch("https://huggingface.co/api/whoami-v2",{headers:p})).json()).name,w=e.split("/")[1],g={repository:`${h}/${w}`};r&&(g.private=!0);let k;try{i||(k=await Rn(e,n))}catch(m){throw Error(Y+m.message)}g.hardware=i||k||"cpu-basic";try{let m=await fetch(`https://huggingface.co/api/spaces/${e}/duplicate`,{method:"POST",headers:p,body:JSON.stringify(g)});if(m.status===409)try{return await we.connect(`${h}/${w}`,t)}catch(te){throw console.error("Failed to connect Client instance:",te),te}else if(m.status!==200)throw Error(m.statusText);let z=await m.json();return await Bn(`${h}/${w}`,s||300,n),await we.connect(Jn(z.url),t)}catch(m){throw Error(m)}}function Jn(e){let t=e.match(/https:\/\/huggingface.co\/spaces\/([^/]+\/[^/]+)/);if(t)return t[1]}function Mn(){return typeof window<"u"&&typeof document<"u"&&typeof window.addEventListener=="function"}function kt(e){return e.includes(".dev.")?`https://moon-${e.split(".")[1]}.dev.spaces.huggingface.tech`:e.endsWith(".hf.space")?"https://huggingface.co":null}function Gn(){if(!Mn()||at)return;window.addEventListener("message",t=>{t.data===st&&(window.supports_zerogpu_headers=!0)}),at=!0;let e=kt(window.location.hostname);e&&window.parent!==window&&window.parent.postMessage(st,e)}function Hn(e){let t=new TextDecoderStream,n=new Wn({allowCR:!0});return e.pipeThrough(t).pipeThrough(n)}function Zn(e){let t=/[:]\s*/.exec(e),n=t&&t.index;if(n)return[e.substring(0,n),e.substring(n+t[0].length)]}function ot(e,t,n){e.get(t)||e.set(t,n)}async function*Yn(e,t){if(!e.body)return;let n=Hn(e.body),r,i=n.getReader(),s;for(;;){if(t&&t.aborted)return i.cancel();if(r=await i.read(),r.done)return;if(!r.value){s&&(yield s),s=void 0;continue}let[a,o]=Zn(r.value)||[];a==="data"?(s||(s={}),s[a]=s[a]?s[a]+`
|
| 2 |
+
`+o:o):a==="event"?(s||(s={}),s[a]=o):a==="id"?(s||(s={}),s[a]=String(+o)===o?+o:o):a==="retry"&&(s||(s={}),s[a]=+o||void 0)}}async function Kn(e,t){let n=new Request(e,t);ot(n.headers,"Accept","text/event-stream"),ot(n.headers,"Content-Type","application/json");let r=await fetch(n);if(!r.ok)throw r;return Yn(r,n.signal)}async function Vn(){let{event_callbacks:e,unclosed_events:t,pending_stream_messages:n,stream_status:r,config:i,jwt:s}=this,a=this;if(!i)throw Error("Could not resolve app config");r.open=!0;let o=null,u=new URLSearchParams({session_hash:this.session_hash}).toString(),c=new URL(`${i.root}${this.api_prefix}/${ht}?${u}`);if(s&&c.searchParams.set("__sign",s),o=this.stream(c),!o){console.warn("Cannot connect to SSE endpoint: "+c.toString());return}o.onmessage=async function(p){let h=JSON.parse(p.data);if(h.msg==="close_stream"){ke(r,a.abort_controller);return}let w=h.event_id;if(!w)await Promise.all(Object.keys(e).map(g=>e[g](h)));else if(e[w]&&i){h.msg==="process_completed"&&["sse","sse_v1","sse_v2","sse_v2.1","sse_v3"].includes(i.protocol)&&t.delete(w);let g=e[w];typeof window<"u"&&typeof document<"u"&&document.visibilityState!=="hidden"?setTimeout(g,0,h):g(h)}else n[w]||(n[w]=[]),n[w].push(h)},o.onerror=async function(p){console.error(p),await Promise.all(Object.keys(e).map(h=>e[h]({msg:"broken_connection",message:q})))}}function ke(e,t){e&&(e.open=!1,t?.abort())}function Qn(e,t,n){e[t]?n.data.forEach((r,i)=>{let s=Xn(i<e[t].length?e[t][i]:null,r);e[t][i]=s,n.data[i]=s}):(e[t]=[],n.data.forEach((r,i)=>{e[t][i]=r}))}function Xn(e,t){return t.forEach(([n,r,i])=>{e=er(e,r,n,i)}),e}function er(e,t,n,r){if(t.length===0){if(n==="replace")return r;if(n==="append")return e+r;throw Error(`Unsupported action: ${n}`)}let i=e;for(let a=0;a<t.length-1;a++)i=i[t[a]];let s=t[t.length-1];switch(n){case"replace":i[s]=r;break;case"append":i[s]+=r;break;case"add":Array.isArray(i)?i.splice(Number(s),0,r):i[s]=r;break;case"delete":Array.isArray(i)?i.splice(Number(s),1):delete i[s];break;default:throw Error(`Unknown action: ${n}`)}return e}function tr(e,t={}){let n={close:()=>{console.warn("Method not implemented.")},onerror:null,onmessage:null,onopen:null,readyState:0,url:e.toString(),withCredentials:!1,CONNECTING:0,OPEN:1,CLOSED:2,addEventListener:()=>{throw Error("Method not implemented.")},dispatchEvent:()=>{throw Error("Method not implemented.")},removeEventListener:()=>{throw Error("Method not implemented.")}};return Kn(e,t).then(async r=>{n.readyState=n.OPEN;try{for await(let i of r)n.onmessage&&n.onmessage(i);n.readyState=n.CLOSED}catch(i){n.onerror&&n.onerror(i),n.readyState=n.CLOSED}}).catch(r=>{console.error(r),n.onerror&&n.onerror(r),n.readyState=n.CLOSED}),n}function X(e,t){try{return e()}catch(n){return console.warn("Could not update the run history.",n),t}}function ee(e){if(typeof window>"u")return null;let t=e?.app_id;if(t==null||t==="")return null;try{return window.localStorage?`${V}${t}${e?.username?`:user:${encodeURIComponent(e.username)}`:""}`:null}catch{return null}}function ir(e){let t=ee(e);return t?t.replace(V,St):null}function Et(e){let t=ir(e);if(!t)return{type:"browser"};try{let n=JSON.parse(window.localStorage.getItem(t)||"null");return typeof n?.bucket_id=="string"?n.type==="bucket"?{type:"bucket",bucket_id:n.bucket_id}:{type:"browser",bucket_id:n.bucket_id}:{type:"browser"}}catch{return{type:"browser"}}}function ut(e){try{let t=JSON.parse(window.localStorage.getItem(e)||"[]");return Array.isArray(t)&&t.length&&Date.parse(t[0]?.started_at)||0}catch{return 0}}function xt(e){let t=Object.keys(window.localStorage).filter(r=>r.startsWith(se)),n=[...t.filter(r=>!r.startsWith(V)&&!r.startsWith(ct)&&!r.startsWith(St)),...t.filter(r=>r.startsWith(V)&&r!==e).sort((r,i)=>ut(i)-ut(r)).slice(rr-1)];for(let r of n)try{window.localStorage.removeItem(r),window.sessionStorage.removeItem(r.replace(V,ct))}catch{}}function sr(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2)}`}function Q(e){let t=new WeakSet;try{return JSON.parse(JSON.stringify(e,(n,r)=>{if(typeof r=="bigint")return r.toString();if(typeof r=="object"&&r){if(t.has(r))return"[Circular]";t.add(r)}return r}))}catch{return"[Unserializable value]"}}function Se(e){let t=ee(e);if(!t)return[];try{let n=JSON.parse(window.localStorage.getItem(t)||"[]");return Array.isArray(n)?n:[]}catch{return[]}}function Ee(e,t){let n=ee(e);if(!n)return;let r=t.slice(0,nr),i=!1;for(;r.length>0;)try{window.localStorage.setItem(n,JSON.stringify(r));return}catch{if(!i){i=!0,xt(n);continue}r=r.slice(0,-1)}try{window.localStorage.removeItem(n)}catch{}}function ar(e){let t=ee(e);if(t){try{window.localStorage.removeItem(t)}catch{}Ot()}}function Ot(){if(!(typeof window>"u"))try{window.dispatchEvent(new Event(or))}catch{}}function cr(e){if(Et(e).type==="bucket")return null;let t=ee(e);if(!t)return null;xt(t);let n={id:sr(),endpoint:e.endpoint,api_name:e.api_name,fn_index:e.fn_index,page:`${window.location.pathname}${window.location.search}`,inputs:Q(e.inputs),outputs:null,...e.input_components?{input_components:Q(e.input_components)}:{},...e.output_components?{output_components:Q(e.output_components)}:{},status:"running",started_at:new Date().toISOString()};return Ee(e,[n,...Se(e)]),Ot(),n.id}function ur(e,t,n){if(!t)return;let r=Se(e),i=r.find(s=>s.id===t);i&&(i.inputs=Q(n),Ee(e,r))}function lr(e,t,n){if(!t)return;let r=Se(e),i=r.find(a=>a.id===t);if(!i)return;let s=!1;if(n.type==="data")i.outputs=Q(n.data),Z.set(t,i.outputs);else if(n.type==="status"&&n.original_msg==="process_starts")dr(i,n.time);else if(n.type==="status"&&(n.stage==="generating"||n.stage==="streaming"))i.streamed=!0;else if(n.type==="status"&&n.stage==="complete")i.status="completed",lt(i,n),s=!0;else if(n.type==="status"&&n.stage==="error")i.status="failed",i.error=typeof n.message=="string"?n.message:JSON.stringify(n.message||"Unknown error"),lt(i,n),s=!0;else return;if(s)Z.has(t)&&(i.outputs=Z.get(t)),Z.delete(t),ge.delete(t);else if(i.streamed){if(Date.now()-(ge.get(t)??0)<pr)return;ge.set(t,Date.now()),Z.delete(t)}Ee(e,r)}function dr(e,t){if(e.process_started_at)return;let n=t||new Date;e.process_started_at=n.toISOString(),e.queued_ms=Math.max(0,n.getTime()-Date.parse(e.started_at))}function lt(e,t){let n=t.time||new Date;e.completed_at=n.toISOString(),e.duration_ms=(!e.streamed&&typeof t.cache_duration=="number"&&t.cache_duration>=0?t.cache_duration*1e3:null)??Math.max(0,n.getTime()-Date.parse(e.process_started_at||e.started_at))}function hr(e){return X(()=>Et(e),{type:"browser"})}function fr(e){X(()=>ar(e),void 0)}function gr(e){return X(()=>cr(e),null)}function _r(e,t,n){X(()=>ur(e,t,n),void 0)}function mr(e,t,n){X(()=>lr(e,t,n),void 0)}function wr(e,t={},n,r,i,s){try{let y=function(d){mr(ne,Pe,d),(d.type==="data"||d.type==="render")&&$e(d.data,At,N,xe.jwt),(i||Tt[d.type])&&Lt(d)},j=function(){for(Ce=!0;G.length>0;)G.shift()({value:void 0,done:!0})},Ne=function(d){G.length>0?G.shift()(d):le.push(d)},Ut=function(d){Ne(yr(d)),j()},Lt=function(d){Ne({value:d,done:!1})},Ue=function(){return le.length>0?Promise.resolve(le.shift()):Ce?Promise.resolve({value:void 0,done:!0}):new Promise(d=>G.push(d))},{token:a}=this.options,{fetch:o,app_reference:u,config:c,session_hash:p,api_info:h,api_map:w,stream_status:g,pending_stream_messages:k,pending_diff_streams:m,event_callbacks:z,unclosed_events:te,post_data:ae,options:R,api_prefix:N}=this,jt=s||{"x-gradio-user":"api"},xe=this;if(!h)throw Error(hn);if(!c)throw Error("Could not resolve app config");let At=c.root,{fn_index:f,endpoint_info:oe,dependency:O}=br(h,e,w,c),Oe=En(t,oe),U=c.protocol??"ws";if(U==="ws")throw Error(fn);let Dt=typeof O.api_name=="string"?`/${O.api_name}`:e,Pt=typeof O.api_name=="string"?`/${O.api_name}`:`Function ${f}`,je=d=>{let v=c.components.find(W=>W.id===d);return v?{type:v.type,component_class_id:v.component_class_id,props:v.props}:null},It=O.api_visibility==="public",Ae=c.run_history!==!1&&this.options.record_history!==!1,ne={app_id:c.app_id,username:c.username},De=hr(ne),ce={...jt,...Ae&&De.type==="bucket"?{"x-gradio-history-bucket":De.bucket_id}:{}},Pe=!Ae||!It?null:gr({...ne,endpoint:Dt,api_name:Pt,fn_index:f,inputs:H(Oe,O,c.components,"input",!0),input_components:O.inputs.map(je),output_components:O.outputs.map(je)}),B,J="",_=typeof e=="number"?"/predict":e,re,S=null,L=!1,Ie={},M=typeof window<"u"&&typeof document<"u"?new URLSearchParams(window.location.search).toString():"",Tt=R?.events?.reduce((d,v)=>(d[v]=!0,d),{})||{};async function Ct(){let d={},v={};d={event_id:S},v={event_id:S,session_hash:p,fn_index:f};try{if(!c)throw Error("Could not resolve app config");"event_id"in v&&await o(`${c.root}${N}/${an}`,{headers:{"Content-Type":"application/json"},method:"POST",body:JSON.stringify(v)}),await o(`${c.root}${N}/${sn}`,{headers:{"Content-Type":"application/json"},method:"POST",body:JSON.stringify(d)})}catch{console.warn("The `/reset` endpoint could not be called. Subsequent endpoint results may be unreliable.")}}let Nt=async d=>{await this._resolve_heartbeat(d)};async function Te(d){if(!c)return;let v=d.render_id;c.components=[...c.components.filter(x=>x.props.rendered_in!==v),...d.components],c.dependencies=[...c.dependencies.filter(x=>x.rendered_in!==v),...d.dependencies];let W=c.components.some(x=>x.type==="state"),$=c.dependencies.some(x=>x.targets.some(b=>b[1]==="unload"));c.connect_heartbeat=W||$,await Nt(c),y({type:"render",data:d,endpoint:_,fn_index:f})}let ue=this.handle_blob(c.root,Oe,oe).then(async d=>{let v=H(d,O,c.components,"input",!0);if(_r(ne,Pe,v||[]),re={data:v||[],event_data:n,fn_index:f,trigger_id:r,...R.oauth_token&&oe?.oauth_token?{oauth_token:R.oauth_token}:{}},tt(f,c))y({type:"status",endpoint:_,stage:"pending",queue:!1,fn_index:f,time:new Date}),ae(`${c.root}${N}/run${_.startsWith("/")?_:`/${_}`}${M?"?"+M:""}`,{...re,session_hash:p},ce).then(async([$,x])=>{let b=$.data;if(x==200)y({type:"data",endpoint:_,fn_index:f,data:H(b,O,c.components,"output",R.with_null_state),time:new Date,event_data:n,trigger_id:r}),$.render_config&&await Te($.render_config),y({type:"status",endpoint:_,fn_index:f,stage:"complete",eta:$.average_duration,queue:!1,time:new Date});else{let E=$?.error===q;y({type:"status",stage:"error",endpoint:_,fn_index:f,message:$.error,broken:E,queue:!1,time:new Date})}}).catch($=>{y({type:"status",stage:"error",message:$.message,endpoint:_,fn_index:f,queue:!1,time:new Date})});else if(U=="sse"){y({type:"status",stage:"pending",queue:!0,endpoint:_,fn_index:f,time:new Date});var W=new URLSearchParams({fn_index:f.toString(),session_hash:p}).toString();let $=new URL(`${c.root}${N}/${ht}?${M?M+"&":""}${W}`);if(this.jwt&&$.searchParams.set("__sign",this.jwt),B=this.stream($),!B)return Promise.reject(Error("Cannot connect to SSE endpoint: "+$.toString()));B.onmessage=async function(x){let{type:b,status:E,data:A}=Qe(JSON.parse(x.data),Ie[f]);if(b==="update"&&E&&!L)y({type:"status",endpoint:_,fn_index:f,time:new Date,...E}),E.stage==="error"&&(B?.close(),j());else if(b==="data"){let[ie,D]=await ae(`${c.root}${N}/queue/data`,{...re,session_hash:p,event_id:S},ce);D!==200&&(y({type:"status",stage:"error",message:q,queue:!0,endpoint:_,fn_index:f,time:new Date}),B?.close(),j())}else b==="complete"?L=E:b==="log"?y({type:"log",title:A.title,log:A.log,level:A.level,endpoint:_,duration:A.duration,visible:A.visible,fn_index:f}):(b==="generating"||b==="streaming")&&y({type:"status",time:new Date,...E,stage:E?.stage,queue:!0,endpoint:_,fn_index:f});A&&(y({type:"data",time:new Date,data:H(A.data,O,c.components,"output",R.with_null_state),endpoint:_,fn_index:f,event_data:n,trigger_id:r}),L&&(y({type:"status",time:new Date,...L,stage:E?.stage,queue:!0,endpoint:_,fn_index:f}),B?.close(),j()))}}else if(U=="sse_v1"||U=="sse_v2"||U=="sse_v2.1"||U=="sse_v3"){y({type:"status",stage:"pending",queue:!0,endpoint:_,fn_index:f,time:new Date});let $="";typeof window<"u"&&typeof document<"u"&&($=window?.location?.hostname);let x=kt($);return(typeof window<"u"&&typeof document<"u"&&window.parent!=window&&x&&window.supports_zerogpu_headers?Pn("zerogpu-headers",x):Promise.resolve(null)).then(b=>{let E={...ce,...b||{}};return ae(`${c.root}${N}/${Vt}?${M}`,{...re,session_hash:p},E)}).then(async([b,E])=>{if(b.event_id&&(J=b.event_id),E===503)y({type:"status",stage:"error",message:ft,queue:!0,endpoint:_,fn_index:f,time:new Date,visible:!0}),j();else if(E===422)y({type:"status",stage:"error",message:b.detail,queue:!0,endpoint:_,fn_index:f,code:"validation_error",time:new Date,visible:!0}),j();else if(E!==200){let A=b?.error===q;y({type:"status",stage:"error",broken:A,message:A?q:b.detail||b.error,queue:!0,endpoint:_,fn_index:f,time:new Date,visible:!0}),j()}else{S=b.event_id,J=S;let A=async function(ie){try{let{type:D,status:P,data:I,original_msg:qt}=Qe(ie,Ie[f]);if(D=="heartbeat")return;if(D==="update"&&P&&!L)y({type:"status",endpoint:_,fn_index:f,time:new Date,original_msg:qt,...P});else if(D==="complete")L=P;else if(D=="unexpected_error"||D=="broken_connection"){console.error("Unexpected error",P?.message);let zt=D==="broken_connection";y({type:"status",stage:"error",message:P?.message||"An Unexpected Error Occurred!",queue:!0,endpoint:_,broken:zt,session_not_found:P?.session_not_found,fn_index:f,time:new Date})}else if(D==="log"){y({type:"log",title:I.title,log:I.log,level:I.level,endpoint:_,duration:I.duration,visible:I.visible,fn_index:f});return}else(D==="generating"||D==="streaming")&&(y({type:"status",time:new Date,...P,stage:P?.stage,queue:!0,endpoint:_,fn_index:f}),I&&O.connection!=="stream"&&["sse_v2","sse_v2.1","sse_v3"].includes(U)&&Qn(m,S,I));I&&(y({type:"data",time:new Date,data:H(I.data,O,c.components,"output",R.with_null_state),endpoint:_,fn_index:f}),I.render_config&&await Te(I.render_config),L&&(y({type:"status",time:new Date,...L,stage:P?.stage,queue:!0,endpoint:_,fn_index:f}),j())),(P?.stage==="complete"||P?.stage==="error")&&(z[S]&&delete z[S],S in m&&delete m[S],j())}catch(D){console.error("Unexpected client exception",D),y({type:"status",stage:"error",message:"An Unexpected Error Occurred!",queue:!0,endpoint:_,fn_index:f,time:new Date}),["sse_v2","sse_v2.1","sse_v3"].includes(U)&&(ke(g,xe.abort_controller),g.open=!1,j())}};S in k&&(k[S].forEach(ie=>A(ie)),delete k[S]),z[S]=A,te.add(S),g.open||await this.open_stream()}})}});ue.catch(d=>{y({type:"status",stage:"error",message:d instanceof Error?d.message:String(d),queue:!tt(f,c),endpoint:_,fn_index:f,time:new Date}),j()});let Ce=!1,le=[],G=[],Le=(d,v)=>{ue.then(()=>{J&&this.post_data(`${c.root}${N}/stream/${J}${d}`,v)},()=>{})},qe={[Symbol.asyncIterator]:()=>qe,next:Ue,throw:async d=>(Ut(d),Ue()),return:async()=>(j(),{value:void 0,done:!0}),cancel:Ct,send_chunk:d=>{Le("",{...d,session_hash:this.session_hash})},close_stream:()=>{j(),Le("/close",{})},event_id:()=>J,wait_for_id:async()=>(await ue,S)};return qe}catch(a){throw console.error("Submit function encountered an error:",a),a}}function yr(e){return{then:(t,n)=>n(e)}}function br(e,t,n,r){let i,s,a;if(typeof t=="number")i=t,s=e.unnamed_endpoints[i],a=r.dependencies.find(o=>o.id==t);else{let o=t.replace(/^\//,"");i=n[o],s=e.named_endpoints[t.trim()]??e.named_endpoints[`/${o}`],a=r.dependencies.find(u=>u.id==n[o])}if(typeof i!="number"||!a){let o=r.dependencies.filter(u=>u.api_name).map(u=>`"/${u.api_name}"`).join(", ");throw Error(`No endpoint matching ${JSON.stringify(t)} was found. `+(o?`Valid named endpoints are: ${o}. `:"This app exposes no named endpoints. ")+"An fn_index (number) of an existing dependency can also be used.")}return{fn_index:i,endpoint_info:s,dependency:a}}var Mt,dt,Gt,Wt,Ht,Zt,Ge,Yt,We,Kt,ht,Vt,He,Qt,Ze,Xt,en,tn,nn,rn,sn,an,on,ft,q,T,cn,Ye,Y,un,ln,gt,pn,dn,hn,fn,gn,_t,_n,yt,ye,vn,_e,En,Xe,ve,bt,Dn,Tn,$t,zn,it,st,at,C,pt,Wn,se,V,ct,St,nr,rr,or,pr,ge,Z,we,he=Be(()=>{Mt=Object.create,dt=Object.defineProperty,Gt=Object.getOwnPropertyDescriptor,Wt=Object.getOwnPropertyNames,Ht=Object.getPrototypeOf,Zt=Object.prototype.hasOwnProperty,Ge=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),Yt=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(var i=Wt(t),s=0,a=i.length,o;s<a;s++)o=i[s],!Zt.call(e,o)&&o!==n&&dt(e,o,{get:(u=>t[u]).bind(null,o),enumerable:!(r=Gt(t,o))||r.enumerable});return e},We=(e,t,n)=>(n=e==null?{}:Mt(Ht(e)),Yt(t||!e||!e.__esModule?dt(n,"default",{value:e,enumerable:!0}):n,e)),Kt="host",ht="queue/data",Vt="queue/join",He="upload",Qt="login",Ze="config",Xt="info",en="runtime",tn="sleeptime",nn="heartbeat",rn="component_server",sn="reset",an="cancel",on="app_id",ft="This application is currently busy. Please try again. ",q="Connection errored out. ",T="Could not resolve app config. ",cn="Could not get space status. ",Ye="Could not get API info. ",Y="Space metadata could not be loaded. ",un="Invalid URL. A full URL path is required.",ln="Not authorized to access this space. ",gt="Invalid credentials. Could not login. ",pn="Could not access this app (received a 401 response). If it is a private Hugging Face Space, pass a valid Hugging Face token to the `token` option of `Client.connect`. You can generate a token at https://huggingface.co/settings/tokens.",dn=(e,t)=>`Space "${e}" could not be accessed (received a ${t} response from the Hugging Face API). Check that the Space name is spelled correctly and that the Space exists. If the Space is private, pass a valid Hugging Face token to the \`token\` option of \`Client.connect\`. You can generate a token at https://huggingface.co/settings/tokens.`,hn="No API information is available for this app. This can happen when the app's `/info` endpoint cannot be reached, or when the app is running a legacy version of Gradio that is not supported by this client. ",fn="This app appears to be running a legacy version of Gradio (3.x or earlier) that communicates over WebSockets, which is not supported by this version of @gradio/client. Please upgrade the app to a newer version of Gradio, or connect to it with @gradio/client version 0.x.",gn="File system access is only available in Node.js environments",_t="Root URL not found in client config",_n="Error uploading file";yt=e=>{let t=[];return e.split(/,(?=\s*[^\s=;]+=[^\s=;]+)/).forEach(n=>{let[r,i]=n.split(";")[0].split("=");r&&i&&t.push(`${r.trim()}=${i.trim()}`)}),t},ye=/^[a-zA-Z0-9_\-\.]+\/[a-zA-Z0-9_\-\.]+$/,vn=/.*hf\.space\/{0,1}.*$/;_e=(...e)=>{try{return e.reduce((t,n)=>(t=t.replace(/\/+$/,""),n=n.replace(/^\/+/,""),new URL(n,t+"/").toString()))}catch{throw Error(un)}};En=(e=[],t)=>{let n=t?t.parameters:[];if(Array.isArray(e))return t&&n.length>0&&e.length>n.length&&console.warn("Too many arguments provided for the endpoint."),e;let r=[],i=Object.keys(e);return n.forEach((s,a)=>{if(e.hasOwnProperty(s.parameter_name))r[a]=e[s.parameter_name];else if(s.parameter_has_default)r[a]=s.parameter_default;else throw Error(`No value provided for required parameter: ${s.parameter_name}`)}),i.forEach(s=>{if(!n.some(a=>a.parameter_name===s))throw Error(`Parameter \`${s}\` is not a valid keyword argument. Please refer to the API for usage.`)}),r.forEach((s,a)=>{if(s===void 0&&!n[a].parameter_has_default)throw Error(`No value provided for required parameter: ${n[a].parameter_name}`)}),r};Xe={si:{radix:1e3,unit:["b","kb","Mb","Gb","Tb","Pb","Eb","Zb","Yb"]},iec:{radix:1024,unit:["b","Kib","Mib","Gib","Tib","Pib","Eib","Zib","Yib"]},jedec:{radix:1024,unit:["b","Kb","Mb","Gb","Tb","Pb","Eb","Zb","Yb"]}};ve=class{constructor({path:e,url:t,orig_name:n,size:r,blob:i,is_stream:s,mime_type:a,alt_text:o,b64:u}){l(this,"path");l(this,"url");l(this,"orig_name");l(this,"size");l(this,"blob");l(this,"is_stream");l(this,"mime_type");l(this,"alt_text");l(this,"b64");l(this,"meta",{_type:"gradio.FileData"});this.path=e,this.url=t,this.orig_name=n,this.size=r,this.blob=t?void 0:i,this.is_stream=s,this.mime_type=a,this.alt_text=o,this.b64=u}},bt=class{constructor(e,t){l(this,"type");l(this,"command");l(this,"meta");l(this,"fileData");this.type="command",this.command=e,this.meta=t}},Dn=typeof process<"u"&&process.versions&&process.versions.node;Tn=["/file=","/file/","/stream/","/proxy="];$t=async(e,t)=>{let n=0;return new Promise(r=>{K(e,ye.test(e)?"space_name":"subdomain",i=>{t(i),i.status==="running"||i.status==="error"||i.status==="paused"||i.status==="space_error"?r():(i.status==="sleeping"||i.status==="building")&&(n<12?(n++,setTimeout(()=>{$t(e,t).then(r)},5e3)):r())})})},zn=/^(?=[^]*\b[dD]iscussions{0,1}\b)(?=[^]*\b[dD]isabled\b)[^]*$/;it=["cpu-basic","cpu-upgrade","cpu-xl","t4-small","t4-medium","a10g-small","a10g-large","a10g-largex2","a10g-largex4","a100-large","zero-a10g","h100","h100x8"];st="supports-zerogpu-headers",at=!1;Wn=(pt=class extends TransformStream{constructor(t={allowCR:!1}){super({transform:(n,r)=>{for(n=F(this,C)+n;;){let i=n.indexOf(`
|
| 3 |
+
`),s=t.allowCR?n.indexOf("\r"):-1;if(s!==-1&&s!==n.length-1&&(i===-1||i-1>s)){r.enqueue(n.slice(0,s)),n=n.slice(s+1);continue}if(i===-1)break;let a=n[i-1]==="\r"?i-1:i;r.enqueue(n.slice(0,a)),n=n.slice(i+1)}Me(this,C,n)},flush:n=>{if(F(this,C)==="")return;let r=t.allowCR&&F(this,C).endsWith("\r")?F(this,C).slice(0,-1):F(this,C);n.enqueue(r)}});Je(this,C,"")}},C=new WeakMap,pt);se="gradio:run-history:",V=`${se}v2:`,ct=`${se}replay:v2:`,St=`${se}destination:v1:`,nr=100,rr=8;or="gradio:run-history-change";pr=500,ge=new Map,Z=new Map;we=class{constructor(e,t={events:["data"]}){l(this,"app_reference");l(this,"options");l(this,"deep_link",null);l(this,"page",null);l(this,"config");l(this,"api_prefix","");l(this,"api_info");l(this,"api_map",{});l(this,"session_hash",Math.random().toString(36).substring(2));l(this,"jwt",!1);l(this,"last_status",{});l(this,"cookies",null);l(this,"stream_status",{open:!1});l(this,"closed",!1);l(this,"pending_stream_messages",{});l(this,"pending_diff_streams",{});l(this,"event_callbacks",{});l(this,"unclosed_events",new Set);l(this,"heartbeat_event",null);l(this,"abort_controller",null);l(this,"stream_instance",null);l(this,"current_payload");l(this,"view_api");l(this,"upload_files");l(this,"upload");l(this,"handle_blob");l(this,"post_data");l(this,"submit");l(this,"predict");l(this,"open_stream");l(this,"resolve_config");l(this,"resolve_cookies");this.app_reference=e,this.deep_link=t.query_params?.deep_link||null,this.page=t.query_params?.page??null,t.events||(t.events=["data"]),mt(t),this.options=t,this.current_payload={},t.cookies&&(this.cookies=t.cookies),this.view_api=xn.bind(this),this.upload_files=On.bind(this),this.handle_blob=Cn.bind(this),this.post_data=Ln.bind(this),this.submit=wr.bind(this),this.predict=qn.bind(this),this.open_stream=Vn.bind(this),this.resolve_config=yn.bind(this),this.resolve_cookies=bn.bind(this),this.upload=An.bind(this),this.fetch=this.fetch.bind(this),this.handle_space_success=this.handle_space_success.bind(this),this.stream=this.stream.bind(this)}get_url_config(e=null){if(!this.config)throw Error(T);e===null&&(e=window.location.href);let t=s=>s.replace(/^\/+|\/+$/g,""),n=t(new URL(this.config.root).pathname),r=t(new URL(e).pathname),i;return i=r.startsWith(n)?t(r.substring(n.length)):"",this.get_page_config(i)}get_page_config(e){if(!this.config)throw Error(T);let t=this.config;return e in t.page||(e=""),{...t,current_page:e,layout:t.page[e].layout,components:t.components.filter(n=>t.page[e].components.includes(n.id)),dependencies:this.config.dependencies.filter(n=>t.page[e].dependencies.includes(n.id))}}fetch(e,t){let n=new Headers(t?.headers||{});return this&&this.cookies&&n.append("Cookie",this.cookies),this&&this.options.headers&&new Headers(this.options.headers).forEach((r,i)=>{n.append(i,r)}),fetch(e,{...t,headers:n})}stream(e){let t=new Headers;return this&&this.cookies&&t.append("Cookie",this.cookies),this&&this.options.headers&&new Headers(this.options.headers).forEach((n,r)=>{t.append(r,n)}),this&&this.options.token&&t.append("Authorization",`Bearer ${this.options.token}`),this.abort_controller=new AbortController,this.stream_instance=tr(e.toString(),{credentials:this.options.credentials??"same-origin",headers:t,signal:this.abort_controller.signal}),this.stream_instance}async init(){Gn(),this.options.auth&&await this.resolve_cookies(),await this._resolve_config().then(e=>e?.config&&this._resolve_heartbeat(e.config));try{this.api_info=await this.view_api()}catch(e){console.error(e.message)}this.api_map=Ke(this.config?.dependencies||[])}async _resolve_heartbeat(e){if(this.config=e,this.api_prefix=e.api_prefix||"",e.space_id&&this.options.token&&(this.jwt=await mn(e.space_id,this.options.token,this.cookies)),nt(this.config,this.jwt),this.config&&this.config.connect_heartbeat){let t=new URL(`${this.config.root}${this.api_prefix}/${nn}/${this.session_hash}`);this.jwt&&t.searchParams.set("__sign",this.jwt),this.heartbeat_event||(this.heartbeat_event=this.stream(t))}}static async connect(e,t={events:["data"]}){let n=new this(e,t);return t.session_hash&&(n.session_hash=t.session_hash),await n.init(),n}async reconnect(){let e=new URL(`${this.config.root}${this.api_prefix}/${on}`),t;try{let n=await this.fetch(e);if(!n.ok)throw Error();t=(await n.json()).app_id}catch{return"broken"}return t===this.config.app_id?"connected":"changed"}close(){this.closed=!0,ke(this.stream_status,this.abort_controller)}async refresh(){if(!this.config)throw Error(T);let e=await this.resolve_config(this.config.root,!1);if(!e)throw Error(T);this.config=e,this.api_prefix=e.api_prefix||"",this.api_map=Ke(e.dependencies||[]),nt(this.config,this.jwt);try{this.api_info=await this.view_api()}catch(t){console.error(Ye+t.message)}return this.get_url_config()}set_current_payload(e){this.current_payload=e}static async duplicate(e,t={events:["data"]}){return Fn(e,t)}async _resolve_config(){let{http_protocol:e,host:t,space_id:n}=await be(this.app_reference,this.options.token),{status_callback:r}=this.options;n&&r&&await $t(n,r);let i;try{let s=`${e}//${t}`;if(i=await this.resolve_config(s),!i)throw Error(T);return this.config_success(i)}catch(s){if(n&&r)K(n,ye.test(n)?"space_name":"subdomain",this.handle_space_success);else throw r&&r({status:"error",message:"Could not load this space.",load_status:"error",detail:"NOT_FOUND"}),s instanceof Error?s:Error(String(s))}}async config_success(e){if(this.config=e,this.api_prefix=e.api_prefix||"",e.run_history===!1&&fr({app_id:e.app_id,username:e.username}),this.config.auth_required)return this.prepare_return_obj();try{this.api_info=await this.view_api()}catch(t){console.error(Ye+t.message)}return this.prepare_return_obj()}async handle_space_success(e){if(!this)throw Error(T);let{status_callback:t}=this.options;if(t&&t(e),e.status==="running")try{if(this.config=await this._resolve_config(),this.api_prefix=this?.config?.api_prefix||"",!this.config)throw Error(T);return await this.config_success(this.config)}catch(n){throw t&&t({status:"error",message:"Could not load this space.",load_status:"error",detail:"NOT_FOUND"}),n}}async component_server(e,t,n){if(!this.config)throw Error(T);let r={},{token:i}=this.options,{session_hash:s}=this;i&&(r.Authorization=`Bearer ${this.options.token}`);let a,o=this.config.components.find(c=>c.id===e);a=o?.props?.root_url?o.props.root_url:this.config.root;let u;if(typeof n=="object"&&n&&"binary"in n){let c=n;u=new FormData;for(let p in c.data)p!=="binary"&&u.append(p,c.data[p]);u.set("component_id",e.toString()),u.set("fn_name",t),u.set("session_hash",s)}else u=JSON.stringify({data:n,component_id:e,fn_name:t,session_hash:s}),r["Content-Type"]="application/json";i&&(r.Authorization=`Bearer ${i}`);try{let c=await this.fetch(`${a}${this.api_prefix}/${rn}/`,{method:"POST",body:u,headers:r,credentials:this.options.credentials??"same-origin"});if(!c.ok)throw Error("Could not connect to component server: "+c.statusText);let p=await c.json();return $e(p,this.config.root,this.config.api_prefix||"",this.jwt),p}catch(c){console.warn(c)}}set_cookies(e){this.cookies=yt(e).join("; ")}prepare_return_obj(){return{config:this.config,predict:this.predict,submit:this.submit,view_api:this.view_api,component_server:this.component_server}}}});he();export{we as Client,In as handle_file};
|
widgets.js
CHANGED
|
@@ -2,10 +2,13 @@
|
|
| 2 |
const $ = (h) => { const t = document.createElement('template'); t.innerHTML = h.trim(); return t.content.firstChild; };
|
| 3 |
const G = '#f2c94c', OR = '#faa968', TE = '#028391', CY = '#8cbfb8', RD = '#f85525';
|
| 4 |
const loops = new Set();
|
| 5 |
-
|
| 6 |
-
function
|
| 7 |
-
function
|
| 8 |
-
function
|
|
|
|
|
|
|
|
|
|
| 9 |
|
| 10 |
export const STUDIOS = [
|
| 11 |
{id:'chat',cat:'Text',icon:'💬',name:'Chat',like:'ChatGPT-like',build(el){
|
|
@@ -13,7 +16,7 @@ export const STUDIOS = [
|
|
| 13 |
const log=el.querySelector('.chat'),inp=el.querySelector('input');
|
| 14 |
const R=['Simuliere Antwort über 7 Agenten im Schwarm…','Gute Frage! Der Schwarm schlägt 3 Varianten vor.','Ich habe das an das Coding-Studio weitergeleitet (simuliert).','Zusammenfassung: Klar, machbar, mit Gold-Rand. 🐝'];
|
| 15 |
const send=()=>{ if(!inp.value.trim())return; log.insertAdjacentHTML('beforeend',`<p class="u">› ${inp.value.replace(/</g,'<')}</p>`); inp.value='';
|
| 16 |
-
const p=$(`<p class="a">◆ </p>`); log.append(p); const txt=R[Math.random()*R.length|0]; let k=0;
|
| 17 |
el.querySelector('button').onclick=send; inp.onkeydown=e=>{e.stopPropagation(); if(e.key==='Enter')send();};
|
| 18 |
}},
|
| 19 |
{id:'image',cat:'Bild',icon:'🖌',name:'Image Edit',like:'Photoshop-like',build(el){
|
|
@@ -64,7 +67,7 @@ export const STUDIOS = [
|
|
| 64 |
el.querySelector('input').onkeydown=e=>e.stopPropagation();
|
| 65 |
el.querySelector('.btn').onclick=()=>{ const s=el.querySelector('.songs'); const n=['Golden Hive','Hex Sunset','Swarm Drive'][s.children.length%3];
|
| 66 |
const d=$(`<div class="row" style="border:1px solid #333;padding:4px"><span style="background:linear-gradient(135deg,${OR},${TE});width:26px;height:26px;display:inline-block"></span><span>${n}<br><small style="color:${CY}">2:4${s.children.length} · v4 sim</small></span><span class="eq" style="margin-left:auto;letter-spacing:-2px;color:${G}"></span></div>`); s.prepend(d);
|
| 67 |
-
let k=0;
|
| 68 |
}},
|
| 69 |
{id:'auto',cat:'Automation',icon:'⛓',name:'Automation',like:'n8n-like',build(el){
|
| 70 |
el.innerHTML=`<canvas></canvas><div class="row"><button class="btn">▶ Execute workflow</button><span class="st" style="color:${CY}">Knoten ziehbar</span></div>`;
|
|
|
|
| 2 |
const $ = (h) => { const t = document.createElement('template'); t.innerHTML = h.trim(); return t.content.firstChild; };
|
| 3 |
const G = '#f2c94c', OR = '#faa968', TE = '#028391', CY = '#8cbfb8', RD = '#f85525';
|
| 4 |
const loops = new Set();
|
| 5 |
+
const ivs = new Set(), cleanups = new Set();
|
| 6 |
+
export function every(fn,ms){ const id=setInterval(()=>fn(()=>{clearInterval(id);ivs.delete(id);}),ms); ivs.add(id); return id; }
|
| 7 |
+
export function onStop(fn){ cleanups.add(fn); }
|
| 8 |
+
export function stopLoops(){ loops.forEach(id=>cancelAnimationFrame(id)); loops.clear(); ivs.forEach(clearInterval); ivs.clear(); cleanups.forEach(f=>{try{f()}catch(e){}}); cleanups.clear(); }
|
| 9 |
+
export function loop(fn){ let id; const f=(t)=>{ loops.delete(id); if(!document.hidden) fn(t); id=requestAnimationFrame(f); loops.add(id); }; id=requestAnimationFrame(f); loops.add(id); }
|
| 10 |
+
export function cv(el,h=110){ const c=el.querySelector('canvas'); const w=c.clientWidth||300; c.width=w*devicePixelRatio; c.height=h*devicePixelRatio; c.style.height=h+'px'; const x=c.getContext('2d'); x.scale(devicePixelRatio,devicePixelRatio); return [c,x,w,h]; }
|
| 11 |
+
export function fakeProgress(el,ms,done){ const i=el.querySelector('.prog i'); let p=0; every((stop)=>{ p+=100/(ms/80); i.style.width=Math.min(p,100)+'%'; if(p>=100){stop(); done&&done();} },80); }
|
| 12 |
|
| 13 |
export const STUDIOS = [
|
| 14 |
{id:'chat',cat:'Text',icon:'💬',name:'Chat',like:'ChatGPT-like',build(el){
|
|
|
|
| 16 |
const log=el.querySelector('.chat'),inp=el.querySelector('input');
|
| 17 |
const R=['Simuliere Antwort über 7 Agenten im Schwarm…','Gute Frage! Der Schwarm schlägt 3 Varianten vor.','Ich habe das an das Coding-Studio weitergeleitet (simuliert).','Zusammenfassung: Klar, machbar, mit Gold-Rand. 🐝'];
|
| 18 |
const send=()=>{ if(!inp.value.trim())return; log.insertAdjacentHTML('beforeend',`<p class="u">› ${inp.value.replace(/</g,'<')}</p>`); inp.value='';
|
| 19 |
+
const p=$(`<p class="a">◆ </p>`); log.append(p); const txt=R[Math.random()*R.length|0]; let k=0; every((stop)=>{p.textContent='◆ '+txt.slice(0,++k); log.scrollTop=1e4; if(k>=txt.length)stop();},18); };
|
| 20 |
el.querySelector('button').onclick=send; inp.onkeydown=e=>{e.stopPropagation(); if(e.key==='Enter')send();};
|
| 21 |
}},
|
| 22 |
{id:'image',cat:'Bild',icon:'🖌',name:'Image Edit',like:'Photoshop-like',build(el){
|
|
|
|
| 67 |
el.querySelector('input').onkeydown=e=>e.stopPropagation();
|
| 68 |
el.querySelector('.btn').onclick=()=>{ const s=el.querySelector('.songs'); const n=['Golden Hive','Hex Sunset','Swarm Drive'][s.children.length%3];
|
| 69 |
const d=$(`<div class="row" style="border:1px solid #333;padding:4px"><span style="background:linear-gradient(135deg,${OR},${TE});width:26px;height:26px;display:inline-block"></span><span>${n}<br><small style="color:${CY}">2:4${s.children.length} · v4 sim</small></span><span class="eq" style="margin-left:auto;letter-spacing:-2px;color:${G}"></span></div>`); s.prepend(d);
|
| 70 |
+
let k=0; every((stop)=>{ if(!d.isConnected)return stop(); d.querySelector('.eq').textContent=[...Array(8)].map(()=>'▁▂▃▄▅▆▇'[Math.random()*7|0]).join(''); if(++k>200)stop();},120); };
|
| 71 |
}},
|
| 72 |
{id:'auto',cat:'Automation',icon:'⛓',name:'Automation',like:'n8n-like',build(el){
|
| 73 |
el.innerHTML=`<canvas></canvas><div class="row"><button class="btn">▶ Execute workflow</button><span class="st" style="color:${CY}">Knoten ziehbar</span></div>`;
|