Spaces:
Sleeping
Sleeping
Commit ·
8565c15
1
Parent(s): e5a3bec
added i18n.
Browse filesFiles changed (6)
- README.md+12-2
- app.py+61-43
- lilyscript/lang.pyAdded+111
- requirements.txt+3
- web/score-player.css+30
- web/score-player.js+15-2
123455 unmodified lines1112131314151516171819202122232425---# https://huggingface.co/docs/hub/spaces-config-referencetitle: LilyScriptemoji: 🌼colorFrom: pink5 unmodified linespinned: falselicense: mitshort_description: A symbolic music AIGC app with Lilylet language---
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference# For ModelScopedomain:- sdtags:- music- symbolic_music- lilyletdatasets: []models:- kllambda/LilyNota---26 unmodified lines2728293031323233343533343536373839404172 unmodified lines1141151161141171181191201211223 unmodified lines126127128124125126127128129130129130131132133134135136137138139140141142143144145146147148149150151134 unmodified lines2862872882712892902732912922932943 unmodified lines29829930028330130230330415 unmodified lines3203213223053233243253262 unmodified lines329330331314315332333334335336337320338339340341324342343344345426 unmodified lines7727737747577757767777781 unmodified line7807817827657837847677857867697877887717897907737917927757767777937947957967797807817977987998007837848018028037867878048058067898078088098101 unmodified line81281381479781581681781881982080382182282382482582680982782882983083183281583383483583611 unmodified lines84884985083385185285385429 unmodified lines88488588686988788888989026 unmodified linesfrom lilyscript.generator import StreamingLilyletGeneratorfrom lilyscript.postprocess import postprocessfrom lilyscript.mask_monitor import MaskMonitor, load_blacklistfrom lilyscript.lang import T, LANG
HERE = os.path.dirname(os.path.abspath(__file__))# Model weights are pulled from the HuggingFace model repo `k-l-lambda/LilyNota`# at first use (the int8 + KV-cache ONNX bundle lives under its `onnx/` dir).# For local development, point LILYSCRIPT_MODEL_DIR at a local onnx dir to skip# the download.# Model weights are pulled from a model hub at first use (the int8 + KV-cache ONNX# bundle lives under its `onnx/` dir). The repo is configured via LILYSCRIPT_MODEL_REPO:# - "owner/name" -> HuggingFace Hub (default)# - "modelscope:owner/name" -> ModelScope hub (for users behind the GFW / in China)# For local development, point LILYSCRIPT_MODEL_DIR at a local onnx dir to skip the# download, or drop the bundle into the repo-local `models/` dir.HF_MODEL_REPO = os.environ.get('LILYSCRIPT_MODEL_REPO', 'k-l-lambda/LilyNota')HF_MODEL_SUBDIR = 'onnx' # weights + geometry + tokenizer live here in the repoMODEL_DIR = os.environ.get('LILYSCRIPT_MODEL_DIR') # set -> use this local dir instead of the hub72 unmodified lines '''Where the ONNX weights live, in priority order: 1. LILYSCRIPT_MODEL_DIR (explicit override, local dev), 2. the repo-local `models/` dir IF it holds the full weight bundle, 3. otherwise pull the `onnx/` bundle from the HF model repo. 3. otherwise pull the `onnx/` bundle from the configured model hub (HuggingFace by default; ModelScope when LILYSCRIPT_MODEL_REPO is prefixed with `modelscope:`). The tokenizer is NOT pulled — it's read from the app's own assets/ dir — so we only fetch the weight files.''' if MODEL_DIR:3 unmodified lines os.path.isfile(os.path.join(LOCAL_MODEL_DIR, name)) for name in required): LOG.info('using local model weights in %s', LOCAL_MODEL_DIR) return LOCAL_MODEL_DIR from huggingface_hub import snapshot_download LOG.info('downloading model weights from hf:%s (%s/) ...', HF_MODEL_REPO, HF_MODEL_SUBDIR) local = snapshot_download( repo_id=HF_MODEL_REPO, allow_patterns=[f'{HF_MODEL_SUBDIR}/patch_kv_int8.onnx', f'{HF_MODEL_SUBDIR}/token_kv_int8.onnx', f'{HF_MODEL_SUBDIR}/wte.npy', f'{HF_MODEL_SUBDIR}/geometry.json'], ) # Only the four weight files under `onnx/` are needed (the tokenizer is local). patterns = [f'{HF_MODEL_SUBDIR}/{name}' for name in required] # Dispatch on the `modelscope:` prefix. Both hubs' snapshot_download share the # `allow_patterns` semantics (glob over repo-relative paths) and return the local # snapshot root, so the `onnx/` subdir join below is the same for either backend. if HF_MODEL_REPO.startswith('modelscope:'): repo_id = HF_MODEL_REPO[len('modelscope:'):] try: from modelscope.hub.snapshot_download import snapshot_download except ImportError as e: raise RuntimeError( 'LILYSCRIPT_MODEL_REPO is set to a modelscope: repo but the modelscope ' 'package is not installed. Run `pip install modelscope` (see requirements.txt).' ) from e LOG.info('downloading model weights from modelscope:%s (%s/) ...', repo_id, HF_MODEL_SUBDIR) local = snapshot_download(repo_id, allow_patterns=patterns) else: from huggingface_hub import snapshot_download LOG.info('downloading model weights from hf:%s (%s/) ...', HF_MODEL_REPO, HF_MODEL_SUBDIR) local = snapshot_download(repo_id=HF_MODEL_REPO, allow_patterns=patterns) return os.path.join(local, HF_MODEL_SUBDIR)
134 unmodified lines # progress on the Generate button label: by measures (completed `|` # separators vs target) when a measure count was requested, else by patches. if meas: btn_label = 'Generating… %d/%d' % (min(raw.count('|'), meas), meas) btn_label = T('generating') % (min(raw.count('|'), meas), meas) else: btn_label = 'Generating… %d/%d' % (max(0, n_yields - 1), mp) btn_label = T('generating') % (max(0, n_yields - 1), mp) # The log streams every patch (raw text). The editor, however, must stay # syntactically valid: only sync it at a measure boundary — i.e. when the # accumulated text ends with the measure separator `|` (so it never shows a3 unmodified lines yield _log_panel(raw), editor_update, gr.update(), store, gr.update(), gr.update(value=btn_label) except Exception as e: LOG.exception('generation failed: %s', e) yield _log_panel(raw), pretty, gr.update(), store, gr.update(), gr.update(value='Generate') yield _log_panel(raw), pretty, gr.update(), store, gr.update(), gr.update(value=T('generate')) return
# timing: the stream yields once for prefill + once per generated patch, so the15 unmodified lines # randomize the seed slider for the next run (the file above already used the # seed this generation ran with, so naming is unaffected) next_seed = random.randint(0, 2147483647) yield _log_panel(raw), pretty, gr.update(choices=list(store.keys()), value=label), store, gr.update(value=next_seed), gr.update(value='Generate') yield _log_panel(raw), pretty, gr.update(choices=list(store.keys()), value=label), store, gr.update(value=next_seed), gr.update(value=T('generate'))
def load_file (label, store):2 unmodified lines
SHEET_PLACEHOLDER = '''<div id="ls-score" class="ls-score-mount" style="height:100%;min-height:600px;"> <div style="display:flex;align-items:center;justify-content:center;height:100%;<div id="ls-score" class="ls-score-mount" style="height:100%%;min-height:600px;"> <div style="display:flex;align-items:center;justify-content:center;height:100%%; min-height:600px;border:1px dashed #c9c9c9;border-radius:8px;color:#999; font-family:sans-serif;text-align:center;"> <div> <div style="font-size:42px;margin-bottom:8px;">🎼</div> <div>Loading score renderer…</div> <div>%s</div> </div> </div></div>'''''' % T('loading_renderer')
# Static-file URL prefix Gradio serves allowed_paths under (verified at 6.18.0).426 unmodified lines examples = load_library()
with gr.Blocks(title='LilyScript') as demo: gr.Markdown('## 🎼 LilyScript — symbolic music generation with Lilylet') gr.Markdown(T('app_title')) store = gr.State(examples)
with gr.Row(elem_id='main-row'):1 unmodified line with gr.Column(scale=5, elem_id='compose-col'): # (1) compose params, with (2) the collapsible run log stacked below with gr.Group(elem_classes=['lp-fixed']): gr.Markdown('## Compose') gr.Markdown(T('compose')) with gr.Group(): gr.Markdown('- Style Options') gr.Markdown(T('style_options')) with gr.Row(): composer = gr.Dropdown(label='composer', choices=COMPOSERS, value='', composer = gr.Dropdown(label=T('composer'), choices=COMPOSERS, value='', allow_custom_value=True) period = gr.Dropdown(label='period', choices=PERIODS, value='', period = gr.Dropdown(label=T('period'), choices=PERIODS, value='', allow_custom_value=True) genre = gr.Dropdown(label='genre', choices=GENRES, value='', genre = gr.Dropdown(label=T('genre'), choices=GENRES, value='', allow_custom_value=True) prompt = gr.Textbox(label='Metadata prompt', lines=3, value='', placeholder='extra metadata lines, e.g.\n[key "C major"]\n(optional)') gr.Markdown('- Length') prompt = gr.Textbox(label=T('metadata_prompt'), lines=3, value='', placeholder=T('metadata_placeholder')) gr.Markdown(T('length')) with gr.Row(): measures = gr.Number(label='Measures (0 = let model decide)', value=0, precision=0) max_patches = gr.Number(label='max patches', value=1024, precision=0) gr.Markdown('- Sampler') measures = gr.Number(label=T('measures'), value=0, precision=0) max_patches = gr.Number(label=T('max_patches'), value=1024, precision=0) gr.Markdown(T('sampler')) with gr.Row(): temperature = gr.Slider(0.0, 2.0, value=1.0, step=0.05, label='temperature') seed = gr.Slider(0, 2147483647, value=42, step=1, label='seed') temperature = gr.Slider(0.0, 2.0, value=1.0, step=0.05, label=T('temperature')) seed = gr.Slider(0, 2147483647, value=42, step=1, label=T('seed')) with gr.Row(): gen_btn = gr.Button('Generate', variant='primary', elem_id='gen-btn') stop_btn = gr.Button('Stop', variant='stop', elem_id='stop-btn') gen_btn = gr.Button(T('generate'), variant='primary', elem_id='gen-btn') stop_btn = gr.Button(T('stop'), variant='stop', elem_id='stop-btn')
with gr.Accordion('Logs', open=True, elem_classes=['lp-fixed']): with gr.Accordion(T('logs'), open=True, elem_classes=['lp-fixed']): log = gr.Textbox(show_label=False, lines=10, max_lines=10, autoscroll=True, interactive=False, container=False)
1 unmodified line with gr.Row(equal_height=True, elem_classes=['lp-fill']): with gr.Column(scale=2, min_width=160): with gr.Group(): gr.Markdown('## Score List') gr.Markdown(T('score_list')) file_list = gr.Radio(show_label=False, choices=list(examples.keys()), value=None, interactive=True, container=False, elem_classes=['score-list']) with gr.Column(scale=5, elem_id='editor-col'): with gr.Group(): gr.Markdown('## Lilylet editor') gr.Markdown(T('lilylet_editor')) with gr.Row(elem_id='ls-editor-actions'): # Share button: copies the current deep-link URL (#score=<file>) # to the clipboard. js-only handler (_JS_SHARE) — see its comment # for the iframe URL/clipboard caveats. A transient hint span next # to it shows the copy result. share_btn = gr.Button('🔗 Share link', elem_id='ls-share-btn', share_btn = gr.Button(T('share_link'), elem_id='ls-share-btn', size='sm', scale=0, min_width=110) # Open the current editor text in lilylet-live-editor: builds a # ?code=<pako+base64> URL (matching the editor's share.ts) and # opens it in a new tab. Hidden via CSS until the editor has text # (toggled by _JS_RENDER, which receives the full text each change). live_btn = gr.Button('🎹 Open in live-editor', elem_id='ls-live-btn', live_btn = gr.Button(T('open_in_live_editor'), elem_id='ls-live-btn', size='sm', scale=0, min_width=150, elem_classes=['ls-hidden']) # Our own CodeMirror 6 editor (lyl-editor.bundle.js) mounts into # this div and bridges to the hidden textbox below — Gradio's11 unmodified lines # ---------------- RIGHT ---------------- with gr.Column(scale=6, elem_id='sheet-col'): with gr.Group(): gr.Markdown('## Sheet music') gr.Markdown(T('sheet_music')) gr.HTML(SHEET_PLACEHOLDER)
# ---- wiring ----29 unmodified lines # run never reaches its final yield, so it'd otherwise stay "Generating…"), # then lift the gate (js) so the player returns + button colors revert. stop_btn.click( lambda: gr.update(value='Generate'), None, outputs=[gen_btn], cancels=[gen_event], lambda: gr.update(value=T('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-linking123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111"""Server-side i18n for LilyScript's static UI text.
Language is fixed at startup by an environment variable (`zh` or `en`, default`en`). Unlike gr.I18n (which switches on the browser locale in the frontend),this resolves once on the server, so every visitor sees the language thedeployment was configured with. Only static UI strings are covered — generatedscores, logs, and JS-driven status text are not translated.
Which env var: `LANG_UI` takes precedence over the standard POSIX `LANG`. Use`LANG_UI` to set the UI language explicitly without being affected by thesystem locale (e.g. on a zh_CN host where `LANG=zh_CN.UTF-8` would otherwiseflip the UI to Chinese). `LANG` is honored as a fallback for convenience.
Usage: from lilyscript.lang import T gr.Markdown(T('compose')) # -> '## Compose' or '## 编排'
Missing keys fall back to English, then to the key itself (and log a warning),so a typo is visible rather than silently blank."""
import osimport logging
LOG = logging.getLogger('lilyscript')
# Supported languages; the first is the default when LANG is unset/unknown.SUPPORTED = ('en', 'zh')
def _resolve_lang (): raw = (os.environ.get('LANG_UI') or os.environ.get('LANG') or '').strip().lower() # LANG often looks like "en_US.UTF-8" / "zh_CN.UTF-8"; take the language subtag. code = raw.split('.')[0].split('_')[0] if code in SUPPORTED: return code return SUPPORTED[0]
LANG = _resolve_lang()
# Translation tables. Keys are stable identifiers; values are the rendered text# (Markdown prefixes like '## ' / '- ' are part of the value so call sites stay# identical to the original literals)._STRINGS = { 'en': { 'app_title': '## 🎼 LilyScript — symbolic music generation with Lilylet', 'compose': '## Compose', 'style_options': '- Style Options', 'composer': 'composer', 'period': 'period', 'genre': 'genre', 'metadata_prompt': 'Metadata prompt', 'metadata_placeholder': 'extra metadata lines, e.g.\n[key "C major"]\n(optional)', 'length': '- Length', 'measures': 'Measures (0 = let model decide)', 'max_patches': 'max patches', 'sampler': '- Sampler', 'temperature': 'temperature', 'seed': 'seed', 'generate': 'Generate', 'generating': 'Generating… %d/%d', 'stop': 'Stop', 'logs': 'Logs', 'score_list': '## Score List', 'lilylet_editor': '## Lilylet editor', 'share_link': '🔗 Share link', 'open_in_live_editor': '🎹 Open in live-editor', 'sheet_music': '## Sheet music', 'loading_renderer': 'Loading score renderer…', }, 'zh': { 'app_title': '## 🎼 LilyScript — 基于 Lilylet 的符号音乐生成', 'compose': '## 创作', 'style_options': '- 风格选项', 'composer': '作曲家', 'period': '时期', 'genre': '体裁', 'metadata_prompt': '元数据提示', 'metadata_placeholder': '额外的元数据行,例如\n[key "C major"]\n(可选)', 'length': '- 长度', 'measures': '小节数(0 = 由模型决定)', 'max_patches': '最大 patch 数', 'sampler': '- 采样器', 'temperature': '温度', 'seed': '随机种子', 'generate': '生成', 'generating': '生成中… %d/%d', 'stop': '停止', 'logs': '日志', 'score_list': '## 乐谱列表', 'lilylet_editor': '## Lilylet 编辑器', 'share_link': '🔗 分享链接', 'open_in_live_editor': '🎹 在 live-editor 中打开', 'sheet_music': '## 乐谱', 'loading_renderer': '正在加载乐谱渲染器…', },}
def T (key): """Translate a UI string key into the configured language.""" table = _STRINGS.get(LANG, _STRINGS['en']) if key in table: return table[key] # fall back to English, then to the raw key (visible, so typos surface) if key in _STRINGS['en']: return _STRINGS['en'][key] LOG.warning('i18n: missing key %r (lang=%s)', key, LANG) return key1 unmodified line2345671 unmodified lineonnxruntimenumpyhuggingface-hub# Optional: only needed when LILYSCRIPT_MODEL_REPO is set to a `modelscope:owner/name`# repo (downloads weights from ModelScope instead of HuggingFace). Uncomment to enable.# modelscope133 unmodified lines134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169133 unmodified lines#ls-score .ls-btn:hover:not(:disabled) { border-color: #8aa; background: #f0f6ff; }#ls-score .ls-btn:disabled { opacity: 0.4; cursor: not-allowed; }
/* Loading state on the play button: while the sound library / MIDI player is still loading, hide the ▶ glyph and spin a small ring in its place. Kept fully opaque (overriding :disabled's dim) so the animation reads as "working", not just greyed. The button stays disabled (cursor: wait) — clicking does nothing until ready. */#ls-score .ls-btn.ls-loading { opacity: 1; cursor: wait; color: transparent; /* hide the ▶ text glyph without reflow */ position: relative;}#ls-score .ls-btn.ls-loading::after { content: ''; position: absolute; width: 14px; height: 14px; border: 2px solid #c9c9d2; border-top-color: #7c5cff; /* accent matches the progress fill */ border-radius: 50%; animation: ls-spin 0.7s linear infinite;}@keyframes ls-spin { to { transform: rotate(360deg); }}/* Respect reduced-motion: pulse the ring opacity instead of spinning. */@media (prefers-reduced-motion: reduce) { #ls-score .ls-btn.ls-loading::after { animation: ls-sf-pulse 1.4s ease-in-out infinite; }}
#ls-score .ls-time { font-family: ui-monospace, Consolas, monospace; font-size: 12px;133 unmodified lines134135136137138139140141142143144145337 unmodified lines48348448548648748848949049149249318 unmodified lines512513514504515516517518519520509521522523524525133 unmodified lines // Render lyl -> SVG. Returns true on success. Does NOT touch the MIDI player // (that is gated separately on generation state). async function render (code) { // Guard: render may be called (e.g. by the page's initial-render poll on // reload/deep-link) before mount() has built the player DOM, so els.svg is // still undefined. Bail quietly — the caller's poll retries until mount is // done. (Without this, injectSvg's `els.svg.innerHTML = ''` throws // "Cannot set properties of undefined".) if (!els.svg) { log('render before mount — skipping'); return false; } const tk = await initVerovio(); if (!tk) { setStatus('Verovio not ready', 'err'); return false; } code = (code || '').trim();337 unmodified lines } els.playBtn.disabled = !(audible && state.player && state.midiData); els.playBtn.title = audible ? 'Play' : 'Loading sound library…'; // While no backend can sound yet (or the player is still building), show an // animated spinner on the play button instead of ▶, so the loading state // reads clearly rather than as a plain greyed button. (CSS: .ls-btn.ls-loading) var loading = !(audible && state.player && state.midiData); els.playBtn.classList.toggle('ls-loading', loading); } syncPlayEnabled(); // keep polling until BOTH a backend is audible and the player is built (covers18 unmodified lines 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; if (els.playBtn) { els.playBtn.disabled = true; els.playBtn.classList.add('ls-loading'); } buildPlayer().then(function (ok) { if (ok) updateProgress(); var F = state.audio && state.audio.MidiAudio; var audible = (F && F.empty) ? !F.empty() : true; var ready = ok && audible; els.playBtn.disabled = !(ok && audible); els.playBtn.disabled = !ready; els.playBtn.classList.toggle('ls-loading', !ready); startSfStatus(); // keep enabling/badge in sync while soundfonts finish loading }); }README.md+12-2
app.py+61-43
lilyscript/lang.pyAdded+111
requirements.txt+3
web/score-player.css+30
web/score-player.js+15-2