// STUDIUS real functions — public Gradio Spaces via self-hosted @gradio/client (no token, no secrets) + client-side tools.
import { Client, handle_file } from './vendor/gradio-client.js?v=271';
import { STUDIOS, every, onStop, loop, cv } from './widgets.js?v=50';
const esc = (t) => String(t).replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c]));
const hf = (s) => `${s}`;
const conns = new Map();
function connect(space) {
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; }));
return conns.get(space);
}
window.__studiusLog = [];
/** run a Space endpoint robustly: status → onStatus, partial data → onData, hard timeout, cancel on close */
async function runAnon(space, ep, data, { onStatus = () => {}, onData = () => {}, timeout = 150000, el } = {}) {
const t0 = performance.now(); const c = await connect(space); const job = c.submit(ep, data);
let last = null, done = false, err = null; const cancel = () => { if (!done) { done = true; try { job.cancel?.(); } catch (e) {} } };
onStop(cancel); const to = setTimeout(() => { err = new Error('Zeitüberschreitung nach ' + Math.round(timeout / 1000) + ' s'); cancel(); }, timeout);
try {
for await (const m of job) {
if (done || (el && !el.isConnected)) break;
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; }
else if (m.type === 'data') { last = m.data; onData(m.data); }
}
} finally { clearTimeout(to); done = true; }
if (err) throw err; if (el && !el.isConnected) throw new Error('abgebrochen'); if (!last) throw new Error('keine Daten');
window.__studiusLog.push({ space, ep, via: 'anon', ms: Math.round(performance.now() - t0) }); return last;
}
/** Signed-in: run server-side with the user's own HF token/quota (token never reaches the page). SSE stream. */
async function runUser(space, ep, data, { onStatus = () => {}, onData = () => {}, timeout = 150000, el } = {}) {
const t0 = performance.now(), f = new FormData(), args = {}; let n = 0;
for (const [k, v] of Object.entries(data)) {
if (v instanceof Blob) { const id = 'f' + n++; f.append(id, v, v.name || ('input.' + ({ 'image/jpeg': 'jpg', 'image/png': 'png', 'image/webp': 'webp', 'audio/wav': 'wav', 'audio/x-wav': 'wav', 'audio/wave': 'wav', 'audio/mpeg': 'mp3', 'audio/ogg': 'ogg', 'audio/flac': 'flac', 'video/mp4': 'mp4', 'video/webm': 'webm' }[(v.type || '').split(';')[0]] || 'bin'))); args[k] = { __file__: id }; }
else if (typeof v === 'string' && v.startsWith('/api/tmp/') && k !== 'prompt') args[k] = { __tmp__: v };
else args[k] = v;
}
f.append('space', space); f.append('ep', ep); f.append('args', JSON.stringify(args)); f.append('timeout', String(Math.round(timeout / 1000)));
const ac = new AbortController(); onStop(() => ac.abort()); const to = setTimeout(() => ac.abort(), timeout + 15000);
let last = null, err = null;
try {
const r = await fetch('/api/run', { method: 'POST', body: f, credentials: 'include', signal: ac.signal });
if (!r.ok) throw Object.assign(new Error((await r.json().catch(() => ({}))).detail || 'HTTP ' + r.status), { http: r.status });
const rd = r.body.getReader(), dec = new TextDecoder(); let buf = '';
for (;;) { const { value, done } = await rd.read(); if (done) break; buf += dec.decode(value, { stream: true }); let i;
while ((i = buf.indexOf('\n\n')) >= 0) { const line = buf.slice(0, i); buf = buf.slice(i + 2); if (!line.startsWith('data: ')) continue; const m = JSON.parse(line.slice(6));
if (el && !el.isConnected) { ac.abort(); throw new Error('abgebrochen'); }
if (m.type === 'status') onStatus(m); else if (m.type === 'data') { last = Array.isArray(m.data) ? m.data : [m.data]; onData(last); } else if (m.type === 'error') err = new Error(m.message); } }
} finally { clearTimeout(to); }
if (err) throw err; if (!last) throw new Error('keine Daten');
window.__studiusLog.push({ space, ep, via: 'user', ms: Math.round(performance.now() - t0) }); return last;
}
export const signedIn = () => !!window.__ws?.me?.signedIn;
/* quota: user's own ZeroGPU seconds (HUD) + clear fallback notices */
export async function refreshQuota() { try { const q = await (await fetch('/api/quota', { credentials: 'include' })).json(); window.__quota = q; window.dispatchEvent(new CustomEvent('studius-quota', { detail: q })); return q; } catch (e) { return null; } }
const fmtReset = (iso) => { if (!iso) return ''; const ms = new Date(iso) - Date.now(); if (ms <= 0) return 'gleich'; const h = Math.floor(ms / 36e5), m = Math.round(ms % 36e5 / 6e4); return `in ${h ? h + ' h ' : ''}${m} min (${new Date(iso).toLocaleTimeString('de-DE', { hour: '2-digit', minute: '2-digit' })})`; };
const isQuota = (m) => /quota|ZeroGPU|GPU task aborted|exceeded/i.test(m || '');
function notice(el, html, kind = 'warn') { const pop = el?.closest?.('#pop'); if (!pop) return; let n = pop.querySelector('.qnote'); if (!n) { n = document.createElement('div'); n.className = 'qnote'; n.setAttribute('role', 'status'); (pop.querySelector('.credit') || pop.lastElementChild).insertAdjacentElement('beforebegin', n); } n.className = 'qnote ' + kind; n.innerHTML = html; window.__notice = n.textContent; }
let LASTM = '';
export async function run(space, ep, data, opt = {}) { LASTM = space; let why = '';
if (signedIn()) {
const q = window.__quota; if (q?.ok && q.remaining < 60) notice(opt.el, `⚡ Nur noch ${Math.round(q.remaining)} s deiner ZeroGPU-Quota${q.resetsAt ? ' · Reset ' + fmtReset(q.resetsAt) : ''} – evtl. Fallback.`);
try { const d = await runUser(space, ep, data, opt); opt.el && via(opt.el, 'user'); refreshQuota(); return d; }
catch (e) { if (e.message === 'abgebrochen' || (opt.el && !opt.el.isConnected)) throw e; if (opt.noAnonOn?.test(e.message)) throw e; console.warn('user-quota run failed, trying anonymous:', e.message); why = e.message;
const q2 = await refreshQuota();
notice(opt.el, isQuota(why) ? `⚠ Deine ZeroGPU-Quota ist aufgebraucht${(m => m ? ` (${m[1]} s angefragt, ${m[2]} s übrig)` : '')(why.match(/\((\d+)s requested vs\. (\d+)s left\)/))}${q2?.ok && q2.resetsAt ? ' · Reset ' + fmtReset(q2.resetsAt) : ''}. Fallback: anonyme Quota – kann langsamer sein oder ebenfalls scheitern. Mehr Quota (PRO)` : `⚠ Lauf mit deinem Konto fehlgeschlagen (${esc(why.slice(0, 120))}). Fallback: anonyme Quota.`);
opt.onStatus?.({ stage: 'pending', message: 'Fallback: anonyme Quota' }); }
}
const anon = {}; for (const [k, v] of Object.entries(data)) anon[k] = v instanceof Blob ? handle_file(v) : typeof v === 'string' && v.startsWith('/api/') && k !== 'prompt' ? handle_file(await (await fetch(v)).blob()) : v;
try { const d = await runAnon(space, ep, anon, opt); opt.el && via(opt.el, 'anon'); return d; }
catch (e) { opt.el?.closest?.('#pop')?.querySelector('.credit .via')?.remove(); if (why || isQuota(e.message)) notice(opt.el, (window.__notice && why ? esc(window.__notice) + '
' : '') + (isQuota(e.message) ? '⛔ Auch die anonyme Quota ist erschöpft' : `⛔ Anonymer Fallback fehlgeschlagen (${esc(e.message.slice(0, 100))})`) + ` – ${signedIn() ? 'warte auf den Reset deiner Quota' : 'melde dich mit Hugging Face an, um deine eigene Quota zu nutzen'}. Das Studio zeigt bis dahin eine Simulation.`, 'err'); throw e; }
}
const via = (el, v) => { const c = el.closest?.('#pop')?.querySelector('.credit'); if (c) { c.querySelector('.via')?.remove(); c.insertAdjacentHTML('beforeend', ` · ${v === 'user' ? '🔑 deine HF-Quota' : 'anonyme Quota'}`); } };
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…')
: 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 || '';
const url = (f) => typeof f === 'string' ? f : f?.url || f?.path;
function badge(el, mode, space) {
const b = el.querySelector('.badge'); if (b) { b.className = 'badge ' + (mode === 'SIM' ? 'sim' : 'real'); b.textContent = mode; }
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'); }
}
async function dl(a, src, name) { // cross-origin download → blob URL
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'; }
}
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); }
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); };
/** typed asset bus: every studio result is announced; workspace.js adds 'Save to Workspace' + 'Send to…' */
export const result = (el, asset) => { if (!asset.model && LASTM && /^(\/api\/tmp\/|https:)/.test(asset.url || '')) asset.model = LASTM; window.__lastAsset = asset; window.dispatchEvent(new CustomEvent('studius-result', { detail: { el, asset } })); };
const S = (id) => STUDIOS.find(s => s.id === id);
const keep = (el) => el.querySelectorAll('input,textarea').forEach(i => i.addEventListener('keydown', e => e.stopPropagation()));
/* 1 CHAT */
const CHAT = 'huggingface-projects/llama-3.2-3B-Instruct';
{ const s = S('chat'); s.real = 'API'; s.build = (el) => {
el.innerHTML = `
◆ STUDIUS-Chat (Llama 3.2 3B). Frag mich etwas.
› ${esc(q)}
`); const p = document.createElement('p'); p.className = 'a'; p.textContent = '◆ …'; log.append(p); log.scrollTop = 1e5; const ctx = hist.slice(-4).map(([u, a]) => `User: ${u}\nAssistant: ${a}`).join('\n'); const persona = window.__persona?.(el); const msg = (persona ? `System: ${persona}\n` : '') + (ctx ? ctx + '\nUser: ' + q : q) + (persona ? '\nAssistant:' : ''); setS(el, 'Verbinde…'); const tm = timer(el, '.stat'); let out = ''; 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, 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; } }); hist.push([q, out]); el.dispatchEvent(new CustomEvent('chat-reply', { detail: { text: out, p } })); result(el.querySelector('.chat'), { kind: 'text', mime: 'text/plain', text: out, name: 'chat-' + Date.now() + '.txt', studio: 'chat', prompt: q }); setS(el, '✔ gestreamt'); badge(el, 'REAL', CHAT); } 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; } finally { clearInterval(tm); busy = false; btn.disabled = false; window.__chatOut = out; } }; btn.onclick = send; inp.onkeydown = e => { e.stopPropagation(); if (e.key === 'Enter') send(); }; }; } /* 2 IMAGE: Generate (FLUX) + Edit (local) */ const FLUX = 'black-forest-labs/FLUX.1-schnell', KONTEXT = 'black-forest-labs/FLUX.1-Kontext-Dev', TTS = 'Qwen/Qwen3-TTS'; { const s = S('image'); const editBuild = s.build; s.real = 'API'; s.build = (el) => { el.innerHTML = ``; const tp = el.querySelector('.tp'); const gen = () => { tp.innerHTML = `