Spaces:
Sleeping
Sleeping
Commit ·
3225df7
1
Parent(s): 94fe5c1
added URL hash for loaded score file.
Browse filesFiles changed (6)
- app.py+55-13
- assets/styles.json+1-1
- web/fluid-audio.js+27-9
- web/layout-fit.js+46-20
- web/score-player.css+9
- web/score-player.js+90-22
379 unmodified lines38038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542685 unmodified lines5125135144744754765155165175185195205215225234804814824834844855245255264875275285295305 unmodified lines536537538499500539540541502542543544545170 unmodified lines716717718719720721722723379 unmodified lines const iv = setInterval(() => { if (tryMount()) clearInterval(iv); }, 200); setTimeout(() => clearInterval(iv), 20000); }
// Deep-link: if the URL carries #score=<file>, select that Score List entry on // first load (so a bookmarked/shared score opens directly). We strip the leading // emoji prefix (📄/✨) when comparing, and click the matching radio input — that // fires Gradio's .select handler, which loads the file into the editor exactly // as a manual click would. Poll until the radio list is populated. const stripPrefix = (s) => (s || '').replace(/^\\s*[\\u{1F4C4}\\u2728]\\s*/u, '').trim(); const m = (location.hash || '').match(/(?:^#|&)score=([^&]*)/); if (m) { const want = decodeURIComponent(m[1]); let tries = 0; const pick = () => { const labels = document.querySelectorAll('.score-list label'); if (!labels.length) { if (++tries < 100) setTimeout(pick, 150); return; } for (const lab of labels) { const span = lab.querySelector('span'); const text = stripPrefix(span ? span.textContent : lab.textContent); if (text === want) { const input = lab.querySelector('input'); if (input && !input.checked) input.click(); return; } } if (++tries < 40) setTimeout(pick, 150); // list may still be filling }; pick(); }}'''
# file-list selection -> write the chosen file into location.hash (#score=<file>) so# the URL deep-links to it. This is a js-ONLY listener (no python fn) running beside# the load_file handler; `value` is the selected radio label. Strip the emoji prefix# for a clean, shareable hash. Returning [] is fine — there are no outputs._JS_SELECT_HASH = '''function (value) { try { const name = (value || '').replace(/^\\s*[\\u{1F4C4}\\u2728]\\s*/u, '').trim(); if (name) history.replaceState(null, '', '#score=' + encodeURIComponent(name)); } catch (e) {} return [];}'''
85 unmodified lines Goal: Compose + Logs keep their natural height; the Score List | editor row fills the rest; a long score must NOT stretch the page (it scrolls inside the sheet panel instead). Gradio's deep wrapper nesting makes pure-CSS flex height propagation unreliable, so the panel heights are driven by a small ResizeObserver in web/layout-fit.js (sets --ls-fill-h on :root = viewport − the panels above the fill row). These rules consume that variable. */ propagation unreliable, so the panel heights are driven from JS in web/layout-fit.js, which sets --ls-fill-h (bottom row) and --ls-sheet-h (sheet panel) on :root. IMPORTANT: those are plain pixel values, NOT 100vh — when this app is embedded in an auto-height iframe (Hugging Face Spaces), any 100vh/viewport reference feeds back into the iframe's growing height and the page scroll height runs away forever. layout-fit.js detects the iframe and uses fixed heights there. */#main-row { align-items: flex-start; /* don't stretch columns to each other's height */}/* Right (Sheet music) column: the score preview scrolls inside a viewport-capped height instead of growing the row. */#sheet-col { position: sticky; top: 8px;}/* Right (Sheet music) column: the score preview scrolls inside a bounded height (set by layout-fit.js) instead of growing the row / page. */#sheet-col .ls-score-root { height: calc(100vh - 110px); height: var(--ls-sheet-h, 720px); min-height: 320px;}#sheet-col .ls-preview {5 unmodified lines display: flex; flex-direction: column;}/* The bottom Score List | editor row gets the height left under Compose + Logs, computed by layout-fit.js into --ls-fill-h (with a sane fallback + floor). *//* The bottom Score List | editor row gets a bounded height from layout-fit.js (--ls-fill-h); never a viewport unit (see the iframe note above). */#compose-col > .lp-fill { height: var(--ls-fill-h, 420px); height: var(--ls-fill-h, 460px); min-height: 360px;}#compose-col > .lp-fill > .column,170 unmodified lines lambda: gr.update(value='Generate'), None, outputs=[gen_btn], cancels=[gen_event], ).then(None, None, None, js=_JS_GEN_END) file_list.select(load_file, inputs=[file_list, store], outputs=[editor]) # separate js-only listener: mirror the selected file into location.hash for deep-linking file_list.select(None, inputs=[file_list], outputs=None, js=_JS_SELECT_HASH)
return demo
18 unmodified lines19202122222318 unmodified lines "Shostakovich, Dmitry" ], "periods": ["Baroque", "Classical", "Romantic", "Modern"], "genres": ["Keyboard", "Choral", "Chamber", "Orchestral"] "genres": ["Keyboard", "Art Song", "Chamber", "Orchestral"]}68 unmodified lines697071727372737475767775787980787981828384858687888990919222 unmodified lines11511611711111211811912012112212312412512612712812913011411513113213313413513613768 unmodified lines if (loaded) return Promise.resolve(); if (loadingPromise) return loadingPromise;
// Start the lightweight legacy piano fallback immediately so playback is // audible while the large FluidSynth soundfont downloads. Non-fatal on error. // 1) Load the lightweight legacy piano fallback FIRST and prioritise it, so // playback is audible as soon as possible. The large GM soundfont (gm.sf3, // ~40MB) only starts downloading once the fallback is ready — we don't want // the 40MB fetch competing for bandwidth with the small fallback font. var legacyPromise; if (legacy && legacy.WebAudio && legacy.WebAudio.empty && legacy.WebAudio.empty()) { legacy.loadPlugin({ soundfontUrl: SOUNDFONT_URL, api: 'webaudio' }) legacyPromise = legacy.loadPlugin({ soundfontUrl: SOUNDFONT_URL, api: 'webaudio' }) .then(function () { legacyReady = true; log('legacy piano fallback ready'); }) .catch(function (err) { console.warn('[LilyFluid] legacy fallback failed:', err); }); } else if (legacy) { legacyReady = true; } else { if (legacy) legacyReady = true; legacyPromise = Promise.resolve(); }
loadingPromise = (async function () { // 2) Wait for the fallback to finish before kicking off the heavy GM load. try { await legacyPromise; } catch (e) {}
audioCtx = new (window.AudioContext || window.webkitAudioContext)(); // libfluidsynth must be added before the worklet module. await audioCtx.audioWorklet.addModule(LIBFLUIDSYNTH_FILE);22 unmodified lines }
// Resume audio output; must be called from a user gesture (autoplay policy). async function resume () { if (audioCtx && audioCtx.state === 'suspended') { try { await audioCtx.resume(); } catch (e) {} } // CRITICAL: both the FluidSynth AudioContext AND the legacy fallback's WebAudio // context start suspended and can only be resumed *synchronously within the user // gesture*. So we must fire BOTH resume()/awaitWarmup() calls BEFORE the first // `await` — otherwise the second one runs in a later microtask, outside the gesture // activation, and the browser refuses to resume it (it hangs/rejects). That was the // "fallback plays but is silent" bug: only FluidSynth's context got resumed, the // legacy one stayed suspended so its buffer sources produced no sound. function resume () { var promises = []; if (audioCtx && audioCtx.state === 'suspended') { try { promises.push(audioCtx.resume()); } catch (e) {} } var WA = legacy && legacy.WebAudio; if (legacyReady && WA && WA.needsWarmup && WA.needsWarmup() && WA.awaitWarmup) { try { await WA.awaitWarmup(); } catch (e) {} if (legacyReady && WA && WA.awaitWarmup) { try { promises.push(WA.awaitWarmup()); } catch (e) {} } return Promise.all(promises).catch(function () {}); }
function noteOn (channel, note, velocity, timestamp) {123456345687810111213910111213141516171819202122181923242526272829303132333435363738394041424344454647294849503251525354553 unmodified lines59606162636465666768697071727344457475764977787980538182832 unmodified lines868788626364899091/* LilyScript layout fitter. * * Gradio's deep wrapper nesting makes pure-CSS flex height propagation unreliable * (a long score in the right panel, or the editor's own content, can blow out the * left column). So we compute the height available to the bottom "Score List | * editor" row in JS and expose it as the CSS variable --ls-fill-h on :root. * Sets two CSS variables on :root that drive the workspace panel heights: * --ls-fill-h height of the bottom "Score List | editor" row (left column) * --ls-sheet-h height of the right "Sheet music" preview panel * * --ls-fill-h = viewport_height - fillRow.top - bottom_gap * Two modes, because the embedding context decides what "fill the screen" means: * * i.e. the fill row gets exactly the space left under Compose + Logs, down to the * bottom of the viewport. score-player.css / app.py consume the variable. We * recompute on resize and whenever the left column's size changes (Logs expanding, * accordion toggle, fonts loading) via a ResizeObserver. * • Standalone (the app is the top-level page): size to the real viewport, so the * bottom row fills the space under Compose + Logs and the sheet panel fills the * window. Recompute on resize + when the left column changes (ResizeObserver). * * • Embedded in an auto-height iframe (Hugging Face Spaces wraps the Gradio app in * an iframe that grows to fit its content): here window.innerHeight / 100vh are * NOT stable — they track the iframe, which tracks the content, which we'd be * sizing from the viewport… an unbounded feedback loop (the page scroll height * grows forever). So when embedded we use FIXED pixel heights and install no * viewport/resize observers. Nothing references the viewport, so nothing loops. */(function () { 'use strict';
var BOTTOM_GAP = 16; // breathing room below the fill row var MIN_FILL = 360; // never collapse the editor/score-list below this var BOTTOM_GAP = 16; // breathing room below the fill row (standalone) var MIN_FILL = 360; // floor for the bottom row // Fixed heights used when embedded (no viewport to measure against). var EMBED_FILL_H = 460; // Score List | editor row var EMBED_SHEET_H = 720; // Sheet music preview
// True when running inside an iframe (HF Spaces, blog embeds, etc.). Accessing // window.top across origins throws — treat that as "embedded" too. var embedded = (function () { try { return window.self !== window.top; } catch (e) { return true; } })();
function setVar (name, px) { document.documentElement.style.setProperty(name, px + 'px'); }
function fillEl () { var col = document.getElementById('compose-col'); return col ? col.querySelector(':scope > .lp-fill') : null; }
// Standalone: derive the bottom row height from the live viewport. function recompute () { var fill = fillEl(); if (!fill) return; var top = fill.getBoundingClientRect().top; // viewport-relative var top = fill.getBoundingClientRect().top; // viewport-relative var avail = window.innerHeight - top - BOTTOM_GAP; if (avail < MIN_FILL) avail = MIN_FILL; document.documentElement.style.setProperty('--ls-fill-h', avail + 'px'); setVar('--ls-fill-h', avail); setVar('--ls-sheet-h', Math.max(320, window.innerHeight - 110)); }
var raf = null;3 unmodified lines }
function boot () { var col = document.getElementById('compose-col');
if (embedded) { // Fixed heights — no viewport reads, no observers, no loop. setVar('--ls-fill-h', EMBED_FILL_H); setVar('--ls-sheet-h', EMBED_SHEET_H); if (!col) setTimeout(boot, 300); // wait for Gradio to mount, then set once return; }
recompute(); window.addEventListener('resize', schedule); // observe the left column so Logs growth / accordion toggles re-fit var col = document.getElementById('compose-col'); if (col && window.ResizeObserver) { var ro = new ResizeObserver(schedule); ro.observe(col); // also observe the two fixed blocks directly (their height drives fill.top) // the two fixed blocks (Compose, Logs) drive the fill row's top var fixed = col.querySelectorAll(':scope > .lp-fixed'); for (var i = 0; i < fixed.length; i++) ro.observe(fixed[i]); } // Gradio mounts asynchronously; retry a few times until #compose-col exists. if (!col) setTimeout(boot, 300); }
2 unmodified lines } else { boot(); } // a late pass after fonts/score player settle setTimeout(recompute, 1200); console.log('[layout-fit] loaded'); if (!embedded) setTimeout(recompute, 1200); // late pass after fonts/player settle console.log('[layout-fit] loaded (embedded=' + embedded + ')');})();60 unmodified lines61626364656667686970717273747560 unmodified lines max-width: 100%; height: auto;}/* Stacked Verovio pages (a long score paginates into several SVGs). Each page is a block so they stack vertically; a small gap separates pages. */.ls-svg .ls-svg-page { display: block; margin: 0 auto 8px;}.ls-svg .ls-svg-page:last-of-type { margin-bottom: 0;}/* Playback cursor: a vertical line tracking the currently-sounding note. */.ls-cursor { position: absolute;91 unmodified lines92939495969798959910010197989910010210210310410510610710810911011111211311411526 unmodified lines14214314413513614514614714814913815015115215315415515687 unmodified lines244245246232233234235236247248249250251252253254255256257258259238239260261262263264265266267268269270271272273274154 unmodified lines4294304314324334344354364374384394 unmodified lines4444454464104474484494504514524534544554564574584594604614624634644654664674124684694704714724734744754764772 unmodified lines48048148242342442542648348448548648748848949049149249349449549649791 unmodified lines return { mei, measureCount: (doc.measures && doc.measures.length) || 1, staffCount }; }
// Inject one or more page SVGs, stacked vertically. Verovio paginates a long score // into multiple pages (getPageCount); rendering only page 1 truncates the score, so // we render every page and append them all. Element IDs are unique across pages, so // the playback cursor/highlight lookups (getElementById) still work. function injectSvg (svgString) { function injectSvg (svgStrings) { if (typeof svgStrings === 'string') svgStrings = [svgStrings]; const parser = new DOMParser(); const doc = parser.parseFromString(svgString, 'image/svg+xml'); if (doc.querySelector('parsererror')) { log('svg parse error'); return; } const svg = doc.querySelector('svg'); if (!svg) return; els.svg.innerHTML = ''; els.svg.appendChild(document.importNode(svg, true)); for (let i = 0; i < svgStrings.length; i++) { const doc = parser.parseFromString(svgStrings[i], 'image/svg+xml'); if (doc.querySelector('parsererror')) { log('svg parse error on page ' + (i + 1)); continue; } const svg = doc.querySelector('svg'); if (!svg) continue; const page = document.importNode(svg, true); page.classList.add('ls-svg-page'); page.style.display = 'block'; els.svg.appendChild(page); } // re-attach the playback cursor (innerHTML reset above removed it) if (els.cursor) { els.cursor.style.display = 'none'; els.svg.appendChild(els.cursor); } }26 unmodified lines setStatus('Rendering…', 'busy'); try { const { mei, measureCount, staffCount } = lylToMei(code); const pageHeight = Math.max(2000, Math.ceil(measureCount / 20) * 2000) * 2 * staffCount; tk.setOptions({ scale: 40, adjustPageHeight: true, pageWidth: 2100, pageHeight: pageHeight }); // Use a normal A4-ish page so Verovio lays the score out across pages; we then // render ALL pages and stack them (see injectSvg). adjustPageHeight trims each // page to its content so there are no big gaps between pages. tk.setOptions({ scale: 40, adjustPageHeight: true, breaks: 'auto', pageWidth: 2100, pageHeight: 2970 }); if (!tk.loadData(mei)) { setStatus('Verovio load failed', 'err'); return false; } injectSvg(tk.renderToSVG(1)); const pageCount = (tk.getPageCount && tk.getPageCount()) || 1; const pages = []; for (let pg = 1; pg <= pageCount; pg++) pages.push(tk.renderToSVG(pg)); injectSvg(pages); state.lastCode = code; state.lastMei = mei; setStatus('', '');87 unmodified lines }
async function play () { if (!state.player || !state.midiData || state.isPlaying || state.generating) return; // warm up / resume the audio backend (browser autoplay policy) inside the play // gesture before scheduling notes, so the opening notes aren't dropped on first // play. LilyFluidAudio.resume() resumes the FluidSynth AudioContext (and warms // the legacy fallback); fall back to the old WebAudio.awaitWarmup path. if (state.isPlaying || state.generating) return; // Don't start a silent walk-through: if no audio backend can sound yet (neither // the legacy piano fallback nor the full GM soundfont is ready), bail. The play // button is normally disabled in this state, but guard here too. var Af = state.audio && state.audio.MidiAudio; if (Af && Af.empty && Af.empty()) { return; } // Resume the audio backend FIRST, synchronously within the click gesture. The // browser's autoplay policy only lets us resume a suspended AudioContext while a // user-activation is in scope; if we first `await buildPlayer()` (async), the // activation is gone by the time we'd resume, so the context stays suspended and // no sound comes out. So kick resume() off now (don't await it yet). var A0 = state.audio && state.audio.MidiAudio; var resumeP = null; if (A0 && A0.resume) { try { await A0.resume(); } catch (e) {} } else { var WA = A0 && A0.WebAudio; if (WA && WA.awaitWarmup) { try { await WA.awaitWarmup(); } catch (e) {} } } if (A0 && A0.resume) { try { resumeP = A0.resume(); } catch (e) {} } else { var WA = A0 && A0.WebAudio; if (WA && WA.awaitWarmup) { try { resumeP = WA.awaitWarmup(); } catch (e) {} } } // The player may not be built yet: on a deep-link load the first render can run // before the audio backend finished initialising, so updatePlayerVisibility's // buildPlayer() returned early and was never retried (the editor text didn't // change afterwards to re-trigger render). Build it on demand here. if (!state.player || !state.midiData) { if (!(await buildPlayer())) return; // still can't build (no MEI/toolkit) → nothing to play } if (!state.player || !state.midiData) return; // now make sure the resume actually completed before scheduling notes if (resumeP) { try { await resumeP; } catch (e) {} } state.isPlaying = true; if (state.pausedTime > 0) { state.playStartTime = performance.now() - state.pausedTime;154 unmodified lines // GM soundfont loads (grand-piano fallback active), then a steady green 🎹✓ once // ready (left in place, no fade). FluidSynth-only; if the backend lacks the // loading/ready introspection (plain music-widgets MidiAudio) the badge stays hidden. // // This also gates the play button: until SOME backend can sound (the legacy piano // fallback OR the full GM soundfont — i.e. !empty()), play is disabled so the user // can't trigger a silent walk-through. The button enables the moment a backend is // audible and the badge turns green once the full GM font is ready. function startSfStatus () { var F = state.audio && state.audio.MidiAudio; if (!els.sf || !F || !F.ready || !F.loading) return; // not the fluid backend4 unmodified lines els.sf.classList.add('ready'); els.sf.title = 'Sound library ready — full instrument timbres'; } if (F.ready()) { markReady(); return; } // fast path (cached) // reflect current backend-audible state on the play button, and recover from a // build race: if a backend is now audible but the player wasn't built yet (the // first buildPlayer ran before audio was ready), build it now so play enables. function syncPlayEnabled () { if (!els.playBtn) return; var audible = F.empty ? !F.empty() : true; // any backend can sound if (audible && state.lastMei && !(state.player && state.midiData) && !state._buildingPlayer) { state._buildingPlayer = true; buildPlayer().then(function (ok) { state._buildingPlayer = false; if (ok) updateProgress(); }); } els.playBtn.disabled = !(audible && state.player && state.midiData); els.playBtn.title = audible ? 'Play' : 'Loading sound library…'; } syncPlayEnabled(); // keep polling until BOTH a backend is audible and the player is built (covers // the legacy-fallback window and the build race), and until the GM font is ready // (for the badge). Stop once everything's settled. var iv = setInterval(function () { if (F.ready()) { clearInterval(iv); state._sfInterval = null; markReady(); } syncPlayEnabled(); if (F.ready()) markReady(); if (F.ready() && state.player && state.midiData) { clearInterval(iv); state._sfInterval = null; } }, 200); state._sfInterval = iv; // safety: never poll forever setTimeout(function () { if (state._sfInterval) { clearInterval(state._sfInterval); state._sfInterval = null; } }, 60000); }
// Show the player bar only when: not generating, a score is rendered, audio2 unmodified lines if (!els.player) return; const show = !state.generating && !!state.lastMei; els.player.style.display = show ? '' : 'none'; if (show) buildPlayer().then(function (ok) { if (ok) updateProgress(); els.playBtn.disabled = !ok; }); if (show) { // disable play until a backend is audible AND the player is built; the // sf-status poller (startSfStatus) keeps this in sync as soundfonts load. if (els.playBtn) els.playBtn.disabled = true; buildPlayer().then(function (ok) { if (ok) updateProgress(); var F = state.audio && state.audio.MidiAudio; var audible = (F && F.empty) ? !F.empty() : true; els.playBtn.disabled = !(ok && audible); startSfStatus(); // keep enabling/badge in sync while soundfonts finish loading }); } }
// ---- mount + public API -------------------------------------------------app.py+55-13
assets/styles.json+1-1
web/fluid-audio.js+27-9
web/layout-fit.js+46-20
web/score-player.css+9
web/score-player.js+90-22