Spaces:
Running
Running
Fix progress bar flicker and model-loading stall
Browse files71 unmodified lines72737475767721 unmodified lines99100101102103104105106107108109110111112113114115116117118119120121206 unmodified lines32832933033133233333433533633733833934034113 unmodified lines35535635735835936010 unmodified lines37137237337437537671 unmodified linestry { await clearCache(); } catch {}for (const m of ["florence", "qwen"]) { try { localStorage.removeItem(manifestKey(m)); } catch {} }storedModels.clear();$("storage-text").textContent = "Downloaded models removed from this device.";$("clear").hidden = true;});21 unmodified lines$("bar-text").textContent = text ?? "";}window.__timings = [];listeners.add((m) => {if (m.type === "timing") { window.__timings.push(m); console.debug("timing", m); }if (m.type === "file" && fileUrls[m.model]) fileUrls[m.model].add(`https://huggingface.co/${m.repo}/resolve/main/${m.file}`);if (m.type === "progress") {const mb = `${(m.loaded / 1e6).toFixed(0)} / ${(m.total / 1e6).toFixed(0)} MB`;bar(m.loaded / m.total, storedModels.has(m.model)? `Loading ${MODEL_NAMES[m.model]} from this device… ${mb}`: `Downloading ${MODEL_NAMES[m.model]}… ${mb} (only the first time)`);}if (m.type === "status" && m.status === "loading") bar(null, `Loading ${MODEL_NAMES[m.model]}…`);if (m.type === "status" && m.status === "ready") {writeManifest(m.model);navigator.storage?.persist?.().catch(() => {});bar(null, "");}if (m.type === "tile") bar(m.done / m.total, `Reading text: part ${m.done} of ${m.total}`);if (m.type === "token") $("ai").textContent += m.text;});206 unmodified lines$("text-card").hidden = !useOcr;$("results").hidden = false;// Load Qwen while OCR runs instead of afterwards (when both fit in memory).if (useVlm && useOcr && caps?.keepBoth) call("preload", { name: "qwen" }).catch(() => {});if (useOcr) {currentStep = S.ocr; step(S.ocr, "active");$("stop").hidden = false;const tiles = makeTiles(views);const results = await call("florence", { tiles: tiles.map(({ id, image }) => ({ id, image })) });state.texts = mergeOcr(tiles, results);findings.push(...ocrFindings(state.texts, img.width, img.height).map((f) => ({ ...f, layer: "ocr" })));renderFindings(findings);13 unmodified linesconst { system, prompt } = buildPrompt({ captions, findings, texts: state.texts, color, meta });$("ai-images").replaceChildren(...images.map((im) => toCanvas(im)));$("ai-prompt").textContent = prompt;const res = await call("qwen", { images, system, prompt, maxNewTokens: 450 });$("ai").textContent = res.text.trim();$("ai").dataset.looped = res.looped ? "1" : "";10 unmodified linesstep(currentStep, "failed");bar(null, `Couldn't finish "${currentStep}": ${err.message ?? err}`);} finally {$("stop").hidden = true;running = false;setInputs(true);71 unmodified lines7273747576777821 unmodified lines100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156206 unmodified lines36336436536636736836937037137237337437537637713 unmodified lines39139239339439539639739839940010 unmodified lines41141241341441541641741871 unmodified linestry { await clearCache(); } catch {}for (const m of ["florence", "qwen"]) { try { localStorage.removeItem(manifestKey(m)); } catch {} }storedModels.clear();readyModels.clear();$("storage-text").textContent = "Downloaded models removed from this device.";$("clear").hidden = true;});21 unmodified lines$("bar-text").textContent = text ?? "";}// One progress state that every source feeds, so the bar doesn't flicker// between Florence-2 loading, Qwen loading in the background and OCR.const loads = new Map(); // model -> { loaded, total }let ocrProgress = null; // { done, total } while text is being readlet phaseText = ""; // what the current step is doing, when nothing is loadinglet vlmActive = false; // the interpretation step has startedconst readyModels = new Set();const WRITING = "Qwen3-VL-2B is writing its interpretation…";const mb = (b) => Math.round(b / 1e6).toLocaleString();function loadText(m, l) {const where = storedModels.has(m) ? "Loading" : "Downloading";const bytes = l.total ? ` ${mb(l.loaded)} / ${mb(l.total)} MB` : "";const first = storedModels.has(m) ? "" : " (only the first time)";return `${where} ${MODEL_NAMES[m]}…${bytes}${first}`;}function renderProgress() {if (!running) return; // warm-up on page load reports in the caps line instead// OCR is the main bar once it has started; before that, a model that is// still loading (and that OCR is waiting for) is.if (ocrProgress && (ocrProgress.done > 0 || (readyModels.has("florence") && !loads.size))) {const bg = [...loads].map(([m, l]) => `${MODEL_NAMES[m]} is ${storedModels.has(m) ? "loading" : "downloading"} in the background${l.total ? ` (${Math.round((l.loaded / l.total) * 100)}%)` : ""}`);bar(ocrProgress.done / ocrProgress.total, [`Reading text: part ${ocrProgress.done} of ${ocrProgress.total}`, ...bg].join(" · "));} else if (loads.size) {let loaded = 0, total = 0;for (const l of loads.values()) { loaded += l.loaded; total += l.total; }bar(total ? loaded / total : 0, [...loads].map(([m, l]) => loadText(m, l)).join(" · "));} else if (ocrProgress) {bar(0, `Getting ${MODEL_NAMES.florence} ready…`); // about to report loading} else {bar(null, phaseText);}}window.__timings = [];listeners.add((m) => {if (m.type === "timing") { window.__timings.push(m); console.debug("timing", m); }if (m.type === "file" && fileUrls[m.model]) fileUrls[m.model].add(`https://huggingface.co/${m.repo}/resolve/main/${m.file}`);if (m.type === "status" && m.status === "loading") { loads.set(m.model, { loaded: 0, total: 0 }); renderProgress(); }if (m.type === "progress" && loads.has(m.model)) { loads.set(m.model, { loaded: m.loaded, total: m.total }); renderProgress(); }if (m.type === "status" && m.status === "unloaded") readyModels.delete(m.model);if (m.type === "status" && m.status === "ready") {readyModels.add(m.model);if (m.model === "qwen" && vlmActive) phaseText = WRITING;loads.delete(m.model);writeManifest(m.model);navigator.storage?.persist?.().catch(() => {});renderProgress();}if (m.type === "tile") { ocrProgress = { done: m.done, total: m.total }; renderProgress(); }if (m.type === "token") $("ai").textContent += m.text;});206 unmodified lines$("text-card").hidden = !useOcr;$("results").hidden = false;if (useOcr) {currentStep = S.ocr; step(S.ocr, "active");$("stop").hidden = false;const tiles = makeTiles(views);ocrProgress = { done: 0, total: tiles.length };renderProgress();const results = await call("florence", { tiles: tiles.map(({ id, image }) => ({ id, image })) });ocrProgress = null;renderProgress();state.texts = mergeOcr(tiles, results);findings.push(...ocrFindings(state.texts, img.width, img.height).map((f) => ({ ...f, layer: "ocr" })));renderFindings(findings);13 unmodified linesconst { system, prompt } = buildPrompt({ captions, findings, texts: state.texts, color, meta });$("ai-images").replaceChildren(...images.map((im) => toCanvas(im)));$("ai-prompt").textContent = prompt;vlmActive = true;// If Qwen still has to load, its loading line shows first and the// "writing" line follows once it's ready (no flash of the wrong text).if (readyModels.has("qwen")) { phaseText = WRITING; renderProgress(); }const res = await call("qwen", { images, system, prompt, maxNewTokens: 450 });$("ai").textContent = res.text.trim();$("ai").dataset.looped = res.looped ? "1" : "";10 unmodified linesstep(currentStep, "failed");bar(null, `Couldn't finish "${currentStep}": ${err.message ?? err}`);} finally {phaseText = "";vlmActive = false;$("stop").hidden = true;running = false;setInputs(true);
38 unmodified lines3940414243444546474849505152533 unmodified lines57585960616225 unmodified lines88899091929394108 unmodified lines20320420520620720820921021121221321421521621721821922022122222322422522622738 unmodified linesreturn { device, f16, keepBoth };}function progress(name) {const files = new Map();return (p) => {if (p.status === "initiate") post({ type: "file", model: name, file: p.file, repo: p.name });if (p.status === "progress" && p.total) {files.set(p.file, [p.loaded, p.total]);let loaded = 0, total = 0;for (const [l, t] of files.values()) { loaded += l; total += t; }post({ type: "progress", model: name, loaded, total });}};}3 unmodified linesif (name === except) continue;loaded.delete(name);await entry.model.dispose();}}25 unmodified lines: { embed_tokens: "q4", vision_encoder: "q4", decoder_model_merged: "q4" };model = await Qwen3VLForConditionalGeneration.from_pretrained(id, { device, dtype, progress_callback });}const processor = await AutoProcessor.from_pretrained(id, { progress_callback });const entry = { name, model, processor };loaded.set(name, entry);timing(`load ${name}`, loadStart);108 unmodified linesconst ready = setup();self.onmessage = async ({ data }) => {const { id, cmd, args } = data;try {const caps = await ready;if (cmd === "caps") return post({ id, result: caps });if (cmd === "stop") { stopRequested = true; return post({ id, result: true }); }if (cmd === "unload") {await unloadAll();return post({ id, result: true });}if (cmd === "preload") {// Warm-up only; never interrupts or replaces a model that's in use.if (!keepBoth && loaded.size) return post({ id, result: false });await load(args.name, caps.f16);return post({ id, result: true });}const fn = { florence, qwen }[cmd];stopRequested = false;const result = await fn({ ...args, f16: caps.f16 });post({ id, result });} catch (err) {console.error(err);38 unmodified lines39404142434445464748495051523 unmodified lines5657585960616225 unmodified lines88899091929394108 unmodified lines20320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523638 unmodified linesreturn { device, f16, keepBoth };}// Model weights report one whole-model total up front (progress_total), so// the bar never jumps backwards when the next file starts. The processor's// small files are only recorded (for the stored-files list), not shown.function progress(name, showBar = true) {return (p) => {if (p.status === "initiate") post({ type: "file", model: name, file: p.file, repo: p.name });if (showBar && p.status === "progress_total" && p.total) {post({ type: "progress", model: name, loaded: p.loaded, total: p.total });}};}3 unmodified linesif (name === except) continue;loaded.delete(name);await entry.model.dispose();post({ type: "status", model: name, status: "unloaded" });}}25 unmodified lines: { embed_tokens: "q4", vision_encoder: "q4", decoder_model_merged: "q4" };model = await Qwen3VLForConditionalGeneration.from_pretrained(id, { device, dtype, progress_callback });}const processor = await AutoProcessor.from_pretrained(id, { progress_callback: progress(name, false) });const entry = { name, model, processor };loaded.set(name, entry);timing(`load ${name}`, loadStart);108 unmodified linesconst ready = setup();// One model job at a time. ONNX Runtime stalls when a session is created// while another model is running in the same worker (seen as OCR stuck on// its first tile while Qwen3-VL loaded), so loads and runs are queued.let queue = Promise.resolve();function exclusive(job) {const run = queue.then(job, job);queue = run.catch(() => {});return run;}self.onmessage = async ({ data }) => {const { id, cmd, args } = data;try {const caps = await ready;if (cmd === "caps") return post({ id, result: caps });if (cmd === "stop") { stopRequested = true; return post({ id, result: true }); }const result = await exclusive(async () => {if (cmd === "unload") { await unloadAll(); return true; }if (cmd === "preload") {// Warm-up only; never replaces a model that's in use on small machines.if (!keepBoth && loaded.size) return false;await load(args.name, caps.f16);return true;}const fn = { florence, qwen }[cmd];stopRequested = false;return fn({ ...args, f16: caps.f16 });});post({ id, result });} catch (err) {console.error(err);
app.js+54-12
worker.js+30-21