// SRT Translator — frontend (vanilla JS, no build step). const $ = (s) => document.querySelector(s); const LS_SETTINGS = 'srt-tr:settings:v1'; const LS_WORK = 'srt-tr:work:v1:'; const CTX_STEPS = [2048, 4096, 6144, 8192, 12288, 16384, 24576, 32768, 49152, 65536, 98304, 131072, 196608, 262144]; const SETTING_IDS = ['contextLength', 'kvCacheK', 'kvCacheV', 'flashAttention', 'gpuRatio', 'numGpu', 'evalBatchSize', 'unloadOthers', 'temperature', 'topP', 'topK', 'minP', 'repeatPenalty', 'seed', 'disableThinking']; const OPTION_IDS = ['source', 'target', 'mode', 'batchSize', 'contextBefore', 'contextAfter', 'maxLineLength', 'concurrency', 'songs', 'notes', 'profile']; const S = { meta: null, engine: 'lmstudio', engineCfg: {}, connected: false, caps: null, models: [], model: null, modelInfo: null, applied: {}, // model -> load config applied by our last load (LM Studio) file: null, tr: {}, status: {}, rows: new Map(), job: null, rowJobs: new Map(), }; // ---------------------------------------------------------------- utilities async function api(path, body, { raw = false, query = '' } = {}) { const res = await fetch(path + query, { method: body === undefined ? 'GET' : 'POST', headers: raw ? { 'content-type': 'application/octet-stream' } : { 'content-type': 'application/json' }, body: body === undefined ? undefined : raw ? body : JSON.stringify(body), }); const data = await res.json().catch(() => ({})); if (!res.ok) throw new Error(data.error || `HTTP ${res.status}`); return data; } const GB = 2 ** 30; const fmtGB = (b) => (b == null || Number.isNaN(b) ? '—' : `${(b / GB).toFixed(b < 10 * GB ? 2 : 1)} GB`); // Sizes under 1 GB read better in MB ("61 MB / 498 MB"). const fmtSize = (b) => (b == null ? '—' : b < 2 ** 30 ? `${Math.round(b / 2 ** 20)} MB` : fmtGB(b)); const fmtInt = (n) => (n == null ? '—' : Math.round(n).toLocaleString('pl-PL')); const fmtCtx = (n) => (n >= 1024 ? `${Math.round(n / 1024)}k` : String(n)); function fmtDur(ms) { if (ms == null || !Number.isFinite(ms)) return '—'; const s = Math.round(ms / 1000); const h = Math.floor(s / 3600), m = Math.floor((s % 3600) / 60), sec = s % 60; return h ? `${h} h ${m} min` : m ? `${m} min ${sec} s` : `${sec} s`; } const shortTime = (t) => t.replace(/^00:/, '').replace(/,(\d)\d\d$/, '.$1'); const visibleLen = (s) => s.replace(/<[^>]+>|\{\\[^}]*\}/g, '').replace(/\n/g, ' ').length; const debounce = (fn, ms) => { let t; return (...a) => { clearTimeout(t); t = setTimeout(() => fn(...a), ms); }; }; let toastTimer; function toast(msg, err = false) { const t = $('#toast'); t.textContent = msg; t.className = 'toast' + (err ? ' err' : ''); t.hidden = false; clearTimeout(toastTimer); toastTimer = setTimeout(() => { t.hidden = true; }, err ? 7000 : 3500); } async function busy(btn, fn) { btn.classList.add('busy'); btn.disabled = true; try { return await fn(); } finally { btn.classList.remove('busy'); btn.disabled = false; } } function langLabel(code) { const l = S.meta?.languages.find((x) => x.code === code); return l ? l.namePl : code; } // ---------------------------------------------------------------- persistence function readValue(id) { const el = document.getElementById(id); if (!el) return undefined; if (el.type === 'checkbox') return el.checked; return el.value; } function writeValue(id, v) { const el = document.getElementById(id); if (!el || v === undefined || v === null) return; if (el.type === 'checkbox') el.checked = !!v; else el.value = v; } function collectSettings() { const s = {}; for (const id of SETTING_IDS) s[id] = readValue(id); for (const k of ['contextLength', 'numGpu', 'evalBatchSize', 'topK', 'seed']) s[k] = s[k] === '' ? undefined : Number(s[k]); for (const k of ['temperature', 'topP', 'minP', 'repeatPenalty']) s[k] = s[k] === '' ? undefined : Number(s[k]); if (s.gpuRatio === '') s.gpuRatio = undefined; return s; } function collectOptions() { const o = {}; for (const id of OPTION_IDS) o[id] = readValue(id); for (const k of ['batchSize', 'contextBefore', 'contextAfter', 'maxLineLength', 'concurrency']) o[k] = Number(o[k]) || 0; o.batchSize ||= 1; o.concurrency ||= 1; // Dedicated MT models need an explicit source language — use the detected one. const prof = effectiveProfile(); if (o.source === 'auto' && S.meta.profiles[prof]?.needsSource && S.file?.detectedLanguage) o.source = S.file.detectedLanguage; return o; } function engineConfig() { const c = { kind: S.engine, baseUrl: $('#baseUrl').value.trim() || S.meta.engines[S.engine].baseUrl }; if (S.engine === 'openai') { c.apiKey = $('#apiKey').value.trim() || undefined; c.structuredOutput = $('#structuredOutput').checked; const extra = $('#extraBody').value.trim(); if (extra) { try { c.extraBody = JSON.parse(extra); } catch { throw new Error('Pole „Dodatkowe pola żądania” nie jest poprawnym JSON-em.'); } } } return c; } function saveSettings() { const cur = loadSaved(); cur.engine = S.engine; cur.engineCfg ||= {}; cur.engineCfg[S.engine] = { baseUrl: $('#baseUrl').value.trim(), apiKey: $('#apiKey').value, structuredOutput: $('#structuredOutput').checked, extraBody: $('#extraBody').value }; cur.model ||= {}; if (S.model) cur.model[S.engine] = S.model; cur.settings = collectSettingsRaw(); cur.options = Object.fromEntries(OPTION_IDS.map((id) => [id, readValue(id)])); cur.exp = { format: $('#exportFormat').value, eol: $('#exportEol').value, bom: $('#exportBom').checked }; try { localStorage.setItem(LS_SETTINGS, JSON.stringify(cur)); } catch { /* storage unavailable */ } } function collectSettingsRaw() { return Object.fromEntries(SETTING_IDS.map((id) => [id, readValue(id)])); } function loadSaved() { try { return JSON.parse(localStorage.getItem(LS_SETTINGS)) || {}; } catch { return {}; } } function workKey() { if (!S.file) return null; const sig = S.file.cues.slice(0, 5).map((c) => c.text).join('|'); let h = 0; for (let i = 0; i < sig.length; i++) h = (h * 31 + sig.charCodeAt(i)) | 0; return `${LS_WORK}${S.file.name}:${S.file.cues.length}:${h}:${$('#target').value}`; } const saveWork = debounce(() => { const k = workKey(); if (!k) return; try { localStorage.setItem(k, JSON.stringify({ tr: S.tr, status: S.status, at: Date.now() })); } catch { /* quota */ } }, 800); function loadWork() { const k = workKey(); if (!k) return; try { const w = JSON.parse(localStorage.getItem(k)); S.tr = w?.tr || {}; S.status = w?.status || {}; } catch { S.tr = {}; S.status = {}; } } // ---------------------------------------------------------------- init async function init() { S.meta = await api('/api/meta'); const langOpts = S.meta.languages.map((l) => ``).join(''); $('#source').innerHTML = `${langOpts}`; $('#target').innerHTML = langOpts; $('#target').value = 'pl'; const kv = S.meta.kvTypes.map((t) => ``).join(''); $('#kvCacheK').innerHTML = kv; $('#kvCacheV').innerHTML = kv; $('#kvCacheK').value = 'f16'; $('#kvCacheV').value = 'f16'; $('#contextLength').value = 8192; const saved = loadSaved(); S.engine = saved.engine || 'lmstudio'; S.engineCfg = saved.engineCfg || {}; for (const [id, v] of Object.entries(saved.settings || {})) writeValue(id, v); for (const [id, v] of Object.entries(saved.options || {})) if (id !== 'profile') writeValue(id, v); if (saved.exp) { writeValue('exportFormat', saved.exp.format); writeValue('exportEol', saved.exp.eol); writeValue('exportBom', saved.exp.bom); } bindUi(); selectEngine(S.engine, true); syncCtxRange(); restoreLastFile(); connect().catch(() => {}); } function bindUi() { document.querySelectorAll('#engineSeg button').forEach((b) => b.addEventListener('click', () => selectEngine(b.dataset.kind))); $('#connectBtn').addEventListener('click', () => busy($('#connectBtn'), () => connect(true))); $('#baseUrl').addEventListener('keydown', (e) => { if (e.key === 'Enter') $('#connectBtn').click(); }); $('#refreshModels').addEventListener('click', () => busy($('#refreshModels'), () => loadModels(true))); $('#modelSelect').addEventListener('change', (e) => selectModel(e.target.value)); $('#profile').addEventListener('change', () => { renderProfile(); saveSettings(); }); $('#ctxRange').addEventListener('input', () => { $('#contextLength').value = ctxSteps()[Number($('#ctxRange').value)]; onSettingsChange(); }); $('#contextLength').addEventListener('change', () => { syncCtxRange(); onSettingsChange(); }); for (const id of ['kvCacheK', 'kvCacheV', 'flashAttention', 'gpuRatio', 'numGpu', 'evalBatchSize', 'unloadOthers']) document.getElementById(id).addEventListener('change', onSettingsChange); for (const id of ['temperature', 'topP', 'topK', 'minP', 'repeatPenalty', 'seed', 'disableThinking', ...OPTION_IDS.filter((x) => x !== 'profile'), 'apiKey', 'structuredOutput', 'extraBody', 'exportFormat', 'exportEol', 'exportBom']) { document.getElementById(id).addEventListener('change', saveSettings); } $('#target').addEventListener('change', () => { if (S.file) { loadWork(); renderTable(); } }); $('#maxLineLength').addEventListener('change', () => refreshAllFlags()); $('#songs').addEventListener('change', () => { if (S.file) { renderFile(); refreshAllFlags(); applyFilter(); } }); $('#applyRecommended').addEventListener('click', applyRecommended); $('#loadBtn').addEventListener('click', () => busy($('#loadBtn'), loadModel)); $('#unloadBtn').addEventListener('click', () => busy($('#unloadBtn'), unloadModel)); $('#pullBtn').addEventListener('click', () => startPull()); $('#pullName').addEventListener('keydown', (e) => { if (e.key === 'Enter') startPull(); }); // file const drop = $('#drop'); $('#pickFile').addEventListener('click', (e) => { e.stopPropagation(); $('#fileInput').click(); }); drop.addEventListener('click', () => $('#fileInput').click()); $('#changeFile').addEventListener('click', () => $('#fileInput').click()); $('#fileInput').addEventListener('change', (e) => { if (e.target.files[0]) openFile(e.target.files[0]); e.target.value = ''; }); for (const ev of ['dragenter', 'dragover']) document.addEventListener(ev, (e) => { e.preventDefault(); drop.classList.add('drag'); }); for (const ev of ['dragleave', 'drop']) document.addEventListener(ev, (e) => { e.preventDefault(); if (ev === 'drop' || e.target === drop) drop.classList.remove('drag'); }); document.addEventListener('drop', (e) => { const f = e.dataTransfer?.files?.[0]; if (f) openFile(f); }); $('#encoding').addEventListener('change', () => reparse()); $('#startBtn').addEventListener('click', () => startJob(false)); $('#resumeBtn').addEventListener('click', () => startJob(true)); $('#stopBtn').addEventListener('click', stopJob); $('#downloadBtn').addEventListener('click', download); $('#onlyFlagged').addEventListener('change', applyFilter); $('#search').addEventListener('input', debounce(applyFilter, 150)); } // ---------------------------------------------------------------- engine function selectEngine(kind, initial = false) { if (!initial) saveSettings(); S.engine = kind; document.body.dataset.engine = kind; document.querySelectorAll('#engineSeg button').forEach((b) => b.classList.toggle('active', b.dataset.kind === kind)); const cfg = S.engineCfg[kind] || loadSaved().engineCfg?.[kind] || {}; $('#baseUrl').value = cfg.baseUrl || S.meta.engines[kind].baseUrl; $('#baseUrl').placeholder = S.meta.engines[kind].baseUrl; $('#apiKey').value = cfg.apiKey || ''; $('#structuredOutput').checked = cfg.structuredOutput !== false; $('#extraBody').value = cfg.extraBody || ''; S.connected = false; S.models = []; S.model = null; S.modelInfo = null; setPill('', 'niepołączony'); $('#modelSelect').innerHTML = ''; $('#modelSelect').disabled = true; $('#modelDetails').innerHTML = ''; $('#engineHint').textContent = ''; $('#loadBtn').textContent = kind === 'ollama' ? 'Załaduj (rozgrzej)' : 'Załaduj model'; renderEngineNotes(); renderPullUi(); renderEstimate(null); if (!initial) { saveSettings(); connect().catch(() => {}); } } function renderEngineNotes(extra = []) { const hints = [...(S.meta.engines[S.engine].notes || []), ...extra]; const code = (h) => escapeHtml(h).replace(/(OLLAMA_FLASH_ATTENTION=1 OLLAMA_KV_CACHE_TYPE=q8_0 ollama serve|setx OLLAMA_\w+ \w+|OLLAMA_\w+=?\w*|launchctl setenv [^;—]+|-c \d+[^,]*|--[\w-]+ [\w.]+)/g, '$1'); $('#kvServerHint').innerHTML = hints.map(code).join('
'); } function setPill(cls, text) { $('#enginePill').className = 'engine-pill ' + cls; $('#enginePillText').textContent = text; } async function connect(manual = false) { try { const st = await api('/api/engine/status', { engine: engineConfig() }); S.connected = true; S.caps = st.capabilities; setPill('ok', `${S.meta.engines[S.engine].label}${st.version ? ' ' + st.version : ''}`); renderEngineNotes(S.engine === 'lmstudio' && !st.sdk ? ['Brak pakietu @lmstudio/sdk — ładowanie bez kwantyzacji KV-cache (uruchom npm install).'] : []); $('#engineHint').textContent = ''; saveSettings(); await loadModels(); attachPulls().catch(() => {}); } catch (e) { S.connected = false; setPill('err', 'brak połączenia'); $('#engineHint').textContent = e.message; if (manual) toast(e.message, true); throw e; } } async function loadModels(keepSelection = true) { const { models } = await api('/api/engine/models', { engine: engineConfig() }); S.models = models; renderPullUi(); const sel = $('#modelSelect'); if (!models.length) { sel.innerHTML = ''; sel.disabled = true; return; } sel.disabled = false; sel.innerHTML = models.map((m) => { const bits = [m.params, m.quant, m.sizeBytes ? fmtGB(m.sizeBytes) : null].filter(Boolean).join(' · '); const tags = [m.loaded?.length ? '● ' : '', m.profile !== 'generic' ? '[MT] ' : ''].join(''); return ``; }).join(''); const saved = loadSaved().model?.[S.engine]; const want = (keepSelection && S.model && models.find((m) => m.id === S.model)?.id) || (saved && models.find((m) => m.id === saved)?.id) || models.find((m) => m.loaded?.length)?.id || models[0].id; sel.value = want; await selectModel(want); } function currentModel() { return S.models.find((m) => m.id === S.model) || null; } async function selectModel(id) { S.model = id; saveSettings(); const m = currentModel(); const det = $('#modelDetails'); det.innerHTML = 'wczytuję szczegóły…'; try { S.modelInfo = await api('/api/engine/model-info', { engine: engineConfig(), model: id }); } catch (e) { S.modelInfo = null; det.innerHTML = `${escapeHtml(e.message)}`; } const info = S.modelInfo || {}; const a = info.arch; const parts = []; if (a) { parts.push(`arch ${escapeHtml(a.name)}`, `${a.layers} warstw`); const kvh = Array.isArray(a.headsKv) ? `${Math.min(...a.headsKv.filter(Boolean))}–${Math.max(...a.headsKv)}` : a.headsKv; parts.push(`KV heads ${kvh} × ${a.keyLen}`); if (a.slidingWindow) parts.push('SWA'); if (a.fullAttnInterval) parts.push('hybrydowy'); if (a.kvLoraRank) parts.push('MLA'); } else if (m?.family) parts.push(`${escapeHtml(m.family)}`); const maxCtx = info.maxContext || m?.maxContext; if (maxCtx) parts.push(`maks. kontekst ${fmtCtx(maxCtx)}`); if (info.capabilities?.thinking) parts.push('reasoning'); if (m?.loaded?.length) parts.push('załadowany'); det.innerHTML = parts.join(''); // profile select const detected = info.profile || m?.profile || 'generic'; $('#profile').innerHTML = `` + Object.entries(S.meta.profiles).map(([k, p]) => ``).join(''); $('#profile').value = 'auto'; renderProfile(); // context: clamp to model max; prefer the loaded context const loadedCtx = m?.loaded?.[0]?.contextLength; if (loadedCtx && S.engine !== 'ollama') $('#contextLength').value = loadedCtx; if (maxCtx && Number($('#contextLength').value) > maxCtx) $('#contextLength').value = maxCtx; syncCtxRange(); renderLoaded(); updateEstimate(); } function effectiveProfile() { const v = $('#profile').value; if (v && v !== 'auto') return v; return S.modelInfo?.profile || currentModel()?.profile || 'generic'; } function renderProfile() { const p = S.meta.profiles[effectiveProfile()]; const notes = []; if (p.note) notes.push(p.note); if (p.needsSource) notes.push('Wymaga języka źródłowego (użyję wykrytego, jeśli wybrano „automatycznie”).'); if (!p.modes.includes('json')) notes.push('Ten model tłumaczy po jednej linii (bez partii) — wolniej, ale zgodnie z jego formatem.'); $('#profileNote').textContent = notes.join(' '); $('#applyRecommended').hidden = !p.recommended; } function applyRecommended() { const r = S.meta.profiles[effectiveProfile()].recommended || {}; const map = { temperature: 'temperature', top_p: 'topP', top_k: 'topK', repeat_penalty: 'repeatPenalty', min_p: 'minP' }; for (const [k, v] of Object.entries(r)) writeValue(map[k], v); saveSettings(); toast('Zastosowano zalecane parametry.'); } // ---------------------------------------------------------------- context & memory function ctxSteps() { const max = S.modelInfo?.maxContext || currentModel()?.maxContext || 262144; const steps = CTX_STEPS.filter((s) => s <= max); if (!steps.includes(max) && max < 262144 * 2) steps.push(max); return steps; } function syncCtxRange() { const steps = ctxSteps(); const v = Number($('#contextLength').value) || 8192; let idx = 0; steps.forEach((s, i) => { if (Math.abs(s - v) < Math.abs(steps[idx] - v)) idx = i; }); $('#ctxRange').max = steps.length - 1; $('#ctxRange').value = idx; $('#ctxLabel').textContent = `${fmtInt(v)} tok.`; } function onSettingsChange() { syncCtxRange(); saveSettings(); renderLoaded(); updateEstimate(); } let estSeq = 0; const updateEstimate = debounce(async () => { if (!S.connected || !S.model) return renderEstimate(null); const seq = ++estSeq; try { const r = await api('/api/engine/estimate', { engine: engineConfig(), model: S.model, settings: collectSettings(), sizeBytes: currentModel()?.sizeBytes }); if (seq === estSeq) renderEstimate(r); } catch (e) { if (seq === estSeq) { renderEstimate(null); $('#vramLines').textContent = e.message; } } }, 250); function renderEstimate(r) { const box = $('#vram'); const lines = []; if (!r) { $('#vramTotal').textContent = '—'; for (const id of ['vW', 'vKV', 'vC']) document.getElementById(id).textContent = '—'; box.querySelector('.seg-w').style.width = box.querySelector('.seg-kv').style.width = box.querySelector('.seg-c').style.width = '0'; box.querySelector('.limit').style.display = 'none'; $('#vramLines').innerHTML = ''; box.classList.remove('over'); return; } const o = r.own; const total = r.engine?.total ?? o.total; const kvAll = o.kv + (o.recurrent || 0); const scale = Math.max(r.budget || 0, total, o.total) * 1.08 || 1; // If the engine gives its own (more reliable) total, scale our breakdown to match it. const k = r.engine?.total ? r.engine.total / o.total : 1; box.querySelector('.seg-w').style.width = `${(o.weights * k / scale) * 100}%`; box.querySelector('.seg-kv').style.width = `${(kvAll * k / scale) * 100}%`; box.querySelector('.seg-c').style.width = `${(o.compute * k / scale) * 100}%`; const lim = box.querySelector('.limit'); if (r.budget) { lim.style.display = 'block'; lim.style.left = `${(r.budget / scale) * 100}%`; } else lim.style.display = 'none'; $('#vramTotal').textContent = fmtGB(total); $('#vW').textContent = fmtGB(o.weights); $('#vKV').textContent = fmtGB(kvAll); $('#vC').textContent = fmtGB(o.compute); const over = r.budget && total > r.budget; box.classList.toggle('over', !!over); if (r.engine) { lines.push(`Szacunek LM Studio: ${fmtGB(r.engine.total)} (model ${fmtGB(r.engine.model)} + kontekst ${fmtGB(r.engine.context)})${r.engine.passesGuardrails === false ? ' — nie przejdzie zabezpieczeń LM Studio' : ''}`); lines.push(`Własny szacunek: ${fmtGB(o.total)}`); } else if (r.engineError) lines.push(`Szacunek LM Studio niedostępny: ${escapeHtml(r.engineError)}`); if (o.perTokenKv) lines.push(`KV-cache: ${(o.perTokenKv / 1024).toFixed(1)} KB/token`); const g = r.system?.gpus?.[0]; if (g) lines.push(`${escapeHtml(g.name)}: dostępne dla modelu ≈ ${fmtGB(r.budget)}${g.unified ? ` z ${fmtGB(r.system.totalRam)} RAM` : ''}`); else lines.push(`RAM: ${fmtGB(r.system?.totalRam)} (nie wykryto GPU)`); if (over) lines.push('Może się nie zmieścić — zmniejsz kontekst lub włącz kwantyzację KV-cache.'); if (r.maxContextFit) lines.push(`Największy kontekst, który się zmieści (wg własnego szacunku): ≈ ${fmtInt(Math.min(r.maxContextFit, r.maxContext || Infinity))} tok.`); for (const n of o.notes || []) lines.push(escapeHtml(n)); if (S.engine !== 'lmstudio') { const s = collectSettings(); if (s.kvCacheK !== 'f16' || s.kvCacheV !== 'f16') lines.push(S.engine === 'ollama' ? 'KV-cache w Ollamie zmienia się zmienną środowiskową serwera (patrz wyżej) — tu tylko do szacunku.' : 'KV-cache ustawia się argumentami serwera — tu tylko do szacunku.'); } $('#vramLines').innerHTML = lines.map((l) => `
${l}
`).join(''); } function renderLoaded() { const m = currentModel(); const el = $('#loadedInfo'); const inst = m?.loaded?.[0]; $('#unloadBtn').disabled = !inst; if (!m) { el.textContent = ''; return; } if (!inst) { el.innerHTML = S.engine === 'lmstudio' ? 'Model nie jest załadowany — zostanie załadowany z powyższymi ustawieniami przy starcie tłumaczenia.' : S.engine === 'ollama' ? 'Model nie jest załadowany — Ollama załaduje go przy pierwszym zapytaniu.' : ''; return; } const want = Number($('#contextLength').value); const bits = [`kontekst ${fmtInt(inst.contextLength)}`]; if (S.engine === 'lmstudio') { const a = inst.applied || S.applied[m.id]; const c = inst.config || {}; if (c.flash_attention !== undefined) bits.push(`FA ${c.flash_attention ? 'wł.' : 'wył.'}`); if (a) bits.push(`KV ${a.k_cache}/${a.v_cache}`); if (c.parallel) bits.push(`równoległość ${c.parallel}`); } if (S.engine === 'ollama' && inst.sizeVram != null) { bits.push(`Ollama raportuje: ${fmtGB(inst.sizeVram)} na GPU${inst.size > inst.sizeVram ? ` + ${fmtGB(inst.size - inst.sizeVram)} w RAM (część modelu na CPU — wolniej!)` : ''}`); // Some Ollama versions under-report (e.g. leave out part of the KV cache) — say so instead of trusting it blindly. if (m.sizeBytes && inst.size < m.sizeBytes * 0.8) bits.push('ta wartość wygląda na zaniżoną'); } let warn = ''; if (want && inst.contextLength && want !== inst.contextLength) { warn = S.engine === 'lmstudio' ? `
załadowany z innym kontekstem kliknij „Załaduj model”, by przeładować z ${fmtInt(want)}.` : S.engine === 'ollama' ? '
Ollama przeładuje model z nowym num_ctx przy pierwszym zapytaniu.' : ''; } el.innerHTML = `Załadowany: ${bits.join(' · ')}${warn}`; } async function loadModel() { if (!S.model) return; try { const r = await api('/api/engine/load', { engine: engineConfig(), model: S.model, settings: collectSettings() }); if (r.applied) S.applied[S.model] = r.applied; if (r.warning) toast(r.warning, true); else toast('Model załadowany.'); await loadModels(); } catch (e) { toast(e.message, true); } } async function unloadModel() { const inst = currentModel()?.loaded?.[0]; if (!inst) return; try { await api('/api/engine/unload', { engine: engineConfig(), instanceId: inst.id }); delete S.applied[S.model]; toast('Model zwolniony.'); await loadModels(); } catch (e) { toast(e.message, true); } } // ---------------------------------------------------------------- file const LS_FILE = 'srt-tr:lastfile:v1'; async function openFile(file) { if (S.job) return toast('Najpierw zatrzymaj bieżące tłumaczenie.', true); const buf = await file.arrayBuffer(); S.file = { name: file.name, buf }; $('#encoding').value = 'auto'; await reparse(); // Remember the file so a page reload doesn't lose the work (subtitle files are small). if (buf.byteLength < 3 * 2 ** 20) { try { let bin = ''; const bytes = new Uint8Array(buf); for (let i = 0; i < bytes.length; i += 0x8000) bin += String.fromCharCode(...bytes.subarray(i, i + 0x8000)); localStorage.setItem(LS_FILE, JSON.stringify({ name: file.name, b64: btoa(bin) })); } catch { /* quota */ } } } async function restoreLastFile() { try { const f = JSON.parse(localStorage.getItem(LS_FILE)); if (!f?.b64) return; const bin = atob(f.b64); const bytes = new Uint8Array(bin.length); for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i); S.file = { name: f.name, buf: bytes.buffer }; await reparse(); } catch { /* nothing to restore */ } } async function reparse() { if (!S.file) return; try { const enc = $('#encoding').value; const r = await api('/api/srt/parse', S.file.buf, { raw: true, query: `?encoding=${encodeURIComponent(enc)}` }); Object.assign(S.file, r); if (enc === 'auto') $('#encoding').value = ['utf-8-bom', 'utf-16le', 'utf-16be'].includes(r.encoding) ? 'utf-8' : r.encoding; loadWork(); renderFile(); renderTable(); } catch (e) { toast(e.message, true); } } function renderFile() { const f = S.file; $('#drop').hidden = true; $('#fileBar').hidden = false; $('#tableTools').hidden = false; $('#tableWrap').hidden = false; $('#fileName').textContent = f.name; const tokens = Math.round(f.stats.chars / 3.3); const songFull = f.cues.filter((c) => c.song === 'full').length; const songPart = f.cues.filter((c) => c.song === 'partial').length; $('#fileStats').textContent = `${fmtInt(f.stats.cues)} napisów · ${fmtDur(f.stats.durationMs)} · ~${fmtInt(tokens)} tok. tekstu` + (f.detectedLanguage ? ` · język: ${langLabel(f.detectedLanguage)}` : '') + (songFull + songPart ? ` · ♪ piosenki: ${songFull}${songPart ? ` (+${songPart} mieszanych)` : ''}` : ''); $('#songCount').textContent = songFull + songPart ? `— w pliku: ${songFull + songPart}` : '— brak w pliku'; const autoOpt = $('#source').querySelector('option[value=auto]'); autoOpt.textContent = f.detectedLanguage ? `automatycznie (wykryto: ${langLabel(f.detectedLanguage)})` : 'wykryj automatycznie'; updateButtons(); } function renderTable() { const body = $('#cueBody'); body.textContent = ''; S.rows.clear(); const frag = document.createDocumentFragment(); for (const c of S.file.cues) { const tr = document.createElement('tr'); tr.dataset.id = c.id; const tdId = document.createElement('td'); tdId.className = 'id'; tdId.textContent = c.id; const tdTime = document.createElement('td'); tdTime.className = 'time'; tdTime.textContent = `${shortTime(c.start)}\n${shortTime(c.end)}`; const tdSrc = document.createElement('td'); tdSrc.className = 'src'; tdSrc.textContent = c.text; const tdTr = document.createElement('td'); tdTr.className = 'tr'; tdTr.contentEditable = 'plaintext-only'; tdTr.spellcheck = true; tdTr.lang = $('#target').value; const flags = document.createElement('span'); flags.className = 'flags'; flags.contentEditable = 'false'; const tdAct = document.createElement('td'); const btn = document.createElement('button'); btn.className = 'rowbtn'; btn.title = 'Przetłumacz tę linię ponownie'; btn.textContent = '↻'; btn.addEventListener('click', () => retranslate(c.id, btn)); tdAct.append(btn); tdTr.addEventListener('focus', () => { tdTr.textContent = S.tr[c.id] || ''; tdTr.classList.remove('pending'); }); tdTr.addEventListener('blur', () => { const v = tdTr.innerText.replace(/\n+$/, '').trim(); if (v !== (S.tr[c.id] || '')) { if (v) { S.tr[c.id] = v; S.status[c.id] = 'edited'; } else { delete S.tr[c.id]; delete S.status[c.id]; } saveWork(); } renderCue(c.id); updateButtons(); }); tr.append(tdId, tdTime, tdSrc, tdTr, tdAct); frag.append(tr); S.rows.set(c.id, { tr, tdTr, flags, cue: c, btn }); } body.append(frag); for (const c of S.file.cues) renderCue(c.id); updateFlagCount(); applyFilter(); } function computeFlags(cue, text, status) { const f = []; if (status === 'error') return [['err', 'błąd']]; const songs = $('#songs').value; if (cue.song && songs !== 'translate') { if (songs === 'remove') return [['song', cue.song === 'full' ? '♪ zostanie usunięty' : '♪ linie piosenki zostaną usunięte']]; if (cue.song === 'full') return [['song', '♪ oryginał']]; } if (!text) return f; const src = visibleLen(cue.text), dst = visibleLen(text); const target = $('#target').value; if (src > 12 && text.trim() === cue.text.trim() && S.file.detectedLanguage !== target) f.push(['warn', 'bez zmian']); if (src > 15 && dst / src < 0.45) f.push(['warn', 'za krótkie?']); if (src > 8 && dst / src > 2.3) f.push(['warn', 'za długie?']); // Hedged gender/alternative forms ("byłeś/aś") that the source doesn't have. if (/\p{L}\/\p{L}/u.test(text.replace(/<[^>]+>/g, '')) && !/\p{L}\/\p{L}/u.test(cue.text)) f.push(['warn', 'warianty „/”']); const lines = text.split('\n'); if (lines.length > 2) f.push(['warn', `${lines.length} linie`]); const max = Number($('#maxLineLength').value) || 0; if (max && lines.some((l) => visibleLen(l) > max + 6)) f.push(['warn', 'długa linia']); const secs = (cue.endMs - cue.startMs) / 1000; if (secs > 0.3) { const cps = dst / secs; if (cps > 21) f.push(['warn', `${Math.round(cps)} zn./s`]); } return f; } function renderCue(id) { const row = S.rows.get(id); if (!row) return; const text = S.tr[id]; const status = S.status[id]; const { tdTr, tr, flags, cue } = row; if (document.activeElement !== tdTr) { tdTr.textContent = text || (status === 'error' ? '' : '…'); tdTr.classList.toggle('pending', !text); } tdTr.classList.toggle('edited', status === 'edited'); const fl = computeFlags(cue, text, status); row.flagged = fl.some(([k]) => k !== 'song'); tr.classList.toggle('flagged', fl.some(([k]) => k === 'warn')); tr.classList.toggle('err', status === 'error'); tr.classList.toggle('removed', cue.song === 'full' && $('#songs').value === 'remove'); flags.innerHTML = fl.map(([k, t]) => `${t}`).join(''); if (fl.length && document.activeElement !== tdTr) tdTr.append(flags); } function refreshAllFlags() { if (!S.file) return; for (const c of S.file.cues) renderCue(c.id); updateFlagCount(); } function updateFlagCount() { let n = 0; for (const r of S.rows.values()) if (r.flagged) n++; $('#flagCount').textContent = n ? String(n) : ''; } function applyFilter() { const only = $('#onlyFlagged').checked; const q = $('#search').value.trim().toLowerCase(); for (const [id, r] of S.rows) { let show = !only || r.flagged; if (show && q) show = r.cue.text.toLowerCase().includes(q) || (S.tr[id] || '').toLowerCase().includes(q); r.tr.hidden = !show; } } function missingCount() { if (!S.file) return 0; return S.file.cues.filter((c) => !S.tr[c.id]).length; } function updateButtons() { const running = !!S.job; const any = S.file && Object.keys(S.tr).length > 0; const missing = missingCount(); $('#startBtn').hidden = running; $('#stopBtn').hidden = !running; $('#startBtn').textContent = any ? 'Tłumacz od nowa' : 'Tłumacz'; $('#startBtn').classList.toggle('primary', !any || !missing); $('#resumeBtn').hidden = running || !any || !missing; $('#resumeBtn').classList.toggle('primary', any && missing > 0); $('#resumeBtn').textContent = `Dokończ brakujące (${missing})`; $('#encoding').disabled = running; } // ---------------------------------------------------------------- jobs function openEvents(jobId, handlers) { const es = new EventSource(`/api/jobs/${jobId}/events`); for (const [ev, fn] of Object.entries(handlers)) es.addEventListener(ev, (e) => fn(JSON.parse(e.data))); es.onerror = () => { /* EventSource reconnects automatically; the snapshot event resyncs */ }; return es; } function applyCue({ id, text, status }) { if (status === 'existing') return; if (S.status[id] === 'edited' && S.job?.onlyMissing) return; // never clobber manual edits if (text) S.tr[id] = text; else delete S.tr[id]; S.status[id] = status; renderCue(Number(id)); } async function startJob(onlyMissing) { if (!S.file) return toast('Najpierw wczytaj plik SRT.', true); if (!S.connected || !S.model) return toast('Połącz się z silnikiem i wybierz model.', true); let engine; try { engine = engineConfig(); } catch (e) { return toast(e.message, true); } if (!onlyMissing) { S.tr = {}; S.status = {}; renderTable(); } const options = { ...collectOptions(), profile: $('#profile').value || 'auto' }; const payload = { engine, model: S.model, settings: collectSettings(), options, cues: S.file.cues.map((c) => ({ id: c.id, text: c.text })), existing: onlyMissing ? S.tr : {}, }; try { const r = await api('/api/jobs', payload); S.job = { id: r.id, onlyMissing, started: Date.now() }; $('#logBox').hidden = false; $('#log').textContent = ''; const pb = $('#progressBox'); pb.hidden = false; pb.className = 'progress'; updateButtons(); S.job.tick = setInterval(() => { if (S.job?.lastStats) renderProgress(S.job.lastStats, 'running'); }, 1000); S.job.es = openEvents(r.id, { snapshot: (s) => { for (const [id, v] of Object.entries(s.results)) applyCue({ id: Number(id), ...v }); $('#log').textContent = ''; s.log.forEach(addLog); renderProgress(s.stats, s.state); }, cues: (list) => { list.forEach(applyCue); updateFlagCount(); saveWork(); }, progress: (st) => renderProgress(st, 'running'), log: addLog, state: ({ state, error, stats }) => { renderProgress(stats, state); if (state !== 'running') finishJob(state, error); }, }); } catch (e) { toast(e.message, true); } } function finishJob(state, error) { if (!S.job) return; S.job.es?.close(); clearInterval(S.job.tick); S.job = null; saveWork(); updateButtons(); updateFlagCount(); applyFilter(); if (state === 'done') toast('Tłumaczenie zakończone.'); else if (state === 'error') toast(`Błąd: ${error}`, true); else if (state === 'cancelled') toast('Zatrzymano. Możesz dokończyć brakujące linie później.'); // Refresh model list (LM Studio may have auto-loaded the model). loadModels().catch(() => {}); } async function stopJob() { if (!S.job) return; try { await api(`/api/jobs/${S.job.id}/cancel`, {}); } catch (e) { toast(e.message, true); } } function renderProgress(st, state) { if (!st) return; if (S.job && state === 'running') S.job.lastStats = st; const pb = $('#progressBox'); pb.className = 'progress' + (state === 'done' ? ' done' : state === 'error' ? ' error' : ''); const pct = st.total ? (st.done / st.total) * 100 : 0; $('#progressFill').style.width = `${pct.toFixed(1)}%`; const elapsed = (st.finishedAt && state !== 'running' ? st.finishedAt : Date.now()) - (st.startedAt || Date.now()); const work = st.done - (st.copied || 0); const eta = work > 0 && state === 'running' ? (elapsed / work) * (st.total - st.done) : null; const items = [ `${fmtInt(st.done)} / ${fmtInt(st.total)} (${pct.toFixed(0)}%)`, `czas ${fmtDur(elapsed)}`, eta != null ? `pozostało ≈ ${fmtDur(eta)}` : '', st.tokPerSec ? `${st.tokPerSec.toFixed(1)} tok/s` : '', `zapytań ${fmtInt(st.requests)}`, st.promptTokens ? `tokeny we/wy ${fmtInt(st.promptTokens)} / ${fmtInt(st.completionTokens)}` : '', st.splits ? `podziałów partii ${st.splits}` : '', st.fallbacks ? `pojedynczo ${st.fallbacks}` : '', st.songs ? `♪ pominięto ${st.songs}` : '', st.failed ? `błędów ${st.failed}` : '', ]; $('#progressStats').innerHTML = items.filter(Boolean).join(''); } function addLog(l) { const d = document.createElement('div'); d.className = l.level; d.textContent = `${new Date(l.t).toLocaleTimeString('pl-PL')} ${l.msg}`; const log = $('#log'); log.append(d); log.scrollTop = log.scrollHeight; $('#logCount').textContent = `(${log.children.length})`; } async function retranslate(id, btn) { if (S.job) return toast('Poczekaj na koniec tłumaczenia.', true); if (!S.connected || !S.model) return toast('Połącz się z silnikiem i wybierz model.', true); if (S.rowJobs.has(id)) return; btn.classList.add('busy'); try { const options = { ...collectOptions(), profile: $('#profile').value || 'auto', concurrency: 1 }; // A higher temperature gives a different variant when retrying. const settings = collectSettings(); if (S.tr[id]) settings.temperature = Math.max(0.5, Number(settings.temperature) || 0); const r = await api('/api/jobs', { engine: engineConfig(), model: S.model, settings, options, cues: S.file.cues.map((c) => ({ id: c.id, text: c.text })), existing: S.tr, onlyIds: [id], }); await new Promise((resolve) => { const es = openEvents(r.id, { cues: (list) => list.forEach((c) => { if (c.id === id && c.status !== 'existing') { S.tr[id] = c.text; S.status[id] = c.status; renderCue(id); } }), log: (l) => { if (l.level === 'error') toast(l.msg, true); }, state: ({ state }) => { if (state !== 'running') { es.close(); resolve(); } }, snapshot: (s) => { const c = s.results[id]; if (c && c.status !== 'existing') { S.tr[id] = c.text; S.status[id] = c.status; renderCue(id); } if (s.state !== 'running' && s.state !== 'pending') { es.close(); resolve(); } }, }); S.rowJobs.set(id, es); }); saveWork(); updateFlagCount(); } catch (e) { toast(e.message, true); } finally { S.rowJobs.delete(id); btn.classList.remove('busy'); } } // ---------------------------------------------------------------- export async function download() { if (!S.file) return; const missing = missingCount(); const eolSel = $('#exportEol').value; try { const r = await api('/api/srt/build', { cues: S.file.cues, translations: S.tr, format: $('#exportFormat').value, eol: eolSel === 'orig' ? S.file.eol : eolSel, bom: $('#exportBom').checked, songs: $('#songs').value, }); const blob = new Blob([r.srt], { type: 'application/x-subrip;charset=utf-8' }); const a = document.createElement('a'); const base = S.file.name.replace(/\.srt$/i, '').replace(/\.[a-z]{2}(-[A-Za-z]{2})?$/, ''); a.download = `${base}.${$('#target').value}${$('#exportFormat').value === 'bilingual' ? '.dual' : ''}.srt`; a.href = URL.createObjectURL(blob); a.click(); setTimeout(() => URL.revokeObjectURL(a.href), 2000); const msgs = []; if (r.removed) msgs.push(`usunięto ${r.removed} napisów z piosenkami`); const songsKept = $('#songs').value !== 'translate' ? S.file.cues.filter((c) => c.song === 'full' && !S.tr[c.id]).length : 0; if (missing - songsKept > 0) msgs.push(`${missing - songsKept} linii bez tłumaczenia — zapisano oryginał`); if (msgs.length) toast(`Zapisano ${r.cues} napisów: ${msgs.join(', ')}.`); } catch (e) { toast(e.message, true); } } // ---------------------------------------------------------------- model downloads // Suggestions are only filled into the input — the download starts with the button. const PULL_SUGGESTIONS = { ollama: [ { name: 'translategemma:4b', label: 'TranslateGemma 4B', size: 3.3, tag: 'MT' }, { name: 'translategemma:12b', label: 'TranslateGemma 12B', size: 8.1, tag: 'MT' }, { name: 'hf.co/tencent/Hy-MT2-7B-GGUF:Q4_K_M', label: 'Hy-MT2 7B', size: 4.6, tag: 'MT' }, { name: 'hf.co/speakleash/Bielik-11B-v3.0-Instruct-GGUF:Q4_K_M', label: 'Bielik 11B v3', size: 6.7, tag: 'PL' }, { name: 'hf.co/bartowski/EuroLLM-9B-Instruct-GGUF:Q4_K_M', label: 'EuroLLM 9B', size: 5.6 }, ], lmstudio: [ { name: 'https://huggingface.co/speakleash/Bielik-11B-v3.0-Instruct-GGUF', quant: 'Q4_K_M', label: 'Bielik 11B v3', size: 6.7, tag: 'PL' }, { name: 'https://huggingface.co/bartowski/EuroLLM-9B-Instruct-GGUF', quant: 'Q4_K_M', label: 'EuroLLM 9B', size: 5.6 }, { name: 'https://huggingface.co/tencent/Hy-MT2-7B-GGUF', quant: 'Q4_K_M', label: 'Hy-MT2 7B', size: 4.6, tag: 'MT' }, ], }; const PULL_PHASE = { starting: 'przygotowuję…', downloading: 'pobieram', verifying: 'sprawdzam sumę kontrolną…', finalizing: 'zapisuję…', paused: 'wstrzymane (w LM Studio)', done: 'gotowe', already_downloaded: 'już pobrany', }; const pullStreams = new Map(); function renderPullUi() { const kind = S.engine; $('#pullName').placeholder = kind === 'ollama' ? 'np. translategemma:12b albo hf.co/użytkownik/repo-GGUF:Q4_K_M' : 'np. google/gemma-3-12b albo link do Hugging Face'; $('#pullHint').innerHTML = kind === 'ollama' ? 'Nazwy z ollama.com/search albo dowolne repozytorium GGUF z Hugging Face (hf.co/…:KWANTYZACJA). Przerwane pobieranie wznowi się od miejsca przerwania.' : 'Model z katalogu LM Studio albo link do repozytorium GGUF na Hugging Face. Pobierania nie da się przerwać z aplikacji — zrobisz to w panelu Downloads w LM Studio.'; const budget = S.meta.system?.gpus?.[0]?.total; const have = new Set(S.models.map((m) => m.id)); $('#pullChips').innerHTML = (PULL_SUGGESTIONS[kind] || []).map((s, i) => { const tooBig = budget && s.size * 1e9 > budget * 0.92; const owned = have.has(s.name); const title = `${s.name}${s.quant ? ' · ' + s.quant : ''}${tooBig ? ' — może się nie zmieścić w pamięci GPU' : ''}`; return ``; }).join(''); $('#pullChips').querySelectorAll('.chip').forEach((b) => b.addEventListener('click', () => { const s = PULL_SUGGESTIONS[kind][Number(b.dataset.i)]; $('#pullName').value = s.name; $('#pullQuant').value = s.quant || ''; $('#pullName').focus(); })); } async function startPull() { const model = $('#pullName').value.trim(); if (!model) return toast('Podaj nazwę modelu do pobrania.', true); if (!S.connected) return toast('Najpierw połącz się z silnikiem.', true); try { const snap = await api('/api/pulls', { engine: engineConfig(), model, quantization: S.engine === 'lmstudio' ? $('#pullQuant').value.trim() || undefined : undefined }); $('#pullName').value = ''; watchPull(snap, S.models.map((m) => m.id)); } catch (e) { toast(e.message, true); } } /** Re-attach to downloads kept on the server (after a reload or engine switch). */ async function attachPulls() { const { pulls } = await api('/api/pulls'); for (const p of pulls) { const recent = Date.now() - (p.finishedAt || 0) < 60000; if (p.engineKind === S.engine && (!['done', 'cancelled'].includes(p.state) || recent)) watchPull(p); } } const PULL_TERMINAL = new Set(['done', 'cancelled']); /** One tile per download for its whole life; the SSE stream stays open until done/cancelled. */ function watchPull(snap, before) { renderPull(snap); if (before) S.pullBefore = { ...S.pullBefore, [snap.id]: before }; if (pullStreams.has(snap.id) || PULL_TERMINAL.has(snap.state)) return; const es = new EventSource(`/api/pulls/${snap.id}/events`); pullStreams.set(snap.id, es); let lastState = snap.state; es.addEventListener('progress', (e) => renderPull(JSON.parse(e.data))); es.addEventListener('state', async (e) => { const s = JSON.parse(e.data); renderPull(s); const changed = s.state !== lastState; lastState = s.state; if (PULL_TERMINAL.has(s.state)) { es.close(); pullStreams.delete(s.id); } if (!changed) return; if (s.state === 'done') { toast(s.note || `Pobrano: ${s.model}`); await loadModels().catch(() => {}); // Select the new model: same name (Ollama) or whatever appeared in the list (LM Studio). const was = S.pullBefore?.[s.id]; const fresh = S.models.find((m) => m.id === s.model || m.id === `${s.model}:latest`) || (was && S.models.find((m) => !was.includes(m.id))); if (fresh) { $('#modelSelect').value = fresh.id; await selectModel(fresh.id); } } else if (s.state === 'error') toast(s.error, true); else if (s.state === 'cancelled') setTimeout(() => document.querySelector(`.pull-item[data-id="${s.id}"]`)?.remove(), 6000); }); es.onerror = () => { /* EventSource reconnects by itself; the first event resyncs the tile */ }; } async function pullAction(id, action) { try { const s = await api(`/api/pulls/${id}/${action}`, {}); renderPull(s); if (action === 'resume' && !pullStreams.has(id)) watchPull(s); } catch (e) { toast(e.message, true); } } const PULL_BUTTONS = { pause: ['Wstrzymaj', 'Zatrzymaj pobieranie — pobrane części zostają, można wznowić'], resume: ['Wznów', 'Kontynuuj od miejsca wstrzymania'], retry: ['Ponów', 'Spróbuj jeszcze raz (od miejsca przerwania)'], cancel: ['Anuluj', 'Przerwij i usuń niedokończone pliki tego pobierania'], hide: ['Ukryj', 'Usuń kafelek z listy'], }; function renderPull(s) { let el = document.querySelector(`.pull-item[data-id="${s.id}"]`); if (!el) { el = document.createElement('div'); el.className = 'pull-item'; el.dataset.id = s.id; el.innerHTML = '
'; el.querySelector('.pull-actions').addEventListener('click', (e) => { const b = e.target.closest('button[data-act]'); if (!b) return; const act = b.dataset.act; if (act === 'hide') { el.remove(); return; } b.disabled = true; pullAction(s.id, act === 'retry' ? 'resume' : act); }); $('#pullList').prepend(el); $('#pullBox').open = true; } const p = s.progress || {}; const pct = p.total ? Math.min(100, (p.completed / p.total) * 100) : 0; el.className = `pull-item ${s.state}${s.state === 'running' && !p.total ? ' indeterminate' : ''}`; el.querySelector('.pull-name').textContent = s.model; el.querySelector('.bar > div').style.width = `${s.state === 'done' ? 100 : pct.toFixed(1)}%`; const size = (b) => (p.total < 2 ** 30 ? fmtSize(b) : fmtGB(b)); const bits = []; if (s.state === 'running') { bits.push(PULL_PHASE[p.phase] || p.status || '…'); if (p.total) bits.push(`${size(p.completed)} / ${fmtSize(p.total)} (${pct.toFixed(0)}%)`); if (p.bytesPerSec) bits.push(`${(p.bytesPerSec / 2 ** 20).toFixed(1)} MB/s`); if (p.etaSec != null && p.phase === 'downloading') bits.push(`zostało ~${fmtDur(p.etaSec * 1000)}`); if (!s.controls?.pause) bits.push('wstrzymasz lub anulujesz w LM Studio → Downloads'); } else if (s.state === 'paused') bits.push(s.note || 'wstrzymano'); else if (s.state === 'done') bits.push(s.note || `gotowe${p.total > 1 ? ` · ${fmtSize(p.total)}` : ''}`); else if (s.state === 'cancelled') bits.push(s.note || 'anulowano'); else if (s.state === 'error') bits.push(`błąd: ${s.error}`); el.querySelector('.pull-stats').textContent = bits.join(' · '); const can = s.controls || {}; const acts = { running: [can.pause && 'pause', can.cancel && 'cancel'], paused: ['resume', can.cancel && 'cancel'], error: ['retry', can.cancel ? 'cancel' : 'hide'], done: ['hide'], cancelled: ['hide'], }[s.state] || []; const key = `${s.state}:${acts.join(',')}`; const box = el.querySelector('.pull-actions'); if (box.dataset.key !== key) { box.dataset.key = key; box.innerHTML = acts.filter(Boolean).map((a) => ``).join(''); } } function escapeHtml(s) { return String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c])); } init().catch((e) => toast(`Błąd inicjalizacji: ${e.message}`, true));